You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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,不符合需求。

相关代码

(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的消息。

修复步骤

  1. 确保Content脚本已加载到当前标签页

    • 扩展安装或更新后,刷新测试网页,旧标签页不会自动注入新添加的Content脚本。
    • 确认当前页面URL符合manifest.json中content_scripts的matches规则(你用的<all_urls>没问题,但chrome://等受限页面无法注入Content脚本)。
  2. 改用标签页定向消息发送
    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);
    })();
    
  3. 验证Content脚本的注入状态

    • 打开当前标签页的开发者工具(F12),切换到Console面板,检查是否有Content脚本输出的日志(比如from a content script:开头的内容),以此确认脚本是否成功注入。
    • 若Content脚本需操作DOM,可在manifest.json的content_scripts中显式添加"run_at": "document_idle"(默认值,显式声明更稳妥),确保脚本在DOM加载完成后执行。

内容的提问来源于stack exchange,提问作者angelplusultra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:46:02