Once an event is triggered in my content script, it send a message request to the background script and waits for a response.
content.js
chrome.runtime.sendMessage({ userId: userId }, function (response) {
console.log(response);
});
background.js:
chrome.runtime.onMessage.addListener(function (
request,
sender,
sendResponse
) {
const userId = request.userId;
if (userId) {
fetchData(userId).then((data) => {
sendResponse({ response: data });
});
return true;
}
});
I've tried async/await, moving the "return true" to outside the if statement, but in my content script the response is either undefined (even though fetchData returns the correct data), no response, or the error "the message port closed before a response was received extension".
The flow I want is:
The issue turned out to be changing tabs in the popup before the response was received. I fixed it by moving the command to change the popup tab (window.open()) to be in the response, after processing the response data.