Chrome扩展脚本未在弹出窗口中运行(无法调用未定义的方法'addListener')

时间:2013-12-13 17:48:04

标签: javascript google-chrome javascript-events google-chrome-extension popup

所以标题说明了一切。我不知道为什么我会收到此错误。

这是我现有的代码。

的manifest.json

{
    "manifest_version": 2,
    "name": "Helper",
    "version": "1.0.0",
    "description": "A helper program",
    "icons": {
        "16": "images/icon16.png",
        "48": "images/icon48.png",
        "128": "images/icon128.png"
    },
    "browser_action": {
        "default_icon": {
            "19": "images/icon19.png",
            "38": "images/icon38.png"
        },
        "default_title": "Helper",
        "default_popup": "popup.html"
    },
    "author": "ME",
    "permissions": [
        "tabs", "http://libraries.com/*"
    ]
}

popup.html

<html>
    <head>
        <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />    
        <title>Helper Popup</title>
        <link rel="stylesheet" href="popup.css" />
        <script type="text/javascript" src="eventpage.js"></script>
    </head>
    <body>
        <p><span id="option1" class="options">Automated Scanning</span></p>
    </body>
</html>

eventpage.js

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("option1").onClicked.addListener(function(tab) {
        chrome.tabs.executeScript(null, {file: "QCScript.js"});
        window.close();
    });
});

目前,当我在扩展程序中加载弹出窗口时,它看起来很好,但会生成错误:

Uncaught TypeError: Cannot call method 'addListener' of undefined eventpage.js:2

我在某处读到你需要将它添加到window.onload,但如果我将eventpage.js更改为阅读...

window.onload = function() {
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById("option1").onClicked.addListener(function(tab) {
            chrome.tabs.executeScript(null, {file: "QCScript.js"});
        });
    });
};

错误确实消失了,但点击按钮什么都不做。它应与当前选项卡连接,自动单击图像以进行质量控制。当我将QCScript.js的内容复制/粘贴到控制台时,它可以很好地工作。

1 个答案:

答案 0 :(得分:0)

而不是.onClicked.addListener,您应该使用:

document.getElementById("option1").addEventListener( 'click', function() { ...