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

从网页向Chrome扩展发消息报chrome.runtime.lastError如何解决

Chrome扩展通信报错修复方案

你遇到的Could not establish connection. Receiving end does not exist.报错,核心原因是后台脚本未正确注册、监听事件类型不匹配,具体修复步骤如下:

1. 修正manifest.json配置

  • 新增background字段注册后台脚本,否则浏览器不会加载你的background.js
  • 删除content_scripts中的无效配置ids,该字段不属于content script的配置项
  • 同扩展内部通信不需要配置externally_connectable,如果没有外部网页调用扩展的需求可以直接删除该项
    修复后的配置参考:
{
    "manifest_version": 2,
    "name": "Sample Name",
    "version": "1.0.0",
    "description": "Sample description",
    "short_name": "Short Sample Name",
    "permissions": ["tabs", "https://google.com/*", "activeTab", "declarativeContent", "storage"],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "content_scripts": [
        {
            "matches": ["https://www.google.com/*"],
            "js": ["content.js"],
            "css": ["test.css"]
        }
    ],
    "browser_action": {
        "default_title": "Sample title",
        "default_popup": "popup.html",
        "default_icon": {
            "16": "icons/icon16.png",
            "32": "icons/icon32.png"
        }
    }
}

2. 简化content.js代码

同扩展的content script与后台通信不需要指定扩展ID,也不需要额外的ping逻辑,直接发送消息即可:

const url = window.location.href;
chrome.runtime.sendMessage({ url: url }, function (response) {
    if (chrome.runtime.lastError) {
        console.log("消息发送失败:", chrome.runtime.lastError.message);
        return;
    }
    console.log(response);
});

3. 修正background.js监听逻辑

  • 删除Chrome App专用的chrome.app.runtime相关代码,该API不适用于Chrome扩展
  • 同扩展内部的消息不需要用onMessageExternal监听,替换为chrome.runtime.onMessage即可
  • 端口消息监听应使用port.onMessage,而非port.onMessageExternal
    修复后的代码参考:
const blocklistedWebsite = [];
// 单次消息监听
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (blocklistedWebsite.includes(sender.url)) {
        sendResponse({success: false, msg: "该网站已被屏蔽"});
        return;
    }
    sendResponse({
        success: true,
        msg: "I have received your message",
    });
    // 异步返回结果需要额外加return true,同步返回无需添加
});

// 如果不需要长连接通信可以删除下面的onConnect逻辑
chrome.runtime.onConnect.addListener((port) => {
    console.log("connected ", port);
    port.onMessage.addListener(function (request, sender) {
        if (blocklistedWebsite.includes(port.sender.url)) return; 
        port.postMessage({
            success: true,
            msg: "I have received your message",
        });
    });
});

验证步骤

修改完成后按照以下顺序操作避免缓存问题:

  • 打开扩展管理页面chrome://extensions/,点击对应扩展的刷新按钮重新加载扩展
  • 关闭所有已打开的谷歌页面,重新打开目标页面测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:54:07