2

I need to send data from popup.js to background.js and after that to send from background.js to popup.js. But if popup.html closed it can't recive data from background.js because port doesn't exist. How to resolve it?

My code:

popup.js

var port = chrome.runtime.connect({ 
name: 'Communication with background.js', 
});

port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
console.log("message recieved" + msg);
});

background.js

chrome.runtime.onConnect.addListener(function(port) {
console.log("Connected .....");
port.onMessage.addListener(function(msg) {
console.log("message recieved " + msg);
port.postMessage("Hi Popup.js");
});
});
2
  • Create the popup on page load but keep it hidden until you need it Commented May 22, 2019 at 20:16
  • @PaulaLivingstone popup.html is part of chrome extension. It works another way Commented May 22, 2019 at 20:25

1 Answer 1

2

Once the popup is gone, not only is the port closed, but the popup.js script is no longer running. You can either store the content in the background.js script (persistent) and each time the popup is loaded, send the relevant information (you already have this partially built out), or you can store the information in local storage and load it every time your popup is loaded.

popup.js or background.js

chrome.storage.sync.set({'dataValue1': 'Some data 1.'});
chrome.storage.sync.set({'dataValue2': 'Some data 2.'});

popup.js

function updatePopup(){
  chrome.storage.sync.get(['dataValue1','dataValue2'], function(data) {
    //Update popupElement1 and popupElement2 with loaded data
    document.getElementById("popupElement1").value = data.dataValue1;
    document.getElementById("popupElement2").value = data.dataValue2;

  });
}

document.addEventListener('DOMContentLoaded', updatePopup);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.