citar88
citar88

Reputation: 73

localStorage resets after close browser

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?

Upvotes: 1

Views: 9033

Answers (3)

Kurono
Kurono

Reputation: 1

I encountered the same problem, I'm also developing my personal web app, I fixed it with this code, I hope it helps.

let oldStorage = localStorage.getItem('myStorage') || '';
let newStorage = [...oldStorage];
console.log(newStorage);

Upvotes: 0

citar88
citar88

Reputation: 73

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).

Upvotes: 3

joshmoto
joshmoto

Reputation: 5128

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/

Upvotes: 0

Related Questions