0

I would like to check if another extension is enabled. I understand Management API can be used to check if another extension is enabled (Detect if another Chrome Extension is installed). However, I try to request for minimum permission and therefore I would like to ask if I can use message passing.

Extension A

let extPort = chrome.runtime.connect(ExtB);
extPort.postMessage({from: "ExtA", fn: "greeting"});
extPort.onMessage.addListener(function(message, sender) {
    if ((message.from == "ExtB") && (message.fn == "greeting")) {
        console.log("Ext B is enabled");
    }
});

Extension B

chrome.runtime.onConnectExternal.addListener(function(port) {
    port.onMessage.addListener(function(message, sender) {
        if ((message.from == "ExtA") && (message.fn == "greeting")) {
                port.postMessage({from: "ExtB", fn: "greeting"});
        }
    });
});

This method works fine if Extension B is enabled but an error message is shown if Extension B is NOT enabled. Any way to handle this error message?

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
kary
  • 11
  • 3
  • Error message contains an obvious hint how to fix it: just check `runtime.lastError` inside your `onMessage` listener (adding it into your `if` statement is enough) – hindmost Feb 03 '20 at 10:22
  • I am sorry. Could you please give me more hints? The error message happens for `let extPort = chrome.runtime.connect(ExtB);` and there is no callback function for `chrome.runtime.connect` – kary Feb 03 '20 at 15:57
  • I wrote: **onMessage** listener, not `connect`'s. Did you really write the above code yourself? – hindmost Feb 03 '20 at 21:02
  • Thanks for your help first =) I am new to Chrome extension. The issue is solved after your motivation on me to check on chrome API spec. As what I have mentioned, this error happens for `let extPort = chrome.runtime.connect(ExtB);` and because there is no runtime.onConnect event listener (ext B is not enabled). Adding checking inside onMessage listener does not fix the issue, as the port / connection does not set up properly. The checking should be added in onDisconnect listener. – kary Feb 04 '20 at 04:16

1 Answers1

0

Checking on chrome.runtime.lastError should be added in onDisconnect listener.

extPort.onDisconnect.addListener(function(object) {
    if (chrome.runtime.lastError) {
        extPort.disconnect();
    }
}); 
kary
  • 11
  • 3