超简单的Chrome扩展;t将EventListener添加到按钮onclick事件

Ultra simple Chrome Extension doesn't addEventListener to button onclick event

本文关键字:添加 EventListener 按钮 事件 onclick 简单 Chrome 扩展      更新时间:2023-09-26

所以我正在测试创建一个chrome扩展。我知道Manifest v2不能在popup.html中有javascript。所以,我把javascript移到了一个单独的文件popup.js.中

我试着在弹出窗口中有一个简单的按钮来调用hello世界警报,但它根本不起作用。

此外,Chrome的Inspect Element调试器没有显示任何错误。

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>

popup.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"
  }
}

有什么想法吗?

只需删除window.onload:

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