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

Chrome扩展background.js发送消息报错:接收端不存在

Chrome扩展:Background向Popup发消息报错“Receiving end does not exist”的解决方法

错误原因

你遇到的Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.错误,本质是Popup仅在用户点击扩展图标打开时才会加载并运行内部脚本,而Background的定时任务会持续发送消息,当Popup未打开时,没有对应的消息监听端存在,导致一次性消息发送失败。

解决方案

根据业务需求,可选择以下两种方案:

方案1:仅在Popup打开时发送消息(长连接方式)

通过chrome.runtime.connect建立Background与Popup的长连接,只有连接存在时才发送消息,避免无接收端的情况。

Background.js 修改代码:

let popupPort = null;

// 监听Popup发起的连接请求
chrome.runtime.onConnect.addListener((port) => {
  if (port.name === 'popup-bg-connection') {
    popupPort = port;

    // Popup关闭时清除连接引用
    port.onDisconnect.addListener(() => {
      popupPort = null;
    });

    // 定时发送消息(仅当连接有效时)
    const msgInterval = setInterval(() => {
      if (popupPort) {
        popupPort.postMessage({ command: "TEST0" });
      } else {
        clearInterval(msgInterval);
      }
    }, 2000);
  }
});

Popup.js 添加监听代码:

// 与Background建立长连接
const bgPort = chrome.runtime.connect({ name: 'popup-bg-connection' });

// 接收Background的消息
bgPort.onMessage.addListener((message) => {
  if (message.command === "TEST0") {
    // 这里添加你的消息处理逻辑
    console.log('收到Background消息:', message);
  }
});

方案2:离线存储消息,Popup打开时读取

如果需要在Popup关闭时也保留消息,等Popup打开后再获取,可通过chrome.storage中转消息。

Background.js 修改代码:

setInterval(() => {
  // 将消息存入本地存储,替代直接发送
  chrome.storage.local.set({
    bgMessage: { command: "TEST0", time: Date.now() }
  });
}, 2000);

Popup.js 添加读取逻辑:

// Popup打开时立即读取存储的消息
chrome.storage.local.get('bgMessage', (res) => {
  if (res.bgMessage) {
    console.log('读取历史消息:', res.bgMessage);
    // 可选:处理后清除已读消息
    // chrome.storage.local.remove('bgMessage');
  }
});

// 监听存储变化,实时接收新消息
chrome.storage.onChanged.addListener((changes, area) => {
  if (area === 'local' && changes.bgMessage) {
    console.log('实时收到消息:', changes.bgMessage.newValue);
  }
});

原代码问题说明

原代码使用chrome.runtime.sendMessage属于一次性消息发送,要求必须有活跃的chrome.runtime.onMessage监听端存在,否则会直接抛出错误。而上述两种方案分别适配了“仅在线发送”和“离线缓存”的场景,避免了无接收端的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 06:30:17