首页 > web前端 > js教程 > 为什么 Chrome 扩展程序的 onMessage 监听器中的 `sendResponse` 不等待我的异步函数?

为什么 Chrome 扩展程序的 onMessage 监听器中的 `sendResponse` 不等待我的异步函数?

Patricia Arquette
发布: 2024-11-26 04:02:08
原创
557 人浏览过

Why Doesn't `sendResponse` Wait for My Async Function in a Chrome Extension's `onMessage` Listener?

sendResponse 不等待异步函数或 Promise 的 Resolve

问题:
sendResponse() 的异步问题contentscript.js 中不会暂停,直到 getThumbnails()返回。此外,getThumbnails() 中的 Payload 经常为 null,这表明潜在的执行不完整。

分析:
Chrome 在 ManifestV3 和 ManifestV3 中都不支持 onMessage 监听器的返回值中包含 Promises V2。这意味着异步侦听器返回的 sendResponse Promise 被忽略,并且端口立即关闭。

解决方案:
要使侦听器兼容:

  1. 从 onMessage 事件中删除 async 关键字监听器。
  2. 创建一个单独的异步函数并从事件监听器调用它。例如:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.message === "get_thumbnails") {
    processMessage(msg).then(sendResponse);
    return true; // keep the messaging channel open for sendResponse
  }
});

async function processMessage(msg) {
  console.log('Processing message', msg);
  // .................
  return 'foo';
}
登录后复制

要修补 API 以允许异步/Promise 侦听器:

  1. 将以下代码添加到顶部每个使用的脚本chrome.runtime.onMessage:
if ('crbug.com/1185241') { // replace with a check for Chrome version that fixes the bug
  const {onMessage} = chrome.runtime, {addListener} = onMessage; 
  onMessage.addListener = fn => addListener.call(onMessage, (msg, sender, respond) => {
    const res = fn(msg, sender, respond);
    if (res instanceof Promise) return !!res.then(respond, console.error);
    if (res !== undefined) respond(res);
  });
}
登录后复制
  1. 然后您可以简单地从异步侦听器返回值:
chrome.runtime.onMessage.addListener(async msg => {
  if (msg === 'foo') {
    const res = await fetch('https://foo/bar');
    const payload = await res.text();
    return {payload};
  }
});
登录后复制

以上是为什么 Chrome 扩展程序的 onMessage 监听器中的 `sendResponse` 不等待我的异步函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板