Connection-based native messaging doesn't work in popups

Hello,

I’ve got native messaging fully working in background scripts, sidebars and option pages of my WebExtension. When using the exact same code in a popup however, an exception is thrown and I can’t receive any incoming messages. This only applies to connection-based messaging, connectionless messaging works as expected.

Here’s the code I’m using:

window.addEventListener("load", function() {
  var message = "ping";
  var port = browser.runtime.connectNative("MyApp");
  
  port.onMessage.addListener(function(response) {
    console.log("Message received: " + response);
    
    port.disconnect();
  });
  
  console.log("Message sent: " + message);
  port.postMessage(message);
});

And the exception I’m getting is:

[Exception... "Component returned failure code: 0xc1f30001 (NS_ERROR_NOT_INITIALIZED) [nsIMessageSender.sendAsyncMessage]"  nsresult: "0xc1f30001 (NS_ERROR_NOT_INITIALIZED)"  location: "JS frame :: resource://gre/modules/MessageChannel.jsm :: sendMessage :: line 530"  data: no] (unknown)
  sendMessage resource://gre/modules/MessageChannel.jsm:530:9
  sendMessage resource://gre/modules/ExtensionCommon.jsm:249:12
  _sendMessage resource://gre/modules/ExtensionChild.jsm:227:12
  postMessage resource://gre/modules/ExtensionChild.jsm:169:5
  onConnectNative/< resource://gre/modules/NativeMessaging.jsm:238:38
  emit resource://gre/modules/EventEmitter.jsm:152:11
  _startRead/this.readPromise< resource://gre/modules/NativeMessaging.jsm:278:9

Does anybody know why this happens in popups, while the code works everywhere else? Is it an intended restriction or a bug?

It may be an intentional restriction, since I believe popups are run with the same permissions as content scripts, so they have limited API access. On the other hand, the exception in the console suggests it may be an unhandled case.

I think it would be a good idea to file a bug report for this.

Thank you, Jorge. I have filed Bug 1382069.

I’m tending toward it being a bug, because native messaging in popups does work fine using connectionless messaging (browser.runtime.sendNativeMessage()).

Could you use this line to open the connection?:

var port = browser.extension.getBachgroundPage().browser.runtime.connectNative("MyApp");

If that works, it’s actually a problem with the broeser API of the panel.

Yes, opening the connection this way does get rid of the exception and I can successfully send and receive messages, without changing anything else in the code. Thank you, Niklas. I think I’ll use this as a workaround until it gets fixed.