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

How to turn off Ringbacks on Rogers

Rogers just update you to the latest iPhone value pack, or figure out some other way to stick you with their ringbacks service, and you’re desperate to find out how to turn it off? They don’t want to make it easy — they want you to pay money for more Ringbacks — but after over an hour of waiting on 3 different customer service and tech support reps, I got the answer. Here it is: From your Rogers iPhone, text 555 with the word OFF. You’ll get an autoreponder with a link to http://rogers.com/ringbacksoff Tap the link. You need to be on Rogers’ network (i.e. not Wi-Fi) to access this page! Scroll down to the bottom and turn OFF both Ringbacks and Voice Greetings. (Yes, Ringbacks are so annoying they require and additionally annoying Voice Greeting to beg the people who call you not to hang up while they’re annoyed by the Ringback.) Rogers tried to get me to give Ringbacks a chance, saying if I loved the Beatles and my friends new I loved the Beatles, I could entertain them w...

How to Reload Operating System on Nuked or Bricked BlackBerry

Good Afternoon Class! I’ve been a bit slack in my  BlackBerry 101  lectures as of late – I blame the  Smartphone Round Robin , all the  Contests  we’ve been running on the site and the busy Holiday Season. My apologies! This will be the last 101 lecture of the year… but we’ll be back in 2008 bigger and better than ever. Today’s lecture isn’t really a “newbie” topic, but it’s one that I wanted to cover because in the past three weeks I’ve gone through it half a dozen times and that is  Reloading the Operating System on a BlackBerry that’s totally “Nuked” . I’m not sure if nuked is the technically appropriate word for it (I also use one that starts with an F and ends in an ED and has a CK in the middle), but it is how I refer to a BlackBerry that is stuck in a permanent reboot cycle and is completely, completely unusable. With a Nuked Berry, essentially the device turns on (red LED comes on for a few seconds), then you see the white screen with the hou...

Best Ipad and Iphone Photography Apps

Longtime Exposure Calculator Price: Free/ Available for iPhone, iPod touch, iPad Long-exposure photography fanatics will know that an ND filter can be essential when it comes to extending exposure time for those all-important open shutter shots. Longtime Exposure Calculator by HPR-Solutions is a free iPhone,iPad and iPod touch app that enables you to dial in a projected shutter speed to one column and then 'add' an ND filter as graded in both f/stops and filter names (eg 3 stop or ND8) in the other column. The app then calculates the adjusted exposure. While it is, in part, possible to TTL meter with an ND filter attached to the front of a camera's lens, the results won't always be accurate, and there's a point where things get so dark that it's not possible - especially with in-vogue super-dense filters. Having an off-camera calculation method such as this makes it quick and easy to figure out exposures without so much as needing to put those brain...