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

Chrome扩展onMessage异步回调sendResponse返回undefined问题

问题根因

chrome.runtime.onMessage的监听器默认按同步逻辑执行,当你在监听器内部调用chrome.storage.local.get这类带异步回调的API时,监听器主逻辑会在异步回调触发前就执行结束,对应的消息通道会被直接关闭。此时你在异步回调里调用sendResponse属于无效操作,popup端自然只能拿到undefined。

修复方案

在消息监听器中需要异步返回响应的分支里,显式return true,告知Chrome runtime需要保持消息通道开放,直到sendResponse被调用为止。

修正后代码

background.js

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if ((msg.from === 'popup') && (msg.subject === 'ubisoft')) {
    chrome.storage.local.get("key", function(data) {
      console.log(data.key)
      sendResponse(data.key);
    });
    // 关键:声明异步响应,保持消息通道开放
    return true;
  }
});

原有逻辑不需要调整,保持如下即可:

chrome.runtime.sendMessage({from: 'popup',subject: 'ubisoft'}, function (result) {
  window.alert(result)
});

补充说明:该写法同时兼容Manifest V2、Manifest V3版本的Chrome扩展。如果是MV3环境,你也可以选择用async/await的Promise写法实现相同效果,不需要额外return true。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 19:57:27