Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage.setItem not persisting on refresh

I'm trying to do a mega-simple setItem and getItem using HTML5 local storage. It just doesn't seem to work though. This works:

$(document).ready(function () {
  localStorage.setItem('keyA', 'valueA');
  var testA = localStorage.getItem('keyA');
  alert(testA);
});

It outputs an alert box saying 'valueA'. But when I comment out line 2 (which sets the item value) and refresh the page it just alerts 'null'.

Why is the value not persisting? It's like it's just not actually getting stored at all.

The browser is Firefox 6, so no problem there. Could it be something to do with calling it in the jquery document.ready? I've googled but couldn't see anything about that.

If anyone could get me over this initial hurdle I'd be most grateful, thanks!

like image 214
Dan Avatar asked Sep 10 '11 20:09

Dan


1 Answers

Okay, after a lot of frustration I have the solution. Basically, I was running this locally just from the filesystem as a 'quick' proof of concept. It didn't work in Firefox nor in IE9 but it did work in Chrome.

What I ended up doing was trying this on a real domain, and that seems to have done the trick.

So the conclusion I can draw is that localStorage in Firefox (6.0.2 at least) and IE9 does not work when run on a file-system path. It does in Chrome. Firefox and IE9 require a 'proper' domain to run from, presumably because they are more strict than Chrome in the way they associate the localStorate object to a 'domain' (in Chrome it doesn't need to be a domain as such).

I hope this has helped people as it's frustrated the hell out of me! :)

like image 75
Dan Avatar answered Sep 19 '22 18:09

Dan