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

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

解决Chrome扩展与Angular网页通信的“接收端不存在”错误

以下是针对该错误的具体排查和修复步骤:

1. 确认扩展ID完全正确

  • 打开Chrome扩展管理页面(chrome://extensions/),开启开发者模式
  • 找到目标扩展,复制其完整ID,替换代码中的abcdefghijklmnoabcdefhijklmnoabc,注意ID区分大小写,不能有任何拼写错误

2. 在扩展manifest.json中添加externally_connectable配置

这是极易遗漏的关键步骤,必须明确声明允许发送消息的网页域名:

{
  "manifest_version": 3,
  "name": "你的扩展名称",
  "version": "1.0",
  "background": {
    "service_worker": "background.js"
  },
  "externally_connectable": {
    "matches": [
      "https://你的angular网站域名/*", // 本地开发可填"https://localhost:4200/*"
      "http://localhost:4200/*"
    ]
  }
}
  • 配置完成后需重新加载扩展(在扩展管理页面点击刷新按钮)

3. 修复background.js的监听逻辑

你的监听函数未调用sendResponse,会导致Chrome判定通信未正常完成,进而抛出连接错误。同时需确保blocklistedWebsite变量已正确定义:

const blocklistedWebsite = "https://example.com"; // 替换为实际黑名单域名

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    // 校验发送方域名
    if (sender.url.startsWith(blocklistedWebsite)) {
      sendResponse({success: false, reason: "Blocked website"});
      return;
    }
    // 处理请求并返回结果
    if (request.openUrlInEditor) {
      openUrl(request.openUrlInEditor);
      sendResponse({success: true});
    } else {
      sendResponse({success: false, reason: "Invalid request"});
    }
    // 若需异步处理请求,需返回true以保持连接
    // return true;
  });

4. 确保Angular中Chrome API的可用性

  • 确认代码仅在浏览器环境执行,避免在SSR(服务器端渲染)阶段调用Chrome API
  • 若Angular报chrome未定义,可在src/typings.d.ts中添加类型声明:
declare namespace chrome {
  namespace runtime {
    function sendMessage(extensionId: string, message: any, callback?: (response: any) => void): void;
  }
}

5. 排查扩展加载状态

  • 检查扩展是否已启用,在扩展管理页面确认开关处于开启状态
  • 查看background service worker是否正常运行:在扩展管理页面点击“服务工作者”的“检查”按钮,查看控制台是否有报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:07:44