1

Following on from this SO question I am now connecting and disconnecting the port to my native host based on when a user opens or closes a website tab. I do not know how to reconnect the port.

Originally when I only opened the port once I had;

if (typeof port !== 'undefined') return;
port = chrome.runtime.connectNative('name_to_host');

Now I have added port.disconnect(); when the user closes a certain tab or navigates away from the website.

This port is then still an object but is in a disconnected state.

What am I supposed to do with it now? Can I somehow "dispose" the port object or can I reconnect somehow?

darbid
  • 2,545
  • 23
  • 55
  • Thanks but I have that in my question already. What then? How do I reconnect? – darbid May 06 '20 at 17:59
  • Ah. Sorry, I don't understand the question. Usually there's no need to dispose of anything in JavaScript. – wOxxOm May 06 '20 at 18:01
  • 1
    There's no such thing as "reconnect" either. Simply call connectNative again and assign it to the same variable or to another one, depending on what you want to do. – wOxxOm May 06 '20 at 18:03
  • Ok great. So the port object has no state property? You either try to send a message and get an error or need to keep track through you code when it is disconnected, for example by listening to onDisconnect – darbid May 06 '20 at 18:10
  • Yep, do that as [there's no state](https://developer.chrome.com/extensions/runtime#type-Port). – wOxxOm May 06 '20 at 18:14

1 Answers1

0

This question probably shows my lack of knowledge of Javascript, however for anyone landing here from Google here is what I am doing.

Backgound: I am opening and closing my port to a native messaging host based on a website. Simply put the host is not always running, therefore I am opening and closing the post.

In my code to open the port and thus start the host I still have

if (typeof port !== 'undefined') return;
port = chrome.runtime.connectNative('name_to_host');

Where I have code sending a message I have the following;

if (typeof port !== 'undefined') port.postMessage({...});

When I want to disconnect the port and thus close the host I have

port.disconnect();
port = undefined;

I realize some may not agree with port = undefined; but this fits with my existing code and seems to work ok.

darbid
  • 2,545
  • 23
  • 55