Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

javascript - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...