将 JS 事件监听器添加到 Chrome 扩展程序弹出窗口
2019-10-23
9799
我正在构建一个 Chrome 扩展程序,在添加事件侦听器时遇到了一些问题。我想将其添加到弹出窗口中的按钮上。
这是 JS -
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('checkButton').onclick = grabLinks;
});
这是弹出窗口 HTML -
<!DOCTYPE html>
<html>
<head>
<script src="background.js"></script>
</head>
<body>
<h3>Duplink</h3>
<p>Check if a link is already on this page.</p>
<form>
URL: <input id="URL" type="text" name="URL"><br>
<input id='checkButton' type="submit" value="Submit">
</form>
<p>Link is:<span id="message"></span></p>
</body>
</html>
另外,这里是 manifest.json 以防万一 -
{
"name": "Duplink",
"version": "1.0",
"description": "Check for duplicate links on DotDash sites",
"manifest_version": 2,
"background": {
"scripts": [
"background.js",
"popup.js"],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html",
"default_title": "Duplink"
},
"permissions": [
"activeTab",
"storage"
]
}
当我解压扩展程序时,出现此错误。- 事件处理程序中的错误:TypeError:无法设置 null 的属性“onclick”
然后它不断重复此错误。- 未捕获的 TypeError:无法读取未定义的属性“addListener”
3个回答
使用 addEventListener 将事件绑定到按钮:
检查下面的代码:
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('checkButton');
btn.addEventListener('click', function() {
alert("button clicked");
});
});
Rishab
2019-10-23
您的
popup.js
应添加到
popup.html
中,而不是添加到后台脚本中。如下所示:
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
然后您的
popup.js
应放置在
popup.html
中:
<h3>Duplink</h3>
...
<p>Link is:<span id="message"></span></p>
<script src="popup.js"></script>
Toan Quoc Ho
2019-10-23
我弄清楚了一些事情!
我将输入类型更改为按钮以防止默认操作。(提交表单) -
<h3>Duplink</h3>
<p>Check if a link is already on this page.</p>
<form>
URL: <input id="URL" type="text" name="URL"><br>
<input id='checkButton' type="button" value="Submit">
</form>
<p>Link is:<span id="message"></span></p>
并将事件绑定到按钮。
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('checkButton');
btn.addEventListener('click', function() {
//Get URL from input
var URL = document.getElementById('URL').value;
//Get all links
var links = document.querySelectorAll('.article a');
//Convert Nodelist to Array
var linksArr = [];
links.forEach(node => linksArr.push(node.href))
//Compare Link to Array
var compareArr = linksArr.includes(URL);
//Alert if link exists on page, or not
if (compareArr === true) {
document.getElementById('message').innerHTML = " On the page - Don't Add Link";
}
else {
document.getElementById('message').innerHTML = ' Not on the page - Add Link';
}
});
});
Tbbd
2019-10-24