0

I built a Chrome extension using sendRequest to send a message from the content page to the popup, and get a callback.

content.js :

chrome.extension.sendRequest(data, function (result){
    // here the result should be a boolean
    if (result){
        alert("ok");
    }
});

popup.js :

chrome.extension.onRequest.addListener(function (request, sender, callback) {
    // Here I have some asynchronous work
    setTimeout(function(){
        callback(true);
    }, 500);
}

All this worked perfectly fine.

But the sendRequest is deprecated, and needs to be replaced by sendMessage (in order to support Firefox)

I did almost the same thing with sendMessage (documentations are exactly the same for sendRequest and sendMessage on Mozilla doc)

content.js :

chrome.runtime.sendMessage(data, function (result) {
    // here the result should be a boolean
    if (result){
        alert("ok");
    }
});

popup.js :

chrome.runtime.onMessage.addListener(function (message, sender, callback) {
    // Here I have some asynchronous work
    setTimeout(function(){
        callback(true);
    }, 500);
}

But now, it doesn't work. As soon as the listener function ends, the callback is called with no argument, and the asynchronous function can't send its result.

Is there any way to do the same thing in Firefox ?

Xan
  • 74,770
  • 16
  • 179
  • 206
glacasa
  • 1,770
  • 2
  • 16
  • 32
  • This is not WebExtension specific, Chrome behaves the same way. However, in the Chrome docs this is stated, while WebExtension docs are silent. – Xan Mar 22 '16 at 09:23
  • My bad: it's mentioned in the WebExtension docs [under `onMessage`](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Runtime/onMessage): _Returns: boolean. Return true from the event listener if you wish to call sendResponse after the event listener returns._ – Xan Mar 22 '16 at 09:26
  • That's right, it seems to work with the return true, I didn't dig the docs enough. Thanks ! – glacasa Mar 22 '16 at 09:31

0 Answers0