Home >Web Front-end >JS Tutorial >Why Doesn\'t `sendResponse` Wait for Async Functions in Chrome\'s `chrome.runtime.onMessage`?
sendResponse Not Waiting for Async Function or Promise's Resolve
This issue arises when using chrome.runtime.onMessage with an async function or a Promise that returns the result in the listener. Chrome currently does not support Promises in the returned value of onMessage for both ManifestV3 and V2.
Root of the Problem
The onMessage listener expects a literal true value to keep the messaging channel open for the sendResponse function. However, when the listener is declared as async, it returns a Promise, which is ignored by the onMessage implementation, effectively closing the port and returning undefined to the caller.
Making the Listener Compatible
To resolve this issue, one can eliminate the async keyword from the listener and create a separate async function that is invoked within the listener:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { if (msg.message === "get_thumbnails") { processMessage(msg).then(sendResponse); return true; // keep the channel open for sendResponse } }); async function processMessage(msg) { // Process the message and return the result }
Patching the API
As an alternative, a patch can be applied to the API, allowing for asynchronous listeners:
if ('crbug.com/1185241') { // Check for Chrome version 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); }); }
With this patch, you can return a Promise or value directly from the listener like so:
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 Async Functions in Chrome's `chrome.runtime.onMessage`?. For more information, please follow other related articles on the PHP Chinese website!