An Introduction to HTML5's localStorage
Did you know that localStorage works as far back as Internet Explorer 8? There's no good reason to not be using it!
Let's start out by saving a very simple piece of information to local storage, like so:
Then to retrieve it just do this:
Beautiful. Simple. Easy.
The Next Level
Okay, so you've just saved and retrieved a single piece of information. Let's see what else we can do.
You should know that localStorage is only capable of saving strings. Numbers get converted into strings and objects will save as the string, "[object Object]".
But, we can use the
JSON.stringify() function to turn an object into a string, which can then be saved to localStorage.
If you do
localStorage.getItem('user'); right now, it will return the stringified object:
This isn't quite what we want, so we'll use the JSON.parse() function to convert it back into an object:
Now you've received your object back in a usable form!
Clearing the Storage
When the browser's cache is cleared, all localStorage is erased.
To manually erase all localStorage do this:
To erase a specific localStorage item, do this:
Max Storage Size
There is a maximum size for the information saved to localStorage. In Google Chrome it's 2.5 MB per origin, in Mozilla Firefox and Opera it's 5 MB per origin and in Internet Explorer it's 10 MB per origin. 'Per origin' meaning per domain (www.yoursite.com) on a single visitor's browser.
I hope you found this useful. Local storage is a great alternative to cookies and the browser support for it is great, which means you can start using it in real projects right now!
Posted on December 21st, 2013