Reputation: 53
I'm sending a message from my popup to background which when receives calls an external API and upon response from that api I'm sending a message back to pop up.
Popout
chrome.runtime.sendMessage({
message: "submit",
payload: {
transactions: usersTxs,
}
}, (response) => { ... do other stuff }
background
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === 'submit'){
fetch('https://example.com/api/submit'})
.then((res) => {
sendResponse({ message: true })
return true
})
}
However despite setting return true I'm still getting the following error:
Unchecked runtime.lastError: The message port closed before a response was received
Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
Am I doing something obviously wrong?
Thanks
Upvotes: 1
Views: 13788
Reputation: 77541
You're returning true at the wrong time - in the asynchronous handler that will execute later. Move your return statement:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === 'submit') {
fetch('https://example.com/api/submit'})
.then((res) => {
sendResponse({ message: true })
})
return true
}
Upvotes: 5