javascript addEventListener 在 chrome 扩展中使用时不触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9611937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:12:58  来源:igfitidea点击:

addEventListener not triggering when used in a chrome extension

javascriptjsongoogle-chromejavascript-eventsgoogle-chrome-extension

提问by Dbz

I'm trying to make a chrome extension that will search different cache databases for a given page. However, it's not working as I expect it to.

我正在尝试制作一个 chrome 扩展,它将搜索给定页面的不同缓存数据库。但是,它并没有像我期望的那样工作。

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">

var x;
var img = document.getElementsByTagName("img");
for(x in img) {
    img[x].addEventListener('click',openPage, false);
}

function openPage(event) {
    alert("clicked");
    var e = event.target;
    switch(e.alt) {
    case "WayBack Machine":
        chrome.tabs.update(tab.id, { url: "http://wayback.archive.org/web/*/" + tab.url });
        break;

    case "Google Cache":
        if(tab.url.substring(0, 5) == "http:")
            chrome.tabs.update(tab.id, { url: 'http://webcache.googleusercontent.com/search?q=cache:' + tab.url.substr(7) });
        else if(tab.url.substring(0,6) == "https:")
            chrome.tabs.update(tab.id, { url: 'http://webcache.googleusercontent.com/search?q=cache:' + tab.url.substr(8) });
        break;

    case "Yahoo Cache":
        // Need the yahoo cache url
        break;

    case "Bing Cache":
        chrome.tabs.update(tab.id, { url: "http://cc.bingj.com/cache.aspx?q=" + tab.url + "&d=4572216504747453&mkt=en-US&setlang=en-US&w=802790a9,218b61b8" });
        break;

    case "Gigablast":
        chrome.tabs.update(tab.id, { url: "http://www.gigablast.com/get?q=" + tab.url + "&c=main&d=70166151696&cnsp=0" });
        break;

    case "CoralCDN":
        chrome.tabs.update(tab.id, { url: tab.url + ".nyud.net" });
        break;

    default: // Webcite
        // Need to send a request, this won't do
        chrome.tabs.update(tab.id, { url: "http://webcitation.org/query" });
        break;
    }

}

</script>
</head>

<body>
<img src="Google Cache.png", alt="WayBack Machine" class="button" id="WayBack Machine" height ="40px" />
<img src="Google Cache.png", alt="Google Cache" class="button" id="Google Cache" height ="40px" />
<img src="Google Cache.png", alt="Yahoo Cache" class="button" id="Yahoo Cache" height ="40px" />
<img src="Google Cache.png", alt="Bing Cache" class="button" id="Bing Cache" height ="40px" />
<img src="Google Cache.png", alt="Gigablast" class="button" id="Gigablast" height ="40px" />
<img src="Google Cache.png", alt="CoralCDN" class="button" id="CoralCDN" height ="40px" />
<img src="Google Cache.png", alt="Webcite" class="button" id="Webcite" height ="40px" />
</body>

</html>

However, it does not even alert(); When I try the code in a jsfiddle.net, it works: http://jsfiddle.net/RZ2wC/

但是,它甚至没有 alert(); 当我在 jsfiddle.net 中尝试代码时,它可以工作:http: //jsfiddle.net/RZ2wC/



Here is my manifest.json:

这是我的 manifest.json:

{
  "name": "gCache",
  "version": "1.1.5",
  "description": "View the Google Cache of a page",

  "browser_action": {
    "default_icon": "icon.png",
    "default_text": "Google Cache version of this page",
    "default_popup": "cacheList.html"
  },

  "permissions": [
    "tabs"
  ]
}


Any help would be greatly appreciated. On this question and any bugs that you see in my code that I haven't gotten to yet. Many thanks!

任何帮助将不胜感激。关于这个问题以及您在我的代码中看到但我还没有解决的任何错误。非常感谢!

采纳答案by x29a

Debugging your sample via right-click on browserAction button and selecting "inspect popup" (this will lead you to "further bugs") showed, that you are trying to add an event to "0"

通过右键单击 browserAction 按钮并选择“检查弹出窗口”(这将导致“进一步的错误”)来调试您的示例显示,您正在尝试将事件添加到“0”

Uncaught TypeError: Object 0 has no method 'addEventListener'

The reason for this is IMHO that the page has not yet loaded but you are trying to access the DOM of the images.

原因是恕我直言,页面尚未加载,但您正在尝试访问图像的 DOM。

Try wrapping your addEvents in a function like

尝试将您的 addEvents 包装在类似的函数中

function magic() {
  var x;
  var img = document.getElementsByTagName("img");
  for(x=0; x < img['length']; ++x) {
    img[x].addEventListener('click',openPage, false);
  }
}

and call it from the body-onload event (or $(document).ready() if using jQuery)

并从 body-onload 事件中调用它(如果使用 jQuery,则为 $(document).ready())

<body onload="magic()">
<img src="Google Cache.png", alt="WayBack Machine" class="button" id="WayBack Machine" height ="40px" />
<img src="Google Cache.png", alt="Google Cache" class="button" id="Google Cache" height ="40px" />
...
</body>

回答by Rexxars

Try to include your javascript as external files, referenced from the bottom of your page (right before you close the body).

尝试将您的 javascript 作为外部文件包含在内,从您的页面底部引用(就在您关闭正文之前)。

Also, to make sure the DOM has actually been loaded, wrap it in a DOMContentLoaded-listener:

此外,为了确保 DOM 已实际加载,请将其包装在 DOMContentLoaded-listener 中:

document.addEventListener('DOMContentLoaded', function() {
    /* Add your event listeners here */
});