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

Chrome扩展MV3:Background Script无法接收React应用消息

问题原因及解决方案

核心原因

你用错了消息发送API:

  • chrome.tabs.sendMessage的作用是向指定标签页的内容脚本发送消息,所以内容脚本能监听到,但背景页的chrome.runtime.onMessage监听器接收不到这个渠道的消息。
  • 要给背景页发消息,必须用chrome.runtime.sendMessage这个API。

代码修改方案

把ChromeExtensionService里的sendMessage方法改成使用chrome.runtime.sendMessage,不需要查询活跃标签,直接发送即可:

export class ChromeExtensionService {
    async sendMessage(messageType: string, messageBody: object): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            chrome.runtime.sendMessage(
                {
                    messageType: messageType,
                    content: messageBody,
                },
                (response) => {
                    if (chrome.runtime.lastError) {
                        reject(chrome.runtime.lastError.message);
                        return;
                    }
                    if (!response) {
                        reject("Something went wrong when sending the message to chrome extension");
                    }
                    console.log("Got a response - ", response);
                    resolve();
                }
            );
        });
    }
}

额外说明

  • 背景页的chrome.runtime.onMessage监听器不需要修改,它本来就是接收chrome.runtime.sendMessage发送的消息。
  • 如果你需要同时给内容脚本和背景页发消息,可以分别调用tabs.sendMessage和runtime.sendMessage,或者让内容脚本收到消息后再转发给背景页(但没必要,直接分开发更清晰)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:15:21