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

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

解决Chrome扩展中chrome.tabs.sendMessage报错“Receiving end does not exist”的问题

以下是针对你遇到的问题的排查和解决步骤:

可能的原因及对应解决方案

1. 目标页面不在content script的匹配范围内

你的content script配置的matches是*://*/*,这个规则不包含Chrome内置页面(如chrome://settings、chrome-extension://开头的页面),如果当前激活的标签页是这类页面,content script不会注入,自然没有消息接收端。

  • 解决:如果需要处理这类页面,检查Chrome扩展文档确认是否允许注入,若允许则修改matches规则;如果不需要,确保发送消息时目标页面是普通HTTP/HTTPS页面。

2. content script未成功加载或监听器未注册

  • 打开目标页面的开发者工具(F12),切换到Sources面板,查看左侧Content scripts下是否存在你的content.js和addon.js:
    • 如果不存在:检查扩展是否在当前页面启用(隐身模式下扩展默认禁用,需在扩展管理页开启“允许在隐身模式下运行”),或确认matches规则是否覆盖当前页面。
    • 如果存在:查看页面控制台是否有语法错误,若content.js有报错,监听器无法正常注册。修正你的content.js代码,确保语法正确:
      chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.message === "request") {
          console.log('response received', request.payload);
          sendResponse({status: "done"});
        }
        // 返回true表示支持异步调用sendResponse
        return true;
      });
      

3. 发送消息时机过早,content script尚未加载完成

即使run_at设置为document_idle,如果background脚本在页面加载初期就发送消息,content script可能还未完成注入和初始化。

  • 解决:添加重试机制,确保content script加载完成后再发送消息。修改background.js:
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      let activeTab = tabs[0];
      
      function sendMessageWithRetry(tabId, message, retries = 3) {
        chrome.tabs.sendMessage(tabId, message, function(response) {
          if (chrome.runtime.lastError) {
            if (retries > 0) {
              // 延迟500ms后重试
              setTimeout(() => sendMessageWithRetry(tabId, message, retries - 1), 500);
            } else {
              console.error('消息发送失败:', chrome.runtime.lastError);
            }
          } else {
            console.log('收到响应:', response);
          }
        });
      }
    
      sendMessageWithRetry(activeTab.id, {"message": "request", "payload": preferences});
    });
    

4. 权限问题导致无法访问目标标签页

activeTab权限需要用户与扩展交互(如点击浏览器图标)才能获取当前标签页的访问权限,如果你的background脚本是在无用户交互的情况下触发消息发送,可能会出现权限问题。

  • 解决:将消息发送逻辑绑定到browserAction的点击事件中:
    chrome.browserAction.onClicked.addListener(function(tab) {
      chrome.tabs.sendMessage(tab.id, {"message": "request", "payload": preferences}, function(response) {
        if (!chrome.runtime.lastError) {
          console.log('收到响应:', response);
        } else {
          console.log(chrome.runtime.lastError);
        }
      });
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:01:22