Chrome扩展Manifest V3:如何在每次浏览器请求时执行函数?
解决方案
在Manifest V3中,由于Service Worker的事件驱动特性,无法直接像V2那样通过chrome.webRequest.onBeforeRequest同步拦截请求并执行逻辑,但可以结合请求事件监听+规则缓存更新的方式实现需求:既保证每次请求触发脚本检查规则有效性,又避免频繁调用API影响性能。
1. 调整manifest.json权限
需要添加webRequest(监听请求事件)和storage(缓存规则)权限,同时明确API的主机权限以避免跨域问题:
{ "manifest_version": 3, "name": "Daniel Website Blocker", "version": "1.0", "description": "Block a list of websites", "permissions": [ "declarativeNetRequest", "webRequest", "storage" ], "content_scripts": [ { "matches": ["<all_urls>"], "js": [ "ContentScript.js" ], "run_at": "document_start" } ], "host_permissions" : [ "<all_urls>", "https://6459308c8badff578e071356.mockapi.io/*" ], "web_accessible_resources": [ { "resources": ["images/*"], "matches": [ "<all_urls>" ] }], "background": { "service_worker": "background.js" } }
2. 修改background.js逻辑
通过请求事件唤醒Service Worker,结合缓存机制定期更新拦截规则:
const API_URL = 'https://6459308c8badff578e071356.mockapi.io/sitelist/websites'; const CACHE_EXPIRY = 5 * 60 * 1000; // 缓存5分钟,可按需调整 // 从API获取数据并更新拦截规则 async function fetchAndUpdateRules() { try { const response = await fetch(API_URL); const data = await response.json(); const rules = data.map(website => ({ id: parseInt(website.id), priority: 1, action: { type: "block" }, condition: { urlFilter: website.name, resourceTypes: ["main_frame"] } })); // 更新动态拦截规则 await chrome.declarativeNetRequest.updateDynamicRules({ addRules: rules, removeRuleIds: rules.map(item => item.id) }); // 缓存规则和更新时间 await chrome.storage.local.set({ cachedRules: rules, lastUpdated: Date.now() }); console.log("规则已更新:", rules); } catch (error) { console.error("更新规则失败:", error); } } // 检查缓存是否过期,过期则更新规则 async function checkAndUpdateRules() { const { cachedRules, lastUpdated } = await chrome.storage.local.get(["cachedRules", "lastUpdated"]); if (!cachedRules || Date.now() - lastUpdated > CACHE_EXPIRY) { await fetchAndUpdateRules(); } } // 监听每次主框架请求,触发规则检查 chrome.webRequest.onBeforeRequest.addListener( async () => { await checkAndUpdateRules(); }, { urls: ["<all_urls>"], types: ["main_frame"] } ); // 扩展安装时初始化规则 chrome.runtime.onInstalled.addListener(fetchAndUpdateRules);
关键说明
- 请求监听:
chrome.webRequest.onBeforeRequest会在每次主框架请求时唤醒Service Worker,触发规则检查逻辑。 - 缓存优化:用
chrome.storage.local缓存规则和更新时间,避免每次请求都调用API,平衡实时性与性能。 - 规则更新:通过
declarativeNetRequest.updateDynamicRules动态替换拦截规则,确保API返回的最新列表生效。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

