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:
- content.js sends a message request to background.js and waits for a response
- background.js receives the message
- background.js fetches data via http request
- background.js sends resolved promise back to content.js
- content.js receives response and logs the data