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

Chrome扩展:Background JS向Content JS发消息失败,反向正常

解决Chrome扩展Background向Content发送消息失败的问题

核心问题分析

报错Could not establish connection. Receiving end does not exist.本质是目标页面的Content脚本未被正确注入,或Background发送消息时Content脚本还未完成加载,导致接收端不存在。以下是针对性解决办法:


1. 检查Content脚本的注入配置

确保manifest.json中content_scripts的规则完全匹配目标页面,且注入时机合理:

{
  "content_scripts": [
    {
      "matches": ["https://www.google.com/*"], // 必须和Background中查询的URL规则一致
      "js": ["content.js"],
      "run_at": "document_idle" // 确保页面加载时脚本已注入,也可根据需求用document_start
    }
  ]
}

2. 避免在Service Worker启动时直接发送消息

Service Worker启动时机较早,此时目标页面可能还未加载完成,Content脚本尚未注入。改为监听页面加载完成事件后发送:

// background.js 修改后
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  // 仅当页面加载完成且URL匹配时发送消息
  if (changeInfo.status === 'complete' && tab.url.startsWith('https://www.google.com/')) {
    try {
      const response = await chrome.tabs.sendMessage(tabId, {greeting: "hello"});
      console.log('收到Content脚本响应:', response);
    } catch (err) {
      console.error('消息发送失败:', err);
    }
  }
});

3. 校验目标标签页的有效性

在发送消息前确认tabs.query返回的标签页存在,避免向无效ID发送:

// background.js 基础校验版
(async () => {
  const [tab] = await chrome.tabs.query({ url: "https://www.google.com/*" });
  if (!tab) {
    console.log('未找到匹配的目标标签页');
    return;
  }
  try {
    const response = await chrome.tabs.sendMessage(tab.id, {greeting: "hello"});
    console.log('响应内容:', response);
  } catch (err) {
    console.error('发送错误:', err);
  }
})();

4. 确认Content脚本正常执行

在Content脚本中添加日志,验证脚本是否被正确注入并注册监听:

// content.js 增强版
console.log('content.js已成功注入页面');
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log("收到Background消息:", request);
  sendResponse({reply: "已收到问候"}); // 可选:返回响应给Background
  return true; // 若sendResponse为异步调用则需要保留,同步场景可省略
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:03:28