5

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?

llams48
  • 387
  • 2
  • 7
  • 16
  • My guess would be that your background page is an event page. When the inspect view isn't open, Chrome decides to unload the background page, and it's no longer around when "unload" fires. I think `chrome.extension.getBackgroundPage()` (which only makes sense in a popup) loads an event page. In that case, moving that function call into your unload listener may do the trick. – Teepeemm Jul 10 '15 at 04:06
  • BTW, `beforeunload` event is better suited for the purpose, I think. – wOxxOm Jul 10 '15 at 22:24
  • Did you ever figure this out? I solved it for Firefox addons by doing `window.addEventListener("unload", ...)` but it did not work for Chrome. – mc9 Mar 17 '18 at 11:09

0 Answers0