I'm working on an extension that does a lot of message-passing between its content scripts and the background service worker (manifest V3), and I've noticed an odd issue with the new Promise-based V3 APIs, specifically with the sendResponse() function.
With API calls that expect a response, everything works fine. But if I don't need a response and don't provide a callback function or use the promise's .then() method (or async/await), a Promise error is thrown - it says "The message port closed before a response was received."
Strangely, the call still works, so I guess this error is more like a warning.
Code example:
In a content script, sending a message to the background:
chrome.runtime.sendMessage({ type: 'toggle_setting' })
The background script gets the message and does something, then exits without sending a response:
chrome.runtime.onMessage.addListener( (message, sender, sendResponse) => {
if (message.type === 'toggle-setting') {
//* do whatever it does
}
})
That background code is what throws the error described above. But if I add one line to it and call the sendResponse() function with no parameters, no error happens.
chrome.runtime.onMessage.addListener( (message, sender, sendResponse) => {
sendResponse()
if (message.type === 'toggle-setting') {
//* do whatever it does
}
})
So this gets rid of the error messages, but I'm not really clear on why it's necessary when there is no response needed or expected. Is there some other way to signal that to the Promise-based V3 APIs, or is it now necessary to call sendResponse() even if you don't need to?