var text = localStorage.getItem("foo");
if (text === "hello") {
alert("You've been here before!");
} else {
localStorage.setItem("foo", "hello");
}
The system doesn't support storing javascript objects or array though. Happily, this is easily fixed with a combination of JSON.stringify and JSON.parse to move the object to and from a string representation.
var st = localStorage.getItem("foo");
var ob = JSON.parse(st);
if (ob && ob.text === "hello") {
alert("You've been here before!");
} else {
var toSave = { text:"hello", other:[1,2,3] };
localStorage.setItem("foo", JSON.stringify( toSave ) );
}
You can clear the contents by using the localStorage.clear() method.
There's a simple demo HTML5 local storage in action available here
No comments:
Post a Comment