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

Chrome扩展content script调用chrome.runtime.sendMessage收到background返回null问题

问题根因

你遇到的chrome.runtime.sendMessage返回null问题,核心触发点如下:

  • 首先确认manifest.json配置是否正确,权限、background脚本声明、content script匹配规则任一配置错误都会导致响应异常
  • 你当前background的消息监听逻辑虽已经返回true保留了sendResponse的引用,但异步逻辑的写法在83版本Chrome中存在兼容问题,可能导致回调未被正确触发

修复方案

1. 核对manifest.json配置

如果使用manifest V2版本,参考如下配置核对:

{
  "manifest_version": 2,
  "content_scripts": [
    {
      "matches": ["<你测试页面的匹配规则>"],
      "js": ["content_script.js"]
    }
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "permissions": ["runtime"]
}

如果使用manifest V3版本,注意background需调整为service worker模式,且权限声明对应调整。

2. 优化background消息监听逻辑

将异步逻辑用立即执行async函数包裹,避免回调丢失:

const create = async (msg, sender: chrome.runtime.MessageSender) => {
    return {
        var1: "var1",
        var2: "var2"
    };
};

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    (async () => {
        switch (msg.type) {
            case 'create':
                const result = await create(msg, sender);
                sendResponse(result);
                break;
            default:
                sendResponse(null);
        }
    })();
    // 必须返回true,告知Chrome需要异步等待sendResponse调用
    return true;
});

3. 兼容content script调用写法

83版本Chrome对回调式的sendMessage存在部分兼容问题,可替换为Promise写法:

window.addEventListener('message', (event) => {
  // 仅接受当前窗口自身发送的消息,不允许来自iframe的消息
  if (event.source !== window) {
    return;
  }

  // 仅转发相关类型的消息
  if (event.data.type && relevantEventTypes.indexOf(event.data.type) > -1) {
    chrome.runtime.sendMessage(event.data)
      .then(resp => {
        console.log("In content script");
        console.log(resp);
      })
      .catch(err => console.error("消息调用异常:", err));
  }
}, false);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 17:54:00