Monday, 23 June 2014

HTML5 Web Storage

Web Storage is a client side storage. It allows users to persist data in form of key/value pair. Before it, web developers use cookies for storing objects/data locally in user's or client's machine. Web Storage is much similar to cookies but we can store greater amount of data and is much secure.

Disadvantages of Cookies:

  1. We can store 4KB of data in cookies whereas using Web Stoage, we can store upto 5MB of data.
  2. Cookies are send along with every HTTP request hence it slows down the web application.
  3. Cookies are included with every HTTP request(unencrypted) hence Cookies are less secure whereas data in Web Storage is stored on client's browser.

Web Storage is Supported in these browsers:
  1. Chrome 5+
  2. Firefox 3.6+
  3. Internet Explorer 8+ etc.




One of the Important point is that Web Storage is browser specific. Let's understand it with an example. Suppose user visit your site with chrome than any data will be stored to Chrome's Web Storage Store is avaiable with chrome browser not with other browser (like I.E. etc). If user revisit your site with differnent browser, than the data saved within Chrome's Web Storage is unavailable. So, we can say that Web storage is browser specific andeach browser's storage is seprate and independent. 

We can also check browser support using the following Code:
if (typeof (Storage) !== "undefined") {
          alert("Your browser supports HTML5 Web Storage");
}
else {
          alert("Your browser does not supports HTML5 Web Storage");
}

Preview:

Types of Web Storage:
There are two types of HTML5 Web Storage:
1)Local Storage                  2)Session Storage

Local Storage object stores the data with no expiration date means stored data will not be deleted even after browser is closed. Session storage object is much similar to Local Storage. The only difference between Session Storage and Local Storage is that Session Storage data is deleted when browser is closed by the user.

Some Common method and properties for local and session storage:















Example: Storing and retrieving data from Local Storage:
Firstly, We have to check whether browser support Web Storage or not. If Supports than we call setItem method of localStorage  and pass the key/value pair. After that we retrieve the value from localStorage using getItem method and display it in output div. 

<!DOCTYPE html>
<html>
       <head>
              <title>Local Storage Example</title>
       </head>
       <body>
              <div id="output"></div>
              <script>
                  if (typeof (Storage) !== "undefined") {
                      localStorage.setItem("Name", "Anoop Sharma");
                      document.getElementById("output").innerHTML = localStorage.getItem("Name");
                  }
                  else {
                      document.getElementById("output").innerHTML = "Your Browser does not Support HTML5 Web Storage";
                  }
              </script>
       </body>
</html>

Example: Storing and retrieving data from Session Storage
Everything is similar to the previous example instead of localStorage object we use sessionStorage object.

<!DOCTYPE html>
<html>
       <head>
              <title>Session Storage Example</title>
       </head>
       <body>
              <div id="output"></div>
              <script>
                  if (typeof (Storage) !== "undefined") {
                      sessionStorage.setItem("Name", "Anoop Sharma");
                      document.getElementById("output").innerHTML = sessionStorage.getItem("Name");
                  }
                  else {
                      document.getElementById("output").innerHTML = "Your Browser does not Support HTML5 Web Storage";
                  }
              </script>
       </body>
</html>

Example: Showing use of various and properties and methods like length, setItem, getItem, clear etc in localStorage type of Web Storage
  1. In this Example we have taken two div with id(box1,box2). box1 contains textbox and buttons where as box2 used for displaying the data from localStorage.
  2. windows.addEventlistener calls the displaythis function on loading the window/page.
  3. savethis function save the data in the textbox to the local Storage after that display the data on div(#box2) by calling displaythis function.
  4. displaythis function runs a loop starting from i=0 to i<localStorage.length (which returns no. of key/value pair in local storage).
  5. Get the keys using localStorage.key(i) which retrieves the key at specific index(i.e. i) and use this value for getting the value using .getItem method.
  6. After Getting the both keys/value pair display is in div(with id box2).
  7. For clearing the data from localStorage we use clearthis fuction onclick event of clear button.
<!DOCTYPE html>
<html>
       <head>
              <title>Local Storage Example</title>
              <style>
              #box1{
              float:left;
              padding:16px;
              border:1px dashed black;
              margin-left:20px;
              }
              #box2{
              float:left;
              padding:16px;
              border:1px dashed green;
              width:300px;
              margin-left:20px;
              }
              </style>
              <script>
                  //display method for displaying data on window load and after saving
                  function displaythis() {
                      var box2 = document.getElementById("box2");
                      box2.innerHTML = "";
                      for (var i = 0; i < localStorage.length; i++) {
                          var keyval = localStorage.key(i);
                          var itemval = localStorage.getItem(keyval);
                          document.getElementById("box2").innerHTML += "Key=" + keyval + " Value=" + itemval + "<br>";
                      }
                  }
                  //Save data to localStorage method
                  function savethis() {
                      var txtbox1 = document.getElementById("textbox1").value;
                      var txtbox2 = document.getElementById("textbox2").value;
                      localStorage.setItem(txtbox1, txtbox2);
                      alert("Record Added!");
                      displaythis();
                      document.getElementById("textbox1").value = "";
                      document.getElementById("textbox2").value = "";
                  }
                  //for Clearing the data from localStorage
                  function clearthis() {
                      localStorage.clear();
                      displaythis();
                  }
                  //call displaythis method on window load
                  window.addEventListener("load", displaythis, false);

              </script>
       </head>
       <body>
              <div id="box1">
                     <p>Key:&nbsp;&nbsp;<input type="text" id="textbox1"></p>
                     <p>Value:<input type="text" id="textbox2"></p>
                     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" id="button" value="Save" onclick="savethis();"><input type="button" id="button1" value="Clear" onclick="    clearthis();">
              </div>
              <div id="box2">No Data Stored</div>
              <script>
                    
              </script>
       </body>
</html>
Preview:

Viewing Web inspector:
1) Right click in body of Web Page and then click on Inspect Element.(you can also get the same from tools->Developer Tools)
2) After that click on resource tab, than click on Local Storage.
Now you are able to see data (key/value) which we have added recently. If you double click on the value in Web Inspector, you find that you can actually modify the value stored there.

Thanks for Reading :-)

[Download Source Code via Google Drive]



0 comments:

Post a Comment

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Subscribe us on YouTube

Like us on Facebook

Follow us on Google+