Chrome扩展中Content Script向Background Script发消息时连接失败报错
Chrome扩展Manifest V3消息通信报错解决方案
问题描述
Content Script向Background Service Worker发送消息时,控制台报错:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
同时Service Worker日志无任何输出,使用Manifest V3,相关代码如下:
backgroundScript.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { console.log('request: ', request); });
contentScript.js
chrome.runtime.sendMessage({ greeting: 'hello' });
manifest.json
{ "manifest_version": 3, "name": "Chrome Extension with React & Webpack", "description": "A chrome extension boilerplate built with React 17, Webpack 5, and Webpack Dev Server 4", "options_page": "options.html", "background": { "service_worker": "background.bundle.js" }, "action": { "default_popup": "popup.html", "default_icon": "icon-34.png" }, "chrome_url_overrides": { "newtab": "newtab.html" }, "icons": { "128": "icon-128.png" }, "content_scripts": [ { "matches": ["http://*/*", "https://*/*", "<all_urls>"], "js": ["contentScript.bundle.js"], "css": ["content.styles.css"] } ], "host_permissions": ["http://*/"], "devtools_page": "devtools.html", "web_accessible_resources": [ { "resources": ["content.styles.css", "icon-128.png", "icon-34.png"], "matches": [] } ] }
排查及解决步骤
1. 确认Service Worker是否正常加载
- 打开
chrome://extensions/,开启开发者模式,找到你的扩展,点击"Service Worker"的检查链接,查看是否有加载错误。 - 检查Webpack打包配置,确保
background.bundle.js正确输出到扩展根目录,与manifest中配置的路径一致。
2. 修正消息监听逻辑
Manifest V3中Service Worker是事件驱动的,若需要保持消息通道开放(比如异步响应),必须在监听函数末尾返回true:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { console.log('request: ', request); return true; // 保留通道,支持异步sendResponse });
3. 补全权限配置
当前host_permissions仅包含http://*/,缺少HTTPS权限,导致HTTPS页面的Content Script无法与后台通信,修改为:
"host_permissions": ["http://*/*", "https://*/*"]
4. 处理Content Script执行时机
Content Script可能在Service Worker启动前就发送消息,可添加重试逻辑:
function sendMessageWithRetry() { chrome.runtime.sendMessage({ greeting: 'hello' }) .catch(() => setTimeout(sendMessageWithRetry, 100)); } sendMessageWithRetry();
内容的提问来源于stack exchange,提问作者aaaaaa
相关产品推荐
相关产品推荐

