html5 localstorage and how to use it

David Jones
@david3jones
avatar-davidejones

I’m still very new to html5 this is mostly due to the constraints of the projects I work on, however I have been slowly breaking these boundaries down and showing my colleagues and superiors exactly what is possible today. The most intriguing thing about html5 that i’ve learnt about is the offline storage or local storage. This is a great new addition that allows a kind of localised database to be accessed using some simple javascript methods. While I admit i’m not completely convinced of the security of using this kind of access i definitely welcome it as a new storage addition and in fact if used in the correct way could solve alot of potential problems. Heres a quick intro to using the localStorage. Testing if the browser supports it This is still a new feature and not all browsers will be supporting it right now so it would be wise to check first before performing any actions.

if (typeof(localStorage) == 'undefined' )
{
    	//not supported
} else {
    	//supported
}

another method could be to try this

if(localStorage)
{
    	//supported
}

Storing a value With each piece of data you store you need a key to reference this just as you would in an associative array heres a couple of ways to do this.

//method 1
localStorage.setItem("keygoeshere","valuegoeshere");
//method 2
localStorage["keygoeshere"] = "valuegoeshere";

Retrieving a value Accessing this data is just as simple all you need it the key and you can either use getItem or access the item as an associative array as before.

//method 1
alert(localStorage.getItem("keygoeshere"));
//method 2
alert(localStorage["keygoeshere"]);

Comments

    Comments are currently closed