动态注入内容脚本无法访问扩展资源,文档描述是否有误?
Chrome扩展MV3动态注入内容脚本访问资源报错问题解析
问题原因
文档描述没出错,静态声明在manifest里的内容脚本确实不受web_accessible_resources限制,但你用的是动态注入的内容脚本——这种脚本运行在页面自身的上下文里,不属于扩展的隔离上下文,调用chrome.runtime.getURL时会返回无效路径chrome-extension://invalid/,直接导致fetch请求失败。
解决办法
方法一:提前传递资源路径(推荐)
在触发注入的扩展逻辑(比如background、popup)里先拿到正确的资源URL,再作为参数传给动态注入的脚本:
// 扩展侧代码(如background.js) const resourceUrl = chrome.runtime.getURL('example.txt'); chrome.scripting.executeScript({ target: { tabId: 当前标签ID }, func: (url) => { fetch(url).then(r => r.text()).then(txt => { // 这里处理获取到的文本内容 }); }, args: [resourceUrl] });
方法二:配置web_accessible_resources后拼接路径
把example.txt加入web_accessible_resources配置,再在动态脚本里用扩展ID拼接路径:
- 修改manifest.json:
"web_accessible_resources": [{ "resources": ["example.txt"], "matches": ["<all_urls>"] // 按需缩小匹配范围 }]
- 动态注入的脚本代码:
const extId = chrome.runtime.id; fetch(`chrome-extension://${extId}/example.txt`).then(r => r.text());
内容的提问来源于stack exchange,提问作者peter duffy
相关产品推荐
相关产品推荐

