sendResponse Not Waiting for Async Function or Promise's Resolve
Problem:
Asynchronicity issue where sendResponse() in contentscript.js does not pause until getThumbnails() returns. Additionally, payload in getThumbnails() is frequently null, indicating a potential incomplete execution.
Analysis:
Chrome does not support Promises in the returned value of onMessage listeners in both ManifestV3 and V2. This means that the sendResponse Promise returned by the async listener is ignored, and the port is closed immediately.
Solution:
To make the listener compatible:
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'; }
To patch the API to allow an async/Promise listener:
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}; } });
The above is the detailed content of Why Doesn\'t `sendResponse` Wait for My Async Function in a Chrome Extension\'s `onMessage` Listener?. For more information, please follow other related articles on the PHP Chinese website!