sendResponse 不等待异步函数或 Promise 的 Resolve
问题:
sendResponse() 的异步问题contentscript.js 中不会暂停,直到 getThumbnails()返回。此外,getThumbnails() 中的 Payload 经常为 null,这表明潜在的执行不完整。
分析:
Chrome 在 ManifestV3 和 ManifestV3 中都不支持 onMessage 监听器的返回值中包含 Promises V2。这意味着异步侦听器返回的 sendResponse Promise 被忽略,并且端口立即关闭。
解决方案:
要使侦听器兼容:
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 侦听器:
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); }); }
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中文网其他相关文章!