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

Chrome扩展开发问题:内容脚本与后台通信报错排查

Chrome扩展通信错误排查与修复

你遇到的Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.错误,核心原因是消息回复方式不匹配,同时存在权限缺失和代码冗余问题,以下是具体分析和修复方案:

错误原因拆解

  1. 消息回复逻辑错误
    background在收到getActiveTabRequest请求时,使用chrome.runtime.sendMessage广播消息,而非用sendResponse回复当前请求的发送者(contentScript)。这导致contentScript发送请求后,没有对应的接收端处理回复,触发连接错误。

  2. 权限缺失
    获取标签页URL需要tabs权限,原manifest未声明,可能导致无法读取activeTab.url。

  3. 其他代码问题

    • background中Script构造函数未定义,会引发未捕获错误;
    • contentScript重复注册chrome.runtime.onMessage监听,造成代码冗余。

修复后的代码

manifest.json(添加tabs权限)

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["contentScript.js"]
    }
  ],
  "permissions": ["scripting", "activeTab", "tabs"],
  "background": {
    "service_worker": "background.js"
  }
}

contentScript.js(简化监听,改用async/await接收回复)

// contentScript.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "executeScript") {
    const script = document.createElement('script');
    script.textContent = message.script;
    document.head.appendChild(script);
  }
});

// 测试消息发送
chrome.runtime.sendMessage({
  type: "printToConsole",
  message: "Hello from the content script!"
});

async function getActiveTab() {
  try {
    const response = await chrome.runtime.sendMessage({ type: "getActiveTabRequest" });
    console.log("Active tab URL:", response.activeTab.url);
  } catch (error) {
    console.error("获取标签页URL失败:", error);
  }
}

getActiveTab();

background.js(合并监听,用sendResponse回复异步请求)

// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch(message.type) {
    case "executeScript":
      chrome.scripting.executeScript({
        target: { tabId: sender.tab.id },
        func: () => eval(message.script)
      });
      break;
    case "printToConsole":
      console.log(message.message);
      break;
    case "sendData":
      console.log("Received data from content script:", message.data);
      break;
    case "getActiveTabRequest":
      // 异步操作需返回true保持连接,直到sendResponse调用
      (async () => {
        const tabs = await chrome.tabs.query({
          active: true,
          currentWindow: true
        });
        sendResponse({ activeTab: tabs[0] });
      })();
      return true;
  }
});

关键修复点说明

  • 用sendResponse回复请求:background处理异步请求时,必须返回true告诉Chrome等待异步操作完成,再通过sendResponse给contentScript返回结果;
  • 添加tabs权限:确保能正常获取标签页的URL信息;
  • 合并消息监听:将多个独立的onMessage监听合并为一个,提升代码可读性和维护性;
  • 修正脚本注入逻辑:background中移除未定义的Script构造函数,改用eval或直接传递脚本内容实现注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:55:54