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,提问作者李志博
相关产品推荐
相关产品推荐

