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

Manifest V3 Chrome扩展中Promise返回undefined问题求助

问题原因与解决方案

核心问题

在Manifest V3中,chrome.runtime.onMessage的监听器如果要返回异步响应(比如Promise),必须显式返回true,否则Chrome会在监听器函数执行完毕后立即判定无响应,导致后台脚本接收到undefined。

你的Content.js代码虽返回了Promise,但未返回true,Chrome不会等待Promise完成就直接关闭消息通道,因此后台收不到预期响应。另外,如果executeAction是异步函数,当前的try/catch无法捕获它的错误——直接调用异步函数不会等待其完成,错误会变成未捕获的Promise拒绝,不会进入catch块。

修正后的代码

Content.js

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
    if(request.action === "executeAction") {
      try {
        // 若executeAction是异步函数,必须用await等待执行完成
        await executeAction(request.instruction, request);
        sendResponse({answer: "instructOK"});
      } catch(e) {
        console.error("执行动作出错:", e);
        sendResponse({answer: "error", error: e.message});
      }
      // 返回true,告知Chrome需等待异步响应
      return true;
    }
  });

后台脚本优化建议

既然已使用async/await,无需混用.then(),可简化代码:

async function messageContentScript(instruction) {
  const message = {"action": "executeAction", instruction};
  let tab = await chrome.tabs.get(runningTabID);
  if(tab.status !== "complete") {
    await waitForUpdate(runningTabID);
  }
  // 直接await获取响应并处理
  try {
    const response = await chrome.tabs.sendMessage(runningTabID, message);
    await playResponse(response);
  } catch(e) {
    errorResponse(e);
  }
}

关键要点

  • 当onMessage监听器需异步处理(如调用异步函数、返回Promise)时,必须返回true,保持消息通道开放直到调用sendResponse。
  • 若executeAction是异步函数,一定要用await等待执行完成,否则try/catch无法捕获其抛出的错误。
  • 后台脚本中使用await chrome.tabs.sendMessage()可更直观获取响应,避免回调嵌套。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:10:52