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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 11:27:09