Reply send from runtime.onMessage handler is not received by sender

I'm converting my extensions and I've noticed that no reply is being send when I send message between different contexts of my extension.

Steps to reproduce:
1) open background script console and execute:
Code Block
browser.runtime.onMessage.addListener(x => {
if (x === 'hello') {
console.warn(x);
return Promise.resolve('ok');
}
});

2) open extension page and in the console execute this:
Code Block
await browser.runtime.sendMessage('hello');

Background console will correctly print "hello" but the extension page won't receive the reply "ok".

Is sending responses from runtime.onMessage handler not supported in Safari?
MDN: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage

Replies

You can get the responses to work by using the sendResponse callback. If you look at the browser compatibility table for onMessage listener you will see that responses via promises only natively work on Firefox (and if you're using a browser. polyfill then the promise response works for chrome too).
You can do something like this for safari:

Code Block
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (x === 'hello') {
console.warn(x);
performAsyncOperation(function callback() { sendResponse('ok') })
// need to return true if you plan on sending a response asynchronously
return true;
}
if (x === 'bye') {
sendResponse('ok')
// no need to return anything here, since we send the response synchronously
}
});

  • I wonder if it would be possible for you to post a version of the above that uses 'async/await' - ie where the listener cannot 'return true'.

Add a Comment
Promises are natively supported by Safari too. This might be a bug. Can you send a sample extension via Feedback Assistant so we can look at fixing this? Thanks!