javascript 超简单的 Chrome 扩展程序不会向按钮 onclick 事件添加事件监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14801349/
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
Ultra simple Chrome Extension doesn't addEventListener to button onclick event
提问by LittleBobbyTables
So I'm testing out creating a chrome extension. I understand that with Manifest v2 you can't have javascript in popup.html. So, I've moved the javascript to a separate file, popup.js.
所以我正在测试创建一个 chrome 扩展。我知道使用 Manifest v2,您不能在 popup.html 中使用 javascript。因此,我已将 javascript 移至单独的文件 popup.js。
I'm trying to have a simple button in a popup that calls a hello world alert, but it simply isn't working.
我试图在弹出窗口中有一个简单的按钮来调用 hello world 警报,但它根本不起作用。
Moreover, Chrome's Inspect Element debugger doesn't show any error.
此外,Chrome 的 Inspect Element 调试器没有显示任何错误。
popup.html
弹出窗口.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
弹出窗口.js
function myAlert(){
alert('hello world')
}
window.onload = function(){
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('alertButton').addEventListener('onclick', myAlert);
});
}
manifest.json
清单文件.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"
}
}
Any ideas?
有任何想法吗?
回答by A. Rodas
Just remove window.onload
:
只需删除window.onload
:
function myAlert(){
alert('hello world');
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('alertButton').addEventListener('click', myAlert);
});