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/45122007/

相关文章:

javascript - 它是一个对象还是数组?

javascript - 如何对 AngularJS 生成的选择列表进行预选?

javascript - 抓取表格中无法在 html 中找到但只能在 Chrome>F12>Element 中找到的子元素

firefox - 如何撤销 Chrome 和 Firefox 中的给定权限?

android 网页链接的两个按钮

javascript - 无法使用 JavaScript 控制台调用按钮类

javascript - 如何使用正则表达式删除字符串中的方括号?

html - css 菜单中除最后一个子元素外的所有子元素都向左移动一个像素

java - Android:如果我将 Switch OnClickListener 放在 FragmentActivity 上,我的应用程序将无法运行

c# - 将鼠标悬停在 ASP.NET 按钮上时显示注释