sendResponse Waits for Async Functions and Promise Resolves
Problem: In a Chrome extension, sendResponse() in contentscript.js does not pause for getThumbnails() to finish.
Explanation: Chrome's chrome.runtime.onMessage event listener returns a boolean value to indicate whether the channel should be kept open for sendResponse. When an async function or Promise is returned, Chrome ignores the Promise and closes the channel immediately.
Solution: Make the event listener compatible with async functions:
Example:
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) { console.log('Processing message', msg); // ... Handle the message processing here ... return 'foo'; }
Alternative Solution: Patch the API
Add the following code to the beginning of every script that uses 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); }); }
This patch allows the event listener to return an async function or Promise.
The above is the detailed content of How Can I Make `sendResponse` Wait for Async Functions in Chrome Extensions?. For more information, please follow other related articles on the PHP Chinese website!