D
D
drinkcsis2012-10-10 08:34:03
Google Chrome
drinkcsis, 2012-10-10 08:34:03

Chrome extensions. Persistently open chrome.tabs.connect() port. How?

Hi Dear! Straight to the point. in my extension for Google Chrome, I need a permanently open port for popup.html communication (that is, the part that appears when you click on the extension icon in the manifest is “default_popup”) and the part that works directly on the tab itself (the background part in the manifest is content_scripts {"js":["background.js"]}).

Now I have written a code in popup.html that creates a connection (as I understand it, it starts when you click on the extension icon at the time the popup is displayed), the code is as follows:

chrome.windows.getCurrent(function(w){
    chrome.tabs.getSelected(w.id,function(t){        
        port = chrome.tabs.connect(t.id);         
        port.onMessage.addListener(Answer);
    });
}); 

that is, it creates a port and subscribes to message sending events.

And in the background script (background.js) there is this code:

chrome.extension.onConnect.addListener(function(port){   
    window.port = port;
    port.onMessage.addListener(Question);   
});


that is, it waits for the connection creation event from the extension and, if it occurs, subscribes to the event of sending a message to the created port.
It all works well and they are “intertwined” with messages, BUT ...

Attention question:
If I click anywhere on the tab (on the site), then the extension window naturally disappears and the connection breaks. All other attempts to send something on this port from backround.js end with a message in the console “Uncaught Error: Attempting to use a disconnected port object „
How do I make a persistent connection? It is alive until the extension window is closed, how can I make it so that I calmly click on the site and the extension window is open?

PS The question is very urgent, if you need clarification, write in a personal. Thanks a lot to everyone!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2012-10-10
@k12th

The popup is initialized every time it is opened and destroyed when it is closed. There is no way to get around this, except that when the port is closed, start adding messages to the queue and send them all when opened.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question