在Chrome扩展中单击元素之前的事件侦听器运行功能

时间:2013-09-05 13:47:13

标签: javascript html google-chrome google-chrome-extension event-handling

我最近一直在为Google Chrome创建扩展程序,清单版本2表示我无法使用事件处理程序(onclick,onmouseover,ondblclick等)INSIDE我创建的html文件。它确实说我可以在链接到它的脚本上创建它们。唯一的问题是,当我单击图标时,该功能在我单击实际的div元素之前运行。我真的很困惑我做错了所以我尝试了几个方法:

我的manifest.json文件似乎工作正常,我没有得到任何错误,每个页面链接工作,以及icon.png文件。

{
    "name" : "Test",
    "version" : "1.0",
    "manifest_version" : 2,
    "description" : "Trying it out",
    "browser_action" : {
"default_icon" : "icon.png",
"defalut_title" : "Test",
"default_popup" : "popup.html"
},
    "chrome_url_overrides" : {
"newtab" : "newtab.html"
}
}

以下是我在popup.html文件中添加的内容:

<html>
<head></head>
<body>
<div id="submitButton">Submit!</div>
</body>
</html> <!-- The rest of the code is unnecessary since it is not used as for now -->
<script type="text/javascript" src="popup.js"></script>

我的popup.js文件具有以下功能:

var sButton = document.getElementById('submitButton');
sButton.addEventListener('onclick',alert('This is not supposed to happen until I click the div'),false);

//I also put the alert in a function like so: function() {alert('what it said')}

在我注意到这种方式不起作用之后,我选择了这个:

sButton.onclick = function() {alert('same thing')}

当我点击扩展程序图标时,我所做的任何一种方式都会发出警报,甚至没有运行popup.html。我不知道是否需要添加一个函数,但由于我是新手(我的第一个扩展名),我真的不知道我是否应该添加一个特殊的chrome方法或其他东西。我查看了Google Dev页面,但没有帮助。它只教我基础知识。

任何帮助将不胜感激,提前谢谢。

1 个答案:

答案 0 :(得分:1)

应该是:

sButton.addEventListener('click',
    function() {alert('This is not supposed to happen until I click the div'),false);});

您正在调用alert()并将结果传递给addEventListener。您需要传递一个调用alert()的函数。

顺便说一句,在addEventListener中指定活动时,您不会包含on前缀 - 它只是click

相关问题