浏览器扩展因Content Security Policy(CSP)无法加载字体的问题咨询
浏览器扩展修改页面字体遭CSP拦截的解决方法
问题背景
我正在开发一款浏览器扩展,目标是修改页面字体。尝试通过content.js注入@import加载Google的Open Sans字体,但浏览器获取资源时失败,报错如下:
Content Security Policy: The page’s settings blocked the loading of a resource at https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500&display=swap (“style-src”).
不清楚该如何修改CSP或调整代码来解决这个问题。
测试环境:Firefox V105.0.1(64位)Windows 10
现有代码
manifest.json
{ "manifest_version": 2, "name": "Test-Extension", "version": "1.0.0", "content_scripts": [ { "all_frames": true, "matches": ["*"], "js": ["build/content.js"], "css": ["build/content.css"] } ] }
content.js
// content.js const style = document.createElement('style'); style.appendChild(document.createTextNode(`@import url(https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500&display=swap)`)); document.head.appendChild(style);
content.css
/* content.css */ *, html { font-family: 'Open Sans', sans-serif !important; }
解决方案
方案一:使用本地字体(最稳妥,不受页面CSP限制)
- 下载Open Sans对应字重的字体文件(推荐woff2格式),放到扩展目录的
fonts文件夹下 - 修改
manifest.json,添加web_accessible_resources字段,允许页面访问扩展内的字体文件 - 在
content.css中用@font-face加载本地字体,再设置全局字体样式
修改后的manifest.json:
{ "manifest_version": 2, "name": "Test-Extension", "version": "1.0.0", "content_scripts": [ { "all_frames": true, "matches": ["*://*/*"], "css": ["build/content.css"] } ], "web_accessible_resources": [ "fonts/*.woff2" ] }
修改后的content.css:
@font-face { font-family: 'Open Sans'; src: url('chrome-extension://__MSG_@@extension_id__/fonts/OpenSans-Light.woff2') format('woff2'); font-weight: 300; font-style: normal; } @font-face { font-family: 'Open Sans'; src: url('chrome-extension://__MSG_@@extension_id__/fonts/OpenSans-Regular.woff2') format('woff2'); font-weight: 400; font-style: normal; } @font-face { font-family: 'Open Sans'; src: url('chrome-extension://__MSG_@@extension_id__/fonts/OpenSans-Medium.woff2') format('woff2'); font-weight: 500; font-style: normal; } *, html { font-family: 'Open Sans', sans-serif !important; }
同时删除content.js中的动态注入代码,无需再加载外部样式。
方案二:调整扩展的CSP规则
在manifest.json中添加content_security_policy字段,允许加载Google字体的样式和字体资源:
{ "manifest_version": 2, "name": "Test-Extension", "version": "1.0.0", "content_security_policy": "style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;", "content_scripts": [ { "all_frames": true, "matches": ["*://*/*"], "css": ["build/content.css"] } ] }
注意:部分设置了严格CSP的页面可能仍然会拦截外部资源,因为页面自身的CSP优先级高于扩展的CSP,此方案不一定适用于所有场景。
内容的提问来源于stack exchange,提问作者Allstreamer_
相关产品推荐
相关产品推荐

