超级简单的Chrome扩展程序没有为按钮onclick事件添加addEventListener。

18

所以我正在测试创建一个Chrome扩展程序。 我知道使用Manifest v2时,popup.html中不能有JavaScript代码。 所以,我已将JavaScript代码移动到一个单独的文件popup.js中。

我试图在弹出窗口中放置一个简单的按钮,用于调用“hello world”警告,但它并没有起作用。

此外,Chrome的检查元素调试器没有显示任何错误。

popup.html

<html>
    <head>
        <title>Test</title>
        <script language='javascript' src='popup.js'></script>
    </head>
    <body>
        <form name='testForm'>
            <input type='button' id='alertButton' value='click me'>
        </form>
    </body>
</html>

弹出窗口.js

function myAlert(){
    alert('hello world')
}

window.onload = function(){
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('alertButton').addEventListener('onclick', myAlert);
    }); 
}

manifest.json

{
  "manifest_version": 2,
  "name": "Test",
  "description": "Test Extension",
  "version": "1.0",

  "icons": { 
    "48": "icon.png"
   },

  "permissions": [
    "http://*/*", 
    "https://*/*"
  ],

  "browser_action": {
    "default_title": "This is a test",
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

有什么想法吗?

1个回答

20

只需删除 window.onload

function myAlert(){
    alert('hello world');
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('alertButton').addEventListener('click', myAlert);
});

1
谢谢!我还注意到我在事件监听器中使用了"onclick"而不是"click"作为事件。 哎呀! - LittleBobbyTables
谢谢......我也为此苦苦挣扎了两个小时。没想到要移除window.onload...再次感谢 :) - Nitin Bansal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接