Chrome扩展:Popup向Background发消息后返回undefined问题求助
Chrome扩展消息响应返回undefined的解决办法
问题根源
你的background.js里,chrome.runtime.onMessage监听器在触发异步的chrome.storage.local.get后,没返回true。Chrome的消息规则是:如果要在异步回调里调用sendResponse,必须让监听器函数返回true,告诉Chrome别着急关闭消息通道,等sendResponse执行完再关。不然监听器函数跑完就直接关通道了,后续调用sendResponse根本传不到Popup,所以Popup拿到的就是undefined。
修复代码
修改后的background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if(request.subject == "config"){ chrome.storage.local.get("config2t2b", function(result){ console.log(result.config2t2b); sendResponse(result.config2t2b); }); // 核心:返回true维持消息通道 return true; } });
可选:用async/await简化写法
如果喜欢Promise风格,可以把存储API包装成Promise用async/await:
chrome.runtime.onMessage.addListener(async function(request, sender, sendResponse) { if(request.subject == "config"){ const result = await chrome.storage.local.get("config2t2b"); console.log(result.config2t2b); sendResponse(result.config2t2b); return true; } });
额外排查点
关于你说的“Popup直接拿storage返回空映射”,可以检查这两点:
- 确认
config2t2b确实存在:打开扩展管理页,进入背景页的DevTools,在Application面板的Local Storage里查看chrome-extension://[你的扩展ID]下的存储内容。 - 确保
manifest.json声明了storage权限:
{ "permissions": ["storage"] }
内容的提问来源于stack exchange,提问作者Zhikang Rong
相关产品推荐
相关产品推荐

