HTML5 : LocalStorage Tutorial

Today, we are covering on how to store some simple data and move on to more complex data structure like an object into HTML5 local storage system. What the heck is local storage? Well in short summary , LocalStorage is a handy API included in the “HTML5” wave that gives web developers an easy to use 5MB store on an users local machine. In other words is way much better than storing app related information in cookies.

We can easily store key and value pair into a localStorage, here is how. In the source code below, context “name” is known as a key, “Hello World” string is our value.

1
2
localStorage.setItem("name", "Hello World!"); //saves to the database, key/value
console.log(localStorage.getItem("name")); //Hello World!

So how do we store a more complex data like object and arrays? Let’s write a prototype extension and name it localStorage.js. This should be loaded before we even use our localStorage command. Code below extend existing localStorage to cater for objects by using JSON.stringify method.

1
2
3
4
5
6
7
Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}
 
Storage.prototype.getObject = function(key) {
   return JSON.parse(this.getItem(key));
}

Then you can just use the method set/get Object to do like code below. That’s about it for today, happy storing 🙂

1
2
3
4
5
6
var dataObject = new Object();
dataObject.id = 1;
dataObject.name = "Alex";
 
localStorage.setObject("myDataObject", dataObject); 
console.log(localStorage.getObject("myDataObject"));

For today’s localStorage.js and how to use it source code…
localStorage Demo file (828 downloads)

Comments

comments