Chrome扩展:chrome.runtime.sendMessage无法正常工作问题求助
问题排查与修复方案
核心问题拆解
- 消息格式不匹配:content.js里直接发字符串
"closeTab",但background.js里判断的是request.from === "closeTab"——字符串没有from属性,导致条件永远不成立,background自然不会执行关闭逻辑。 - content.js语法错误:if语句的闭合括号位置错了,导致最后一行的
console.log(chrome.runtime.sendMessage("closeTab"))会无条件执行,不管有没有检测到禁用词汇,还会重复发消息。 - 调试方式错了:Manifest V3的background是service worker,不能用普通页面的控制台看日志,得打开它专属的调试窗口。
具体修复步骤
1. 修正content.js的消息发送与语法
// content.js const forbiddenText = "cheese"; function checkForForbiddenText() { console.log("Checking for Forbidden Text....."); const bodyText = document.body.innerText; if (bodyText.includes(forbiddenText)) { console.log("Forbidden text found! Closing the tab..."); // 改成对象格式的消息,和background的判断逻辑匹配 chrome.runtime.sendMessage({ from: "closeTab" }); } } window.addEventListener("load", checkForForbiddenText);
2. 优化background.js的稳定性
原逻辑没问题,但可以加个异常处理避免报错:
// background.js chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.from === "closeTab") { console.log("Background Running....."); // 先判断tab id是否存在,防止意外报错 if (sender.tab?.id) { chrome.tabs.remove(sender.tab.id) .then(() => console.log("Tab closed")) .catch(err => console.error("Failed to close tab:", err)); } } }); chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { console.log("Tab updated:", changeInfo); });
3. 精简manifest.json权限
activeTab权限在这里没用,可以删掉,保留tabs足够:
{ "manifest_version": 3, "name": "Test Blocker", "version": "1", "permissions": ["tabs"], "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ] }
4. 正确查看background日志
- 打开Chrome扩展管理页(输入
chrome://extensions/) - 开启「开发者模式」
- 找到你的扩展,点击「Service Worker」下方的「检查」按钮,打开专属控制台就能看到background的日志了
内容的提问来源于stack exchange,提问作者Benroke
相关产品推荐
相关产品推荐

