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

Event Listener Running Function Before The Element Is Clicked In Chrome Extension

本文关键字:运行 事件 功能 侦听器 元素 扩展 Chrome 程序 单击      更新时间:2023-09-26

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

我的 manifest.json 文件似乎工作正常,我没有收到任何错误,并且链接的每个页面以及图标.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"
}
}

这是我放在弹出窗口.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>

我的弹出窗口.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')}

当我单击扩展程序图标并且它甚至没有运行弹出窗口时,我所做的任何一种方式都会发出警报.html。我不知道我是否需要为其添加一个功能,但由于我是新手(我的第一个扩展),我真的不知道我是否应该添加一个特殊的 chrome 方法或其他东西。我已经浏览了谷歌开发页面,但它没有帮助。它只教会了我基础知识。

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

它应该是:

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

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

顺便说一句,在 addEventListener 中指定事件时,您不包括 on 前缀 - 它只是click .