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

Chrome扩展报错:无法建立连接接收端不存在,求通信修复方案

核心问题分析

  • Content Script 监听API错误:误用了不存在的chrome.tabs.addListener,且异步逻辑处理有误
  • 消息数据不可序列化:直接传递DOM元素article,Chrome扩展消息仅支持可JSON序列化的数据
  • Service Worker 异步调用未加await:导致无法获取实际响应结果
  • Service Worker 错误调用API:chrome.runtime.sendMessage用于扩展内部页面通信,向Content Script发消息需用chrome.tabs.sendMessage

修复后的代码

1. Service-Worker.js

修正异步调用逻辑,移除无效API调用,确保正确处理响应:

chrome.runtime.onMessage.addListener(async function(request, sender, sendResponse) {
  if (request.action === "submit") {
    console.log("submit stage 1");
    try {
      const domContent = await sendMessageToActiveTab();
      console.log("Received DOM content:", domContent);
      // 此处可将DOM内容发送至后端服务器
      // fetch('你的后端接口地址', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ dom: domContent })
      // });
      sendResponse({ status: 'success' });
    } catch (err) {
      console.error("Failed to get DOM:", err);
      sendResponse({ status: 'error', msg: err.message });
    }
    // 异步处理需返回true以保持消息通道打开
    return true;
  }
});

async function sendMessageToActiveTab() {
  const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
  return chrome.tabs.sendMessage(tab.id, { action: 'sendDOM' });
}

2. Content-Script.js

移除错误监听器,将DOM转换为可序列化的HTML字符串:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === "sendDOM") {
    // 直接获取body的HTML字符串,无需await
    const bodyHTML = document.body.outerHTML;
    console.log("Captured body content:", bodyHTML);
    sendResponse(bodyHTML);
    // 同步返回可省略return true,若有后续异步操作则必须添加
    return true;
  }
});

3. manifest.json

移除不必要的externally_connectable配置(仅外部网站需与扩展通信时才需设置):

{
  "manifest_version": 3,
  "name": "Nuntia",
  "version": "1.0",
  "permissions": ["activeTab","tabs"],  
  "action": {
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "service-worker.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"]
    }
  ],
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ]
}

额外注意事项

  • 确保Content Script已注入:扩展安装后打开的标签页需刷新,才能让Content Script生效
  • 消息大小限制:Chrome消息传递数据上限约1MB,若DOM内容过大,建议在Content Script中先做精简处理再发送
  • Service Worker 生命周期:Manifest V3的Service Worker会自动休眠,若需长时间运行任务,需通过合理方式保持其活跃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:53:10