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

Chrome扩展Manifest V3:background.js与content.js通信报错求助

Chrome扩展通信错误排查:Receiving end does not exist

在Chrome扩展中尝试从background.js向content.js发送请求时,出现错误:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
已尝试Chrome官方文档示例仍无法解决,以下是相关代码和目录结构,请求协助排查:

Manifest.json

{
    "name": "test",
    "description": "test",
    "version": "1.0.0",
    "manifest_version": 3,
    "author": "test",

    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["scripts/content.js"]
      }
    ],

    "action": {
    },

    "background": {
      "service_worker": "scripts/background.js"
    },

    "permissions": [
      "tabs"
    ],

    "host_permissions": [
      "*://*/*"
    ]
}

content.js

chrome.runtime.onMessage.addListener( (request, sender, sendResponse) => {
  console.log(request);
})

background.js

chrome.action.onClicked.addListener(
  (tab) => {
    chrome.tabs.sendMessage(tab.id, {response: "Hello World"})
  }
)

文件夹目录结构

manifest.json
scripts/background.js
scripts/content.js

排查方向与解决方案

  1. 确认内容脚本注入的页面类型
    <all_urls> 并不包含Chrome内置页面(如chrome://开头的页面、扩展管理页面等),点击扩展图标时如果当前标签页是这类页面,内容脚本不会注入,自然接收不到消息。建议切换到普通HTTPS/HTTP网页(如https://example.com)后再测试。

  2. 添加错误捕获与异步处理
    Manifest V3中后台是Service Worker,chrome.tabs.sendMessage是异步操作,未处理错误会抛出未捕获的Promise错误。修改background.js:

    chrome.action.onClicked.addListener(async (tab) => {
      try {
        const response = await chrome.tabs.sendMessage(tab.id, {response: "Hello World"});
        console.log("内容脚本回应:", response);
      } catch (err) {
        console.error("消息发送失败:", err);
      }
    });
    
  3. 验证内容脚本是否正常注入
    在content.js开头添加日志,确认脚本是否加载到目标页面:

    console.log("content.js已成功注入页面");
    chrome.runtime.onMessage.addListener( (request, sender, sendResponse) => {
      console.log("收到消息:", request);
      // 可选:返回回应给background.js
      sendResponse({status: "消息已接收"});
    })
    
  4. 重新加载扩展
    修改代码后,进入Chrome扩展管理页面,点击扩展的"重新加载"按钮,确保最新代码生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:50:39