Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension, messaging: getting port status

I am trying to get a port's status in an application (not a content script). When I do :

this.port = chrome.runtime.connect("okcbadfdlhldjgkbafhnkcpofabckgde");

I get a valid port object but I can't find anyway to determine if the port can be used at all (I don't even get a disconnect event if the extension can't be reached).

The only way I figured out to have the connectivity state is to actually trap an exception when performing a this.port.postMessage.

Is there a better way ?

https://developer.chrome.com/extensions/runtime#method-connect

Update

  • Running Version 48.0.2564.97 (64-bit) on Linux Ubuntu
  • No cross-extension messaging, just application to/from extension
  • Extension source code but note I have since moved on to implement another strategy for the extension because of the issue raised in this question.
like image 228
jldupont Avatar asked Oct 30 '22 10:10

jldupont


1 Answers

Your extension uses a background-script that provides listener function for the chrome.runtime.onMessageExternal event. This event is used to listen for incoming messages, send from external webpage-scripts (or other extensions) by calling the chrome.runtime.sendMessage method.

Since your extension does not provide a listener function for the chrome.runtime.onConnectExternal event, chrome.runtime.connect cannot work for your extension.

As far as knowing the connection status is concerned, in this case a simple try-catch block would do enough to know whether the extension supports port or not. If it does, you need to view the manifest corresponding to this extension - to see if a particular host is allowed to send messages or not.

I was able to send message to your extension (see the enclosed figure) by adding the following lines of code in the background-script. In addition to this, I also added the matches string for the host - www.example.org in the manifest.

chrome.runtime.onMessageExternal.addListener(
    function(request, _sender, sendResponse) {
        console.log(request);
        ...
    }
);

image-1

like image 65
Patt Mehta Avatar answered Nov 13 '22 06:11

Patt Mehta