localStorage resets after close browser

2019-09-03 09:13发布

问题:

I've developed a local HTML5/JavaScript web application and I'm trying to store data in localStorage.

There are no problems if I close the webapp tab without closing the browser: when I re-open the webapp in a new tab I'm able to find my data in localStorage.

I see in Developer Tools (F12) -> Application that a localStorage object exists and my data are there.

If I close the browser, when I re-open the webapp (restarting the browser too) I lost everything.

I however see in Developer Tools (F12) -> Application that a localStorage object exists, but it's void.

I'm not using the localStorage.clear() instruction and I don't remove any item in my js code.

Browser: I'm using Google Chrome Version 67.0.3396.99 (Official Build) (64-bit) (NOT in incognito mode).

Any idea?

回答1:

Solved:

In my JS code I was using the window.onbeforeunload = function() {...} instruction to prevent browser closing without saving data. I've removed this instruction.

Furthermore, I've deselected the flag "Delete browsing history on exit" from Internet Options.

Now I can restore my data from localStorage even after closing browser and restart my webapp (restarting the browser too).



回答2:

I've not used local storage much but this works for me.

The set_data(); function sets the data in local storage. You fire this when ever you want to save the current page data.

Then when the browser closes and the page reopens, the localStorage.getItem finds any stored data.

var data = localStorage.getItem('my_data');

// for testing
alert(data);

set_data = function() {

  data = localStorage.setItem('my_data', 'whatever');

  // for testing
  alert(localStorage.getItem('my_data'));

}

delete_data = function() {

  data = localStorage.clear();

  // for testing
  alert(localStorage.getItem('my_data'));

}

See working jsfiddle https://jsfiddle.net/joshmoto/j2y8o6rq/