浏览器插件开发,JS 执行 click,提示 Content Security Policy 错误

该文章已生成可运行项目,

问题描述:

在chrome插件(V3版本)开发时,需要用代码模拟 a 元素的 click 事件,执行代码后,console提示错误:

Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

问题解决过程:

1. 查看 chrome extension 官方资料:

关于content-scripts的介绍链接

2. 以为是权限的问题,各种尝试没能消除 error,但是每次 click 的执行效果是有的。

3. 快要放弃的时候,google 到这篇文章:

javascript click function causes Content Security Policy error

我说 error 信息里面怎么有:“inline execution”,原来是我触发 a 元素的 click 事件,元素的属性 href="javascript:;" (我觉得浏览器错误的理解了代码的作用)。根据网页提示调整了代码(下面代码引用自原始网站,需要根据个人代码适当修改):

currencySelectorLink.href= '#' ;
currencySelectorLink.addEventListener("click", function(event) {
  event.preventDefault();  // Prevent default action (a following a link)
  }, false);

我的代码能正常执行,并且不提示错误。记录下来给需要的人,算是一个找答案的思路。

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值