Troubleshooting "sendResponse not waiting for async function or Promise's resolve"
Issue:
Chrome's chrome.tabs.sendMessage's sendResponse function does not wait for asynchronous functions or Promise resolutions.
Problem Analysis:
In the provided code, the getThumbnails function within the content script (contentscript.js) is an asynchronous function that takes time to execute. However, the sendResponse function in the onMessage listener is invoked immediately, potentially before getThumbnails has completed its execution. This leads to sendResponse returning undefined or null in response.
Solution 1: Remove Async Keyword and Declare Separate Async Function
Solution 2: Patching the API for Async Listener
Implementation in Contentscript.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.message === "get_thumbnails") { getThumbnails().then(payload => { sendResponse({ payload }); return true; // Keep messaging channel open for sendResponse }); } }); async function getThumbnails() { // Your code to retrieve thumbnails }
Implementation with Patch:
// Patch to allow async/Promise listener if ('crbug.com/1185241') { // Replace with Chrome version check const { onMessage } = chrome.runtime; 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 How to Resolve \'sendResponse not waiting for async function or Promise\'s resolve\' in Chrome\'s `chrome.tabs.sendMessage`?. For more information, please follow other related articles on the PHP Chinese website!