HTML5 LOCAL STORAGE
Just like Las Vegas, often what you do in a web page stays in the web page. Let's say you have a simple application that allows me to maintain a to-do list:
[ you can play with this (very buggy) application here ]
If you accidentally navigate somewhere else or close the tab this page was on without first hitting the Save button, any action or information you had inputted would be lost. Bummer.
Because web pages do not persist data, various solutions have been proposed over the years ranging from cookies to 3rd party plug-ins to browser-specific implementations. With HTML5, you have something new - something that everyone hopes will stick! This "something new" is a solution affectionately known as Local Storage.
In this tutorial, you will learn what local storage is and how you can use it to easily store and retrieve data from a user's browser.
How Local Storage Works
Before jumping right into the code, let's take a few moments and first learn how local storage actually works.
At the core, each of your pages has a reference to a global object calledlocalStorage:
If you step inside this object, what you will see is a well-oiled machine that is designed for storing data. The way it stores the data is by neatly organizing them into rows of key/value pairs.
The following is a visualization of me storing some information about my arch-nemesis:
In the above localStorage visualization, you can see that there are three pieces of data:
- firstName with a value of Bugs
- lastName with a value of Bunny
- location with a value of Earth
Think of each row as one contiguous piece of data made up of a key and a value. The key serves as the identifier to your data, and the value is the information associated with it. You'll see the key/value interactions more as we look at some examples.
An important thing to note is the scope of this data. The localStorage data is domain-specific where you have only one instance per domain. In other words, any data inside your localStorage object is available only when you are referring to it from a page hosted within the same domain.
If I am storing the firstName, lastName, and location data on www.kirupa.com, I will only be able to access these keys when a page that refers to these keys is hosted on www.kirupa.com. If I am on a subdomain (kirupa.com) or another domain altogether such as (google.com), I won't be able to access these entries at all. The data won't exist or, as is the case with common key names, the data will exist but be different and specific to this new domain.
Code for Working with Local Storage
Now that you have a basic idea of what the localStorage object is, let's look at the code for how you will add and retrieve data from it.
Adding Data
To add data to your local storage object, all you need is a key and a value...and thesetItem method that lives on your localStorage object:
- localStorage.setItem('firstName', 'Bugs');
- localStorage.setItem('lastName', 'Bunny');
- localStorage.setItem('location', 'Earth');
In each line, we are adding a key/value pair to our localStorage object. The setItem method takes two arguments. The first argument is the key, and the second argument is the value.
After running this code, your localStorage object will look as follows:
[ this looks familiar...! ]
If you specify a key that doesn't exist, a new key/value pair with the information you provided is created. If you specify a key that already exists, you just overwrite the existing data the key points to with the new data.
Retrieving Data
To retrieve data stored in your localStorage object, you use the getItem method:
- var firstNameData = localStorage.getItem("firstName");
- var lastNameData = localStorage.getItem("lastName");
- var locationData = localStorage.getItem("location");
The getItem method takes only the key as an argument, and it returns the value associated with that key. If the key you pass in does not exist, a value of undefinedis returned.
Note
If you don't like using the getItem or setItem methods, you can bypass them by using object notation for setting and retrieving data:
- // storing data
- localStorage[key] = value;
- // retrieiving data
- var myData = localStorage[key];
Whichever approach you take is entirely up to you!
Now, back to our regularly scheduled programming.
Removing Data
There are two extremes to removing data from your localStorage object. You can remove everything scorched earth style, or you can selectively remove a key/value pair individually.
Because scorched earth is an awesome game, let's look at it first. To remove everything from your localStorage for your current domain, you can call theclear() method:
- localStorage.clear();
This will remove all traces of any data you may have stored for this domain, so use it cautiously if you have several pages on your site that each write to the local storage independently.
To remove only select key/value entries from your local storage, you can useremoveItem() and pass in the key name associated with the data you wish to remove:
- localStorage.removeItem("location");
In this example, the location key and its value will be deleted while leaving all of the other data intact.
Dealing with File Size
You have a fixed size of 5 MB for each domain your local storage is tied to. If you try to add more data even after you have exceed your quota, a QUOTA_EXCEEDED_ERRexception will be thrown.
Handling this exception is pretty straightforward:
- try {
- localStorage.setItem("key", "some data");
- } catch (e) {
- if (e == QUOTA_EXCEEDED_ERR) {
- // do something nice to notify your users
- }
- }
All you need to do is wrap any code that tries to add more data to your localStorage into a try/catch statement. While just catching the exception will prevent users from seeing a script error, matching the exception to the QUOTA_EXCEEDED_ERRexception will allow you to go one step further and let your users know why they were not able to save the data to local local storage.
Detecting Whether Local Storage Exists or Not
The last thing we are going to do is talk about detecting whether someone's browser supports local storage or not.
Here is the code for doing this detection:
- function isLocalStorageSupported {
- try {
- var supported = false;
- if (window['localStorage'] !== null)
- {
- supported = true;
- }
- return supported;
- } catch(e) {
- return false;
- }
- }
A call to the isLocalStorageSupported function will return a value of true if local storage is supported, and if local storage isn't supported, you will see a value offalse.
The way I detect is pretty simple. I just check if your window has a localStorage object. If it does, then localStorage is supported by the browser. If it doesn't, then localStorage is not supported.
If you don't feel like writing this code, you can rely on a 3rd party library like modernizrto handle detecting whether this feature (along with many others) are supported or not.
Comments
Post a Comment