12 - HTML5 Web Storage

With HTML5 web storage, web pages can store named key/value pairs within the web browser. HTML5 has introduced two mechanisms to store data on the client side: local storage and session storage. In case of local storage, the data will persist for ever. In other words, the data will remain even if you navigate away to another application from the website or even close your browser. In case of session storage, the data persists only for the current session.

Previous versions of HTML have been using HTTP session cookies for this purpose. But cookies have a number of drawbacks such as security issues, performance issues and even limitations in the amount of data that can be stored. The two new mechanisms, session storage and local storage, overcome these drawbacks. These two methods are more secure compared to cookies. Also they can be used to store large amounts of data without affecting the performance of the website. However, web storage is per domain. That is, only pages from one domain can store and access the same data. So, you do not have to worry about the privacy of your data.

Local Storage

The local storage allows webpages to store data that needs to persist beyond the current session. Local storage is the best option to store data that needs to be fetched so fast or that does not change so often. For example, an application might have to remember the name of the user and display it as soon as the user opens the application. In that case, local storage will be helpful. You can use the window.localStorage object to store data with no expiry.

Like many other HTML5 techniques, not every browser supports HTML5 web storage also. So, it is good to check the browser support for localStorage before proceeding. The three main methods we need to use are setItem, getItem and removeItem. The setItem method is used to store a value, the getItem method is used to retrieve a value and the removeItem method is used to delete a value. While using the setItem method, you have to pass the key as well as the value. In case of getItem and removeItem methods, you have to pass only the key. If you want to remove all the data stored in local storage, you can use the clear method.

Sample Code:

<!DOCTYPE html>
<html>
 <head>
  <title>Local Storage</title>
  <script>
   function SaveData()
   {
    if(window.localStorage)
    {
     var first = document.getElementById('fName').value;
     var last =  document.getElementById('lName').value;
     window.localStorage.setItem("firstName", first);
     window.localStorage.setItem("lastName", last);
    alert("Data is saved successfully!!!");
    }
    else
     alert("Your browser does not support HTML5 localStorage!!!");
   }
   function GetData()
   {
    if(window.localStorage)
    {                
      var output = "Welcome back " + window.localStorage.getItem("firstName") + " " + window.localStorage.getItem("lastName");
      document.getElementById("result").innerHTML = output;
    }
    else
     alert("Your browser does not support HTML5 localStorage!!!");
    }
    function RemoveData()
    {
     if(window.localStorage)
     {                
       window.localStorage.removeItem("lastName");
       alert("Last name removed successfully!!!");
     }
     else
       alert("Your browser does not support HTML5 localStorage!!!");
     }
  </script>
 </head>
 <body>
   First Name: <input type="text" id="fName" /><br />
   Last Name:<input type="text" id="lName" /><br /> 
   <button id="saveData" onclick="SaveData();">Store Data</button>
   <button id="getData" onclick="GetData();">Get Data</button>
   <button id="removeData" onclick="RemoveData();">Remove Last Name</button><br /><br />
   <div id="result"></div>
 </body>
</html>

Save the file that contains the above lines of code in your localhost folder and access it as localhost/filename.html. Enter first name and last name in the text boxes and click the Store Data button. Then click the Get Data button. You will get a screen like this:

           HTML5 local storage example 01

Now close the browser window and again open it using localhost/filename.html. This time click the Get Data button without entering anything in the text box. You will get a screen like this.

         HTML5 local storage example_2

This means that the data is stored permanently. Now click the Remove Last Name button and click the Get Data button. You will get a screen like this where the value of the last name is removed.

        /HTML5 local storage example 3

Session Storage

In some cases, you might have to store data only for a particular session. Your data might not be relevant after that particular session. For example, you might have to store the level and score of a player for a particular online game. Once the player quits the game, the data is no more relevant. In such cases, you can store data in session storage. You need to use the window.sessionStorage object to store data with expiry. The methods we use with sessionStorage object are the same as with localStorage object: setItem(), getItem() and removeItem().

Sample Code:

<!DOCTYPE html>
<html>
 <head>
  <title>Session Storage</title>
   <script>
     function SaveData()
     {
      if(window.sessionStorage)
      {
    if(document.getElementById('answer').value == 8)
        {
        window.sessionStorage.setItem("level", 2);
        window.sessionStorage.setItem("score", 100);
    }
    else
    {
        window.sessionStorage.setItem("level", 1);
        window.sessionStorage.setItem("score", 0);
    }
      }
     else
       alert("Your browser does not support HTML5 sessionStorage!!!");
    }
    function GetData()
    {
     if(window.localStorage)
     {    
       var output;
       var level =  window.sessionStorage.getItem("level");
     if(level == 1)
        output = "Your answer is wrong. Try Again!!!";
    else if(level ==2)
        output = "Congratulations!!! You completed Level 1. Your score is " + window.sessionStorage.getItem("score");
     document.getElementById("result").innerHTML = "<b>" + output + "</b>";
     }
     else
      alert("Your browser does not support HTML5 sessionStorage!!!");
     }
    function RemoveData()
    {
     if(window.localStorage)
     {                
       window.localStorage.removeItem("lastName");
       alert("Last name removed successfully!!!");
     }
     else
      alert("Your browser does not support HTML5 sessionStorage!!!");
    }
  </script>
 </head>
 <body>
  Find Out: <b>6 &times; 4 &divide; 3 + <input id="answer" type="text" size="1" /> - 7 = 9 <br /><br />
  <button id="saveData" onclick="SaveData();">Submit</button>
  <button id="getData" onclick="GetData();">Proceed</button><br /><br />
  <div id="result"></div>
 </body>
</html>

Save the file that contains the above lines of code in your localhost folder and access it as localhost/filename.html. Try to solve the puzzle and enter the answer in the textbox. After entering the answer, click the Submit button. Then click the Proceed button. If your answer is wrong, you will get a message like this:

           HTML5 session storage example 04

If your answer is correct, you will get a screen like this:

         HTML5 session storage example 2

 

Now close the browser window and again open it using localhost/filename.html. This time click the Proceed button without entering anything in the text box. You will get a screen like this.

             HTML5 session storage example 3

 

This means that the data is available only for that particular session.

When the data in the localStorage or sessionStorage is changed, a storage event is fired. This event is really useful as you can find whether the data you stored in localStorage or sessionStorage is modified with the help of a script running on another page. You should register a handler for storage events so that it will get triggered when your data is changed. The storage event object has four important properties and they are 1) key that holds the name or key of the item that was added, removed or modified, or null if the clear() method was called 2) oldValue that holds the old value of an existing item that changed or was deleted, or null if a new item was added 3) newValue that holds the new value of the item, or null if removeItem() was called and 4) url that holds the URL of the document the script of which made storage change.

Summary

In this section, we have seen how to use localStorage and sessionStorage objects to store data locally on the browser. We have used the setItem(), getItem() and removeItem() methods to store data permanently and also store data for a particular session. You can actually do wonders using HTML5 web storage if used wisely.

Like us on Facebook