Dave Stein
Dave Stein

Reputation: 9316

Can a callback to onMessageExternal.addListener be async?

I have a Chrome extension running along with a simple webpage. I send a message to the extension, at which point the extension does something async. The below code doesn't work because the callback on sendMessage immediately fires, before my promise resolves. Is there any way around this? Or do I need to manually send a message back from the extension to the browser?

Webpage:

chrome.runtime.sendMessage(editorExtensionId, {action: "share"}, function(response) {
    console.log(response);
  // var promise = navigator.mediaDevices.getUserMedia({audio:true, video:true});
});

Extension:

chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
  var promise = new Promise((resolve, reject) => {
    if (request.action === 'share') {
      chrome.desktopCapture.chooseDesktopMedia(["screen","window"], (streamId, options) =>{
        resolve(streamId);
      });
    } else {
      reject('Bad action');
    }
  }).then(resp => {
    sendResponse(resp);
  });
});

Upvotes: 0

Views: 256

Answers (1)

Iván Nokonoko
Iván Nokonoko

Reputation: 5118

According to documentation, the sendResponse function

becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called)

Therefore, your extension code would be something like:

chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
  var promise = new Promise((resolve, reject) => {
    if (request.action === 'share') {
      chrome.desktopCapture.chooseDesktopMedia(["screen","window"], (streamId, options) =>{
        resolve(streamId);
      });
    } else {
      reject('Bad action');
    }
  }).then(resp => {
    sendResponse(resp);
  });

  return true;  //<-- add this

});

Upvotes: 1

Related Questions