Answer the question
In order to leave comments, you need to log in
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');
}
});
})
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
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);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question