Chrome扩展Popup脚本与Content脚本通信失败问题排查
问题
开发基于JavaScript的Chrome扩展时,无法实现Popup脚本与可访问网页DOM的Content脚本之间的通信。参考官方文档示例代码配置manifest.json后,popup.js中的sendMessage函数触发错误:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
将监听代码移至Service Worker的background.js时通信成功,但Service Worker无法访问DOM,不符合需求。
相关代码
popup.js
(async () => { const response = await chrome.runtime.sendMessage({greeting: "hello"}); console.log(response); })();
script.js(Content脚本)
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension"); if (request.greeting === "hello") sendResponse({farewell: "goodbye"}); });
初始manifest.json
{ "name": "Test", "version": "0.1", "manifest_version": 3, "action": { "default_popup": "popup.html", "default_title": "Test App" }, "permissions": ["scripting", "activeTab"], "host_permissions": ["*://*/*"], "content_scripts": [{ "matches": ["<all_urls>"], "js": ["script.js"] }] }
解决方案
错误原因
你使用的chrome.runtime.sendMessage是向整个扩展的所有监听者广播消息,当Popup调用它时,如果当前活跃标签页的Content脚本未正确加载(比如扩展安装/更新后标签页未刷新,或者Content脚本匹配规则未覆盖当前页面),就会出现找不到接收端的错误。而移到background.js能成功,是因为Service Worker始终在后台运行,能接收runtime.sendMessage的消息。
修复步骤
确保Content脚本已加载到当前标签页
- 扩展安装或更新后,刷新测试网页,旧标签页不会自动注入新添加的Content脚本。
- 确认当前页面URL符合
manifest.json中content_scripts的matches规则(你用的<all_urls>没问题,但chrome://等受限页面无法注入Content脚本)。
改用标签页定向消息发送
Popup要和当前活跃标签页的Content脚本通信,需使用chrome.tabs.sendMessage指定目标标签页ID,而非chrome.runtime.sendMessage。修改popup.js如下:(async () => { // 获取当前活跃标签页 const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); // 向该标签页的Content脚本发送消息 const response = await chrome.tabs.sendMessage(tab.id, {greeting: "hello"}); console.log(response); })();验证Content脚本的注入状态
- 打开当前标签页的开发者工具(F12),切换到Console面板,检查是否有Content脚本输出的日志(比如
from a content script:开头的内容),以此确认脚本是否成功注入。 - 若Content脚本需操作DOM,可在
manifest.json的content_scripts中显式添加"run_at": "document_idle"(默认值,显式声明更稳妥),确保脚本在DOM加载完成后执行。
- 打开当前标签页的开发者工具(F12),切换到Console面板,检查是否有Content脚本输出的日志(比如
内容的提问来源于stack exchange,提问作者angelplusultra
相关产品推荐
相关产品推荐

