javascript - Chrome 扩展程序弹出窗口不起作用,点击事件未处理

标签 javascript google-chrome button google-chrome-extension content-security-policy

我创建了一个 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 的值,并在每次单击扩展程序或按钮时将其加一

picture of the extension

最佳答案

您的代码无法正常工作,因为它违反了默认 Content Security Policy 。我创建了一个一分钟的截屏视频来显示问题所在:

screencast

首先,我展示了如何调试问题。右键单击弹出按钮,然后单击 "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/46741795/

相关文章:

javascript - Google Earth 的扩展,允许徒手和可拖动地标选择

javascript - Firebase 云函数 Cron 更新

Java Swing为一组按钮添加鼠标监听器(内部类)导致故障

css - Chrome 72 是否破坏了 css 背景 svgs 的 'data:image/svg+xml;utf8'?

html - 我的输入字段在 IE 上以内联方式呈现,但在 Chrome 和 Firefox 中以新行呈现。我该如何解决?

JavaScript 不适用于所有浏览器

iphone sdk-带有图像的 UIAlertView 按钮

javascript - 给HTML元素加上自己的属性可以吗?

javascript - 比较和匹配两个对象列表时防止结果列表重复

javascript - offsetHeight 在 Chrome 上不起作用