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

Safari Web Extension消息通信异常:Content脚本无法接收消息

问题排查与修复方案

核心问题1:Manifest V3 背景脚本配置错误

你的manifest.json里背景脚本用了scripts字段,这是Manifest V2的写法,V3必须改用service_worker字段,同时不需要额外加type:module(V3的service worker默认支持ES模块语法)。错误配置会导致背景脚本运行异常,直接影响消息转发逻辑。

修复后的manifest.json背景部分:

"background": {
    "service_worker": "background.js"
},

核心问题2:消息收发的匹配与时机问题

  1. Popup向Content发送消息:
    确认当前激活标签页已注入content.js——你的matches规则*://*/*覆盖了绝大多数网页,但浏览器内置页面(如chrome://extensions/、about:blank)不会注入content脚本,这类页面下消息自然无法被接收。
    另外,将run_at从document_end改为document_idle,能确保content脚本在页面稳定后再注入,避免因页面未加载完成导致的消息丢失。

  2. Background向Content发送消息:
    你当前发送的是纯字符串"Sent from bg",虽然content脚本的监听逻辑能处理,但建议统一用对象格式传递消息,和Popup的发送格式保持一致,方便后续扩展逻辑。

实用调试技巧

  • 查看正确的控制台:别盯着扩展后台的控制台看,要打开当前网页的开发者工具(F12),切换到Console标签页,才能看到content.js的日志输出——很多人都会在这里踩坑。
  • 添加错误捕获:给tabs.sendMessage加上错误回调,能快速定位是否存在注入失败或消息发送失败的情况:
    // popup.js中修改发送逻辑
    browser.tabs.sendMessage(tabs[0].id, { greeting: "hello from the popup" })
      .catch(err => console.error("Popup发消息失败:", err));
    
  • 确认标签ID正确性:在Popup里打印tabs[0].id,确保获取到的是当前激活标签的有效ID。

修复后完整代码示例

window.onload = function() {
    browser.tabs.query({active: true, currentWindow: true}, function(tabs) {
        const tabId = tabs[0].id;
        console.log("当前标签ID:", tabId);
        // 发消息给content.js
        browser.tabs.sendMessage(tabId, { greeting: "hello from the popup" })
          .catch(err => console.error("Popup发消息失败:", err));
        // 发消息给background
        browser.runtime.sendMessage({ tabId: tabId, greeting: "Going to background?"})
          .catch(err => console.error("Popup发消息给后台失败:", err));
    });
}

content.js

browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log("Content收到消息: ", request);
    // 如需异步响应,return true保持消息端口开放
    return true;
});

background.js

browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log("后台收到消息: ", request);
    // 转发消息给content.js
    browser.tabs.sendMessage(request.tabId, { greeting: "Sent from bg" })
      .catch(err => console.error("后台发消息失败:", err));
});

manifest.json

{
    "manifest_version": 3,
    "name": "__MSG_extension_name__",
    "description": "__MSG_extension_description__",
    "version": "1.0",
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts": [{
        "js": [ "content.js" ],
        "matches": [ "*://*/*" ],
        "run_at": "document_idle"
    }],
    "action": {
        "default_popup": "popup.html",
        "default_icon": "images/toolbar-icon.svg"
    },
    "permissions": [
        "activeTab",
        "nativeMessaging"
    ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:48:28