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

使用Mozilla webextension-polyfill的Chrome扩展无法显示通知

解决Chrome扩展中消息端口关闭的报错问题

我来帮你搞定这个问题!你遇到的The message port closed before a response was received错误,本质是Chrome和Firefox在处理runtime.onMessage监听器时的行为差异,再加上可能缺少必要权限导致的。下面是具体的修复步骤:

1. 添加Chrome必需的通知权限

Chrome要求扩展必须明确声明notifications权限才能显示通知,而Firefox在权限处理上相对宽松。打开你的manifest.json,补充permissions字段(如果原本没有的话):

{
  "manifest_version": 2,
  // ... 其他已有的配置项
  "permissions": [
    "notifications",
    "storage",
    "activeTab" // 确保执行内容脚本的权限
  ],
  "background": {
    "scripts": [ "lib/browser-polyfill.js", "background-script.js" ],
    "persistent": false
  },
  "options_ui": {
    "page": "settings/options.html"
  }
}

2. 修改后台脚本的消息监听器

Chrome的runtime.onMessage机制有个特殊要求:如果监听器内包含异步操作(比如browser.notifications.create是返回Promise的异步方法),必须返回true来告知浏览器“我会异步处理这条消息,不要立刻关闭端口”。否则Chrome会在监听器函数执行完毕后直接关闭端口,导致内容脚本的sendMessage Promise抛出错误。

更新你的background-script.js中的notify函数:

function notify(message, sender, sendResponse) {
  if (message.copied) {
    browser.notifications.create({
      "type": "basic",
      "title": "Notification title", // 修正了你原代码里的拼写错误:Notifaction → Notification
      "message": "Hello, world!"
    })
    // 可选:处理通知创建的结果
    .then(() => {
      console.log("通知显示成功");
      // 告知内容脚本消息已处理完成(可选,因为你不需要返回数据)
      sendResponse();
    })
    .catch(err => {
      console.error("创建通知失败:", err);
      sendResponse();
    });
  }
  // 返回true,保持消息端口开放直到异步操作完成
  return true;
}

browser.browserAction.onClicked.addListener(() => {
  browser.tabs.executeScript({file: "lib/browser-polyfill.js"});
  browser.tabs.executeScript({file: "content-script.js"});
});

browser.runtime.onMessage.addListener(notify);

3. 可选优化:避免重复注入内容脚本

每次点击浏览器图标都注入脚本可能导致重复执行,你可以在注入前检查标签页是否已经注入过脚本:

browser.browserAction.onClicked.addListener(async (tab) => {
  // 检查当前标签页是否已经注入过content-script
  const hasInjected = await browser.tabs.executeScript(tab.id, {
    code: "typeof window.hasInjectedScript === 'boolean'"
  });
  if (!hasInjected[0]) {
    browser.tabs.executeScript(tab.id, {file: "lib/browser-polyfill.js"});
    browser.tabs.executeScript(tab.id, {file: "content-script.js"});
    // 标记已注入,避免重复执行
    browser.tabs.executeScript(tab.id, {
      code: "window.hasInjectedScript = true;"
    });
  }
});

这样修改后,Chrome里的消息传递就不会再报错,通知也能正常显示了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:53:52