Chrome扩展:background.js向content-script.js发消息失败求助
问题原因
你遇到的错误「Could not establish connection. Receiving end does not exist.」核心原因有两个:
- Chrome内置页面的注入限制:
chrome://history/属于Chrome内置系统页面,默认情况下浏览器不允许扩展向这类页面自动注入content script,即使在manifest中配置匹配规则,部分内置页面仍受安全策略限制。 - 消息发送时机过早:
tabs.onCreated和tabs.onActivated触发时,页面可能尚未完全加载,content script还未完成注入,此时发送消息自然找不到接收端。
解决方案
方案1:尝试配置manifest支持内置页面注入(仅部分场景可行)
先修改manifest.json,添加历史页面的匹配规则及必要权限:
{ "manifest_version": 3, "name": "你的扩展名称", "version": "1.0", "permissions": ["tabs", "scripting"], "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["chrome://history/*"], "js": ["content-script.js"], "run_at": "document_idle" } ] }
⚠️ 注意:Chrome对chrome://协议页面限制严格,部分版本或环境下可能仍无法注入,此时需改用方案2。
方案2:用chrome.scripting.executeScript动态注入并通信
改用动态注入脚本的方式,确保脚本注入完成后再发送消息:
修改background.js的checkHistory函数及监听逻辑:
let currentTabURL = null; let currentTabId = null; // 监听页面加载完成事件,替代原有的onCreated和onActivated chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { if (changeInfo.status === "complete" && tab.url) { currentTabURL = tab.url; currentTabId = tabId; checkHistory(); } }); async function checkHistory(){ if(currentTabURL && currentTabURL.includes("://history/") && currentTabURL.endsWith("://history/")){ console.log("History page opened"); console.log("currentTabId: ", currentTabId); try { // 先动态注入content script await chrome.scripting.executeScript({ target: { tabId: currentTabId }, files: ["content-script.js"] }); // 注入完成后发送消息 chrome.tabs.sendMessage(currentTabId, {action: "checkHistory"}); } catch (err) { console.error("注入脚本失败:", err); // 注入失败时的降级处理逻辑 } } else{ console.log("History page not opened"); } }
方案3:直接在动态注入脚本中执行逻辑(无需消息通信)
如果只是需要在历史页面打开时执行操作,可以省略消息步骤,直接在注入的脚本中写逻辑:
创建history-script.js:
console.log("History page opened (直接注入执行)"); // 这里编写你需要在历史页面执行的逻辑
修改background.js的checkHistory:
async function checkHistory(){ if(currentTabURL && currentTabURL.includes("://history/") && currentTabURL.endsWith("://history/")){ console.log("History page opened"); console.log("currentTabId: ", currentTabId); try { await chrome.scripting.executeScript({ target: { tabId: currentTabId }, files: ["history-script.js"] }); } catch (err) { console.error("注入脚本失败:", err); } } else{ console.log("History page not opened"); } }
额外注意事项
- Chrome内置页面(如
chrome://history/、chrome://settings/等)受严格安全控制,部分页面即使配置权限也无法注入脚本,这是浏览器固有限制。 - 确保扩展使用Manifest V3,V2已被弃用,V3的service worker和scripting API是当前标准方案。
内容的提问来源于stack exchange,提问作者Gurneesh Budhiraja
相关产品推荐
相关产品推荐

