M
M
Martovitskiy2021-04-07 18:30:16
Google
Martovitskiy, 2021-04-07 18:30:16

What is the correct way to listen on a port in a chrome extension?

The task is not to let the tab die, and if the connection to the background page is lost, then reload
background.js

chrome.extension.onConnect.addListener(function(port) {
        console.log("Connected .....");
        port.onMessage.addListener(function(msg) {
             try{
                port.postMessage('active_port');
             } catch {
                port.postMessage('disable_port');
             }
        });
   })


script.js
setInterval(() => {
    try {
        var port = chrome.extension.connect({
            name: "Sample Communication"
        });
        port.postMessage("active back");
        port.onMessage.addListener(function(msg) {
            console.log(msg);
        });
    } catch {
        localStorage.setItem('reload_' + appId, 1);
        location.reload();
    }

}, 5000);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-04-07
@Martovitskiy

Every second, send a message from the content script to the background process: In the background process, listen for incoming messages:
chrome.extension.sendMessage('Ваше сообщение');

chrome.extension.onMessage.addListener(function(message) {
  console.log('Принято сообщение: ' + message);
});

If the link to a particular tab is lost, recreate it or update it.
PS There are other ways to prevent freezing of the tab, if you're interested, I'll tell you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question