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

Chrome扩展转Safari后chrome.runtime.sendMessage返回undefined问题求助

解决Safari扩展中content script与background script消息通信返回undefined的问题

问题出在Safari对Chrome扩展API的兼容细节上:chrome.runtime.onMessage的监听器必须返回true,才能让sendResponse的结果正确传递给content script——哪怕你是同步返回响应,也必须加上这一行,否则Safari会提前关闭消息通道,导致content script接收到的结果为undefined。

修改你的background.js代码,添加返回true的语句:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    sendResponse("test123");
    return true; // 关键:告知Safari保留消息通道以传递响应
});

修改完成后,重新使用xcrun safari-web-extension-converter --app-name MySafariTest dist命令生成Safari扩展,或者直接在Xcode项目中更新对应的background脚本,重新运行测试即可。此时content script中await this.test()就能正确拿到返回值"test123"了。

内容的提问来源于stack exchange,提问作者李志博

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:59:52