Chrome扩展Manifest V3下替换远程JS为本地JS的实现求助
解决Manifest V3中替换远程JS文件的问题
在Manifest V3中,chrome.webRequest.onBeforeRequest的blocking模式已被大幅限制,替代方案是使用Declarative Net Request API实现请求重定向,同时需配置资源可访问性让页面能加载本地脚本。以下是完整实现步骤:
1. 准备本地替代脚本
创建本地JS文件(比如命名为local-remote.js),写入你想要替换的业务逻辑。
2. 修改manifest.json
更新配置,添加web_accessible_resources(允许页面访问扩展内的本地脚本),优化权限配置:
{ "manifest_version": 3, "name": "Replace js", "description": "Replace remote JS with local file", "version": "1.0", "content_scripts": [ { "js": ["content-script.js"], "matches": ["https://mine.com/*"] } ], "background": { "service_worker": "background.js" }, "action": { "default_popup": "popup.html" }, "permissions": [ "declarativeNetRequest", "declarativeNetRequestFeedback" ], "host_permissions": [ "*://www.mine.com/*" ], "web_accessible_resources": [ { "resources": ["local-remote.js"], "matches": ["*://www.mine.com/*"] } ], "declarative_net_request": { "rule_resources": [ { "id": "ruleset_1", "enabled": true, "path": "rules.json" } ] } }
3. 创建请求重定向规则文件
新建rules.json,定义将远程JS请求重定向到本地文件的规则:
[ { "id": 1, "priority": 1, "action": { "type": "REDIRECT", "redirect": { "extensionPath": "/local-remote.js" } }, "condition": { "urlFilter": "https://www.mine.com/remote.js", "resourceTypes": ["script"] } } ]
4. 可选:动态添加规则(替代静态rules.json)
如果需要动态控制规则开关,可以在background.js中添加以下代码,无需配置declarative_net_request.rule_resources:
chrome.runtime.onInstalled.addListener(() => { chrome.declarativeNetRequest.updateDynamicRules({ addRules: [ { "id": 1, "priority": 1, "action": { "type": "REDIRECT", "redirect": { "extensionPath": "/local-remote.js" } }, "condition": { "urlFilter": "https://www.mine.com/remote.js", "resourceTypes": ["script"] } } ], removeRuleIds: [] }); });
关键注意事项
web_accessible_resources必须配置,否则页面无法加载扩展内的本地脚本。- 规则的
urlFilter要精准匹配目标远程JS的URL,避免误拦截其他资源。 - 优先级
priority可根据需求调整,确保该规则优先于其他可能存在的规则执行。
内容的提问来源于stack exchange,提问作者solverfox
相关产品推荐
相关产品推荐

