I'm trying to prevent loss of information when the user doesn't press Save and the chrome extension popup is closed or navigates away to a different tab. I save the text from the popup and put it back once the popup is opened again.
So, I have this code to detect closed popup in background.js:
var backgroundPage = chrome.extension.getBackgroundPage();
window.addEventListener("unload", function() {
if(saved === false) {
var savedText = document.getElementById('textbox').value;
localStorage.setItem('text', savedText);
backgroundPage.console.log(localStorage.getItem('text'));
}
}, true);
In another function, once the popup is loaded again, I set the data back by
if(localStorage.getItem('text') !== "") {
document.getElementById('text').value = localStorage.getItem('title');
}
But, this works only sometimes. I have seen other posts that chrome has a bug re: detecting unload events. But, the problem I am seeing is strange. When I do not have my background page inspect view open, the data is not being displayed in the textbox in the popup after navigating away and re-opening it. But, if I have my background page inspect view open, the data is showing up in the textbox...I am new to Chrome extension development, could someone please help me out with this issue?
I also tried the other suggestions of setting up ports for messaging, but not sure how to do this correctly. In background.js:
port.onDisconnect.addListener(function() {
backgroundPage.console.log("Disconnected");
})
Do I need anything else? Where do I set the up the port and chrome.runtime.onConnect? What is the code for this?