Chrome网站拦截扩展失效排查请求(代码无明显问题)
网站拦截Chrome扩展问题排查与修复
核心问题分析
扩展拦截功能未生效,主要原因包括权限缺失、规则更新逻辑缺陷、静态规则配置冗余,以及用户输入未处理导致的过滤规则错误。
具体修复方案
1. manifest.json 权限与配置修正
- 补充关键权限:添加
declarativeNetRequestWithHostAccess权限,这是Manifest V3中使用动态网络拦截规则的必要权限。 - 移除冗余配置:若未创建
rules.json文件,需删除declarative_net_request节点,否则会导致扩展加载报错。
修复后的manifest.json:
{ "manifest_version": 3, "name": "Website Blocker", "version": "1.0", "permissions": [ "declarativeNetRequest", "declarativeNetRequestWithHostAccess", "storage", "activeTab" ], "background": { "service_worker": "background.js" }, "action": { "default_popup": "popup.html", "default_icon": { "16": "block.jpg", "48": "block.jpg", "128": "block.jpg" } }, "icons": { "16": "block.jpg", "48": "block.jpg", "128": "block.jpg" }, "web_accessible_resources": [ { "resources": ["blocked.html"], "matches": ["<all_urls>"] } ] }
2. background.js 规则更新逻辑优化
- 合并规则操作:原代码两次调用
updateDynamicRules易引发错误,改为先获取当前规则ID,一次性完成旧规则删除与新规则添加。 - 精准删除规则:不再批量删除1-1000的无效ID,而是删除现有动态规则的真实ID。
修复后的updateBlockedSitesRules函数:
function updateBlockedSitesRules(blockedSites) { console.log("Updating rules with blocked sites: ", blockedSites); chrome.declarativeNetRequest.getDynamicRules((currentRules) => { const removeRuleIds = currentRules.map(rule => rule.id); const newRules = blockedSites.map((site, index) => ({ id: index + 1, priority: 1, action: { type: "redirect", redirect: { extensionPath: `blocked.html?targetUrl=${encodeURIComponent(`*://${site.url}/*`)}` } }, condition: { urlFilter: `*://${site.url}/*`, resourceTypes: ["main_frame"] } })); chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: removeRuleIds, addRules: newRules }, () => { if (chrome.runtime.lastError) { console.error("Error updating rules: ", chrome.runtime.lastError); } else { console.log("Rules updated successfully"); chrome.declarativeNetRequest.getDynamicRules((rules) => { console.log("Current dynamic rules: ", rules); }); } }); }); }
3. popup.js 用户输入处理优化
- 提取纯域名:用户输入的URL可能包含协议或路径,需处理为纯域名,避免生成无效过滤规则。
- 添加去重逻辑:防止重复添加同一网站。
修复后的popup.js:
function extractDomain(url) { // 移除协议、www前缀及路径,保留纯域名 let domain = url.replace(/^(https?:\/\/)?(www\.)?/, '').split('/')[0]; return domain; } document.getElementById('blockBtn').addEventListener('click', () => { const urlInput = document.getElementById('urlInput').value.trim(); const cleanUrl = extractDomain(urlInput); const passwordInput = document.getElementById('passwordInput').value.trim(); if (cleanUrl && passwordInput) { chrome.storage.sync.get(['blockedSites'], (result) => { const blockedSites = result.blockedSites || []; if (!blockedSites.some(site => site.url === cleanUrl)) { blockedSites.push({ url: cleanUrl, password: passwordInput }); chrome.storage.sync.set({ blockedSites }, () => { console.log("Blocked sites updated: ", blockedSites); }); document.getElementById('urlInput').value = ''; document.getElementById('passwordInput').value = ''; showBlockedSites(blockedSites); } else { alert("该网站已被添加"); } }); } }); document.getElementById('showBtn').addEventListener('click', () => { chrome.storage.sync.get(['blockedSites'], (result) => { showBlockedSites(result.blockedSites || []); }); }); function showBlockedSites(blockedSites) { const list = document.getElementById('blockedSitesList'); list.innerHTML = ''; blockedSites.forEach((site) => { const li = document.createElement('li'); li.textContent = site.url; list.appendChild(li); }); }
4. 辅助检查项
- 创建rules.json(可选):若保留manifest中的静态规则配置,需创建空的
rules.json文件,内容为[]。 - 查看后台日志:打开
chrome://extensions/,点击扩展的"服务工作者"链接,查看日志验证规则是否成功更新。
内容的提问来源于stack exchange,提问作者alfaprogramer
相关产品推荐
相关产品推荐

