简体   繁体   中英

Unable to open a new tab using a button within a Chrome Extension popup

I'm trying to write a Chrome Extension popup that will have some options in it: based on the selected one, I'll have to generate a URL and load it in a new tab. I've tried almost all the solutions I've found, but I'm still unable to understand what I'm doing wrong. I've provided the details below.

manifest.json

{
    "name": "New Extension",
    "version": "1",
    "description": "New Extension",
    "manifest_version": 2,

    "browser_action": {
    "name": "New Extension",
    "default_popup": "popup.html",
    "default_icon": "icon.png"
    },

    "permissions": [ "tabs" , "<all_urls>"]
}

popup.html

<html>
<head>
  <link rel="stylesheet" href="style.css" type="text/css" />
  <script src="popup.js"></script>
</head>
<body style="width: 400px" bgcolor= "#FFFFFF">
    Operation:<input type="radio" name="operation" id="Google"     checked="checked">Google
    <input type="radio" name="operation" id="Yahoo">Yahoo<br/>
    <input type="button" name="btngenerate" id="btngenerate" value="Generate" />
</body>
</html>

popup.js

document.getElementById("btngenerate").addEventListener('click', function() {
    alert("in generate URL");
    var URL = "http://google.com";
    if (document.getElementById("yahoo").checked == true) 
        URL = "http://yahoo.com";
    chrome.tabs.create({url: URL});
});

When I try to execute this, I'm able to see the popup, but, when I click on "Generate", nothing happens. What's wrong with my code?

Chrome starts to parse your HTML file tag by tag and populates the DOM.

As soon as it encounters the <script> tag, it gets executed.

As a result, your code executes before #btngenerate exists in the DOM.

You need to wrap it in an event that will fire after the file is fully read and DOM is constructed:

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("btngenerate").addEventListener(/*...*/);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM