Monday, 6 September 2010

HTML5 Local Storage

There are a number of different technologies for storing data locally in the web client. Cookies, SQLite (in those browsers that support it), the offline cache manifest, and also 'Local Storage'. If you simply want to store some name-value pairs, such as user config data, local storage is by far the simplest option. Up until today we had been using Brian le Roux's lawnchair for local storage, which we used in the mode where it wraps SQLite (specifically the Webkit version). The fact that all requests were asynchronous, while nice in most situations, didn't fit our model. So I've switched to localStorage instead, which has the added bonus of being ridiculously simple.

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