Skip to main content

HTML 5

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:
a to-do list example
[ 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:
the local storage object 
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:
key value pairs
In the above localStorage visualization, you can see that there are three pieces of data:
  1. firstName with a value of Bugs
  2. lastName with a value of Bunny
  3. 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:
key value pairs
[ 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

Popular posts from this blog

Ipad apps: AppStart Review

AppStart For iPad Review Free for a limited time only , AppStart for iPad is a terrific app by the folks over at  AppAdvice.com  that’s meant to serve as a starter guide for new iPad users and owners. The promotion is only available for a limited time as customers flock to pick up their iPad 2s this week. Whether you’ve had your iPad since launch day or you just picked one up, AppStart For iPad is a detailed and comprehensive guide for the most popular and useful ways to utilize your iPad in addition to recommending a few apps to get your feet wet. When you first open the app, the home screen is displayed in a clean grid of buttons for you to tap-in and find out everything there is to do with the iPad. Each grid-box allows you to open up a mini-guide for how you can use your iPad as an eReader, home theater, radio, nightstand, magazine, or social media hub. Within each mini-guide, the folks over at App-Advice also throw in their suggestions for both free and paid apps that re...

Ipad 2 Accesories

Zagg have done it again and released what we are excited to say is the seasons MUST HAVE iPad accessory: The  ZAGGmate iPad case with keyboard . It’s not often that we get entirely blown away by an accessory for the iPad, but this one has left us shell shocked and in awe. The perfect compliment to your iPad, this is the first iPad keyboard case combo that we have seen yet that has done it right. In fact, it’s the best bluetooth keyboard we’ve seen to date as well! It’s so right and so perfect that we already wonder how we ever used our iPad without it! Check out the review below… ZAGGmate with Keyboard The iPad’s New Best Friend Our first impression of the ZAGGmate was: “Where’s the rest of it?” This iPad case is unlike anything else we’ve seen on the market to date and the designers at Zagg worked hard to literally rethink what an iPad case could be. This is an iPad case that doesn’t cover the whole iPad, but rather just covers the iPad’s screen, and leaves the back of the tablet...

Ipad 2 Apps: Skyfire Web browser Review

Ipad 2 Apps: Skyfire Web browser Review Skyfire for the iPad made headlines when it was first released, due to its ability to play Flash videos on a device previously void of this popular technology. Users flocked to the App Store, eager to drop five bucks for the chance to view their favorite clips, shows, and movies on their iPad. Not only did the browser play these videos, but the integrated video compression saved a significant amount of bandwidth for people on a restricted data plan. The initial excitement wore off quickly, though, as complaints were rampant about many sites not playing videos as expected. Since its inception Skyfire has certainly improved in this area, now claiming support for over 200,000 websites containing Flash. The dissenters will always be there as not every Flash video on the Web will be playable, even if the developers at Skype Labs remain diligent. Some of the backlash is warranted to a certain extent. If I paid $4.99 with the intent of viewi...