如何为浏览器扩展正确设置Content Security Policy?配置后仍报错怎么办
报错的核心原因
CSP配置语法错误导致自定义规则未生效
Chrome扩展Manifest V2中,要通配允许所有HTTPS协议来源的脚本,正确写法是https:(末尾必须带冒号),你配置中写的https会被浏览器识别为名为https的单独主机,不属于合法的协议通配规则。浏览器检测到你的CSP配置存在语法问题后,会直接忽略你的自定义配置,回退到Manifest V2的默认CSP规则:script-src 'self',这也是你报错日志里生效规则是script-src 'self'的原因。如果是在content script中加载外部脚本,扩展CSP不生效
Manifest中配置的CSP仅作用于扩展自身的上下文(包括popup页面、background页面、扩展自有HTML页面),不会作用于content script注入的目标站点页面。如果你是在content script中向页面DOM插入了Google API的script标签,那加载该脚本时遵循的是shopee站点自身的CSP规则,和你扩展的CSP配置无关,也会触发拦截。
解决方案
- 若你是在扩展自有上下文(popup/background)中加载Google API:修正CSP配置即可,修改后的配置如下:
{ "manifest_version":2, "name": "Hyperfect", "version": "1.0", "content_security_policy": "script-src 'self' 'unsafe-inline' https:; style-src 'self' 'unsafe-inline';", "description": "Simple shopee extension for Hyperfect", "browser_action":{"default_popup": "src/popup.html"}, "content_scripts":[{"matches":["https://seller.shopee.com.my/portal/sale/order/*"],"run_at": "document_end","js":["src/script/jquery-3.6.0.js","src/script/content.js"]}], "permissions":["activeTab"], "background":{"scripts":["src/script/event.js"],"persistent": false} }
- 若你是在content script中需要调用Google API:不要直接在页面插入外部script标签,改为在background页面加载Google API,通过扩展内置的消息传递机制(
chrome.runtime.sendMessage/chrome.runtime.onMessage)让content script和background通信,由background完成API调用后返回结果给content script,绕开目标站点的CSP限制。
内容的提问来源于stack exchange,提问作者new guy
相关产品推荐
相关产品推荐

