Chrome扩展弹出窗口不能正常工作,请单击事件没有处理 [英] The Chrome extension popup is not working, click events are not handled

查看:1679
本文介绍了Chrome扩展弹出窗口不能正常工作,请单击事件没有处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个JavaScript变量,当我按一下按钮就应该加1,但它没有发生。

I have created a JavaScript variable and when I click on the button it should increment by 1, but its not happening.

下面的的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"
  }
}

下面是code的html页面

Here is the code for the html page

<!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>

我要扩展到显示我的价值和一个每次我点击分机或按钮

I want the extension to show me the value of a and increment it by one each time I click on the extension or the button

推荐答案

您code不工作,因为它违反了默认的内容安全政策。我创建了一分钟截屏显示什么是错的:

Your code is not working because it violates the default Content Security Policy. I've created a screencast of one minute to show what's wrong:

首先,我展示了如何调试问题。在你的弹出按钮,单击鼠标右键,然后点击检查弹出。这样做之后,你将看到以下错误消息:

First, I've shown how to debug the problem. Right-click on your popup button, and click on "Inspect popup". After doing that, you will see the following error message:

拒绝了,因为它违反了以下内容安全策略的指令来执行内联脚本:脚本的src'自我'铬扩展资源:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

这说明你的code是不工作的,因为它违反了默认的CSP:内嵌的JavaScript将不执行。为了解决这个问题,你必须从你的HTML文件中删除所有内嵌的JavaScript,并把它放在一个单独的JS文件。

This explains that your code is not working, because it violates the default CSP: Inline JavaScript will not be executed. To solve the problem, you have to remove all inline JavaScript from your HTML file, and put it in a separate JS file.

的结果如下所示:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="demo">=a</p>
<button type="button" id="do-count">Count</button>
<script src="popup.js"></script>
</body>
</html>

popup.js

var a=0;
function count() {
    a++;
    document.getElementById('demo').textContent = a;
}
document.getElementById('do-count').onclick = count;

请注意,我把它换成的innerHTML 的textContent 。了解如何使用的textContent 而不是的innerHTML 当你打算改变的文字。在这个简单的例子也没关系,但在更复杂的应用,它可能成为在XSS形式的安全问题。

Note that I've replaced innerHTML with textContent. Learn to use textContent instead of innerHTML when you intend to change the text. In this simple example it does not matter, but in more complex applications, it might become a security issue in the form of XSS.

这篇关于Chrome扩展弹出窗口不能正常工作,请单击事件没有处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆