Consider the content script:
(async () => {
function pause(delay) {
return new Promise((resolve) => setTimeout(resolve, delay));
}
async function myHandler() {
await pause(1000);
return ['something 1', 'something 2'];
}
function waitForMessage() {
return new Promise((resolve) => {
async function onMessageListener(message, sender, sendResponse) {
chrome.runtime.onMessage.removeListener(onMessageListener);
resolve(true);
// The following response is received just fine!
// sendResponse({'results': ['something 1', 'something 2']});
const lines = await myHandler();
const response = {'results': lines};
console.log('Responding', response); // All is fine, {'results': <array of strings>}
sendResponse(response); // However, the popup script receives `undefined`!
}
chrome.runtime.onMessage.addListener(onMessageListener);
});
}
waitForMessage();
})();
Here is the part of the popup script sending the request:
async function requestFromContentScript() {
const message = { type: 'request' };
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tabId = tabs[0].id;
return new Promise((resolve) => {
chrome.tabs.sendMessage(tabId, message, (result) => {
console.log('Got in callback:', result);
resolve(result);
});
});
}
As the comments indicate, if I hardcode the response, it is received by the popup script just fine. However, if the response is computed using an asynchronous call, the popup script receives undefined. How can this happen?