One of the things I find different and new about HTML5 is the relationship with other technologies.
While all past versions of the markup language work well with JavaScript, HTML5 relies on it to extend its own capabilities beyond simple markup, allowing us to make so much more with it. That is the case for localStorage
.
The localStorage
attribute is part of the Web Storage API, and its function is to save, read and delete data in a key/value format to a database in the client side, kind of like cookies, but better. Way better. Better because it holds up to 5 MB of persistent data in the browser's database with no expiration date.
Also better because is amazingly easy and fast to implement.
// Save data
localStorage.setItem('name', 'value');
// Read data
var data = localStorage.getItem('name');
// Delete data
localStorage.removeItem('name');
That's all!
It even has good browser support, from IE8+, Safari 4+, Firefox 3.5+, Chrome 4+, Opera 10.5 +, iPhone/iPad and Android 2+, but since there is a small chance some older browsers will throw and exception if you use these functions, we'll have to take care of that by testing if localStorage
exists:
try {
localStorage.setItem('name', 'value');
} catch (e) {
return false;
//You can catch the error and do something else.
}
Or use Modernizr:
if (Modernizr.localstorage) {
localStorage.setItem('name', 'value');
} else {
// Do something else
}
This way we can make sure there will be no ugly errors and we can still use it where it's available.
Remembering layout settings, pre-fill web forms, show personalized messages, what you can do with this data, is up to you, possibilities are endless. I use it right here in the comments form, to remember user information, so you don't have to write it again. For more information and examples you can read this great article.
Any questions, suggestions or corrections are welcome!