The callback of onMessage should return a literal true
value (documentation) in order to keep the internal messaging channel open so that sendResponse can work asynchronously.
Problem
Your callback is declared with async
keyword, so it returns a Promise
, not a literal true
value. Chrome extensions API doesn’t support Promise in the returned value of onMessage callback until https://crbug.com/1185241 is fixed so it’s just ignored, the port is immediately closed, and the caller receives undefined
in response.
Solution
Remove the async
keyword and use a standard function, from which you can call another async function that can be embedded as an IIFE:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "get_thumbnails") {
(async () => {
const payload = await getThumbnails();
console.log("thumbPayload after function:", payload)
sendResponse({payload});
})();
return true; // keep the messaging channel open for sendResponse
}
});
Or declare a separate async
function and call it from the onMessage listener:
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';
}