我创建了一个 JavaScript 变量,当我单击按钮时,它应该增加 1,但它没有发生。
这是 manifest.json
。
{
"name":"Facebook",
"version":"1.0",
"description":"My Facebook Profile",
"manifest_version":2,
"browser_action":{
"default_icon":"google-plus-red-128.png",
"default_popup":"hello.html"
}
}
这是html页面的代码
<!DOCTYPE html>
<html>
<head>
<script>
var a=0;
function count()
{
a++;
document.getElementById("demo").innerHTML=a;
return a;
}
</script>
</head>
<body>
<p id="demo">=a</p>
<button type="button" onclick="count()">Count</button>
</body>
</html>
我希望扩展程序向我显示 a 的值,并在每次单击扩展程序或按钮时将其加一
最佳答案
您的代码无法正常工作,因为它违反了默认 Content Security Policy 。我创建了一个一分钟的截屏视频来显示问题所在:
首先,我展示了如何调试问题。右键单击弹出按钮,然后单击 "Inspect popup" 。执行此操作后,您将看到以下错误消息:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".
这说明您的代码无法正常工作,因为它违反了默认 CSP:Inline JavaScript will not be executed 。要解决这个问题,您必须从 HTML 文件中删除所有内联 JavaScript,并将其放入单独的 JS 文件中。
结果如下所示:
hello.html
(弹出页面)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="demo">=a</p>
<button type="button" <b>id="do-count"</b>>Count</button>
<b><script src="popup.js"></script></b>
</body>
</html>
popup.js
var a=0;
function <b>count</b>() {
a++;
document.getElementById('demo').<b>textContent</b> = a;
}
<b>document.getElementById('do-count').onclick = count;</b>
请注意,我已将 innerHTML
替换为 textContent
。当您打算更改文本时,请学习使用 textContent
而不是 innerHTML
。在这个简单的示例中,这并不重要,但在更复杂的应用程序中,它可能会成为 XSS 形式的安全问题。
关于javascript - Chrome 扩展程序弹出窗口不起作用,点击事件未处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45122007/