HTML Web Storage API

In prior html5 versions the application data could be stored using cookies only, but html5 introduced web storage API.

HTML web storage API is used to store and retrieve data locally in the user’s browser in form of key/value pairs just like cookies but, it is better than cookies because it is more secure and large number of data can be stored using it without effecting website performance.

Web storage Mechanism

There are two kind of web storage mechanisms through which data can be saved on client side.

  1. Session Storage: It maintains a separate storage area for storing data but that saved data is only available within duration of page session.
    • Data is stored as long as, the the browser is open.
    • Data remains on client side and not transferred on server side.
    • The storage capacity of session storage is longer than cookies it can save data up to 5MB.
    • The object used for session storage is window.sessionStorage.
  2. Local Storage: It acts same as storage session but, in local storage data remain save even after closing and reopening of browser.
    • Storage data has no expiration date.
    • Data stored using local storage can be cleared either through JavaScript or by clearing the browser cache.
    • Storage capacity is better than both cookies and session storage.
    • The object used for session storage is window.localStorage.

Browser Support

Its better to check the browser support for local storage and session storage, before using web storage. Lets see the syntax for checking browser support.

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
} else {
  // Sorry! No Web Storage support.
}

Local Storage Object

In local storage storage data has no expiration date, data remains save until the browser cache is not cleared.

Lets see an example to understand the local storage object more clearly. The following example counts the number of clicks on button and stores the value through local storage.

<!DOCTYPE html>
<html>
<head>
<script>
function Counter()
   {
        if (typeof(Storage) !== "undefined") {
			if (localStorage.clickcount) {
			  localStorage.clickcount = Number(localStorage.clickcount)+1;
			} else {
			  localStorage.clickcount = 1;
			}
			document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s) in this session.";
		  } else {
			document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage";
		  }
    }
</script>
</head>
<body>

<p><button onclick="Counter()" type="button">Click me</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab, and try again.</p>

</body>
</html>
Web Storage

In the above example there is button, on every button click the value of clicks will be store in local storage object, the result will be displayed in place of div allocated for showing result.

Note: Default data type of key/value pair is string, So if we need to store the value in any other format, than we have to convert it first, such as in above example the values are converted in number using number().

Clear Local Storage

As we discussed above that data stored using local storage object has no expiration date, So it can be cleared through JavaScript or by clearing the browser cache.

If you want to clear all data than localStorage.clear() method is used, and for deleting particular data localStorage.remove(key) method is used, in which ‘key’ is the key of that particular value you want to remove.

The following example will clear complete local storage.

<!DOCTYPE html>
<html>
<head>
<script>
 localStorage.clear();
function Counter()

   {
     
        if (typeof(Storage) !== "undefined") {
			if (localStorage.clickcount) {
			  localStorage.clickcount = Number(localStorage.clickcount)+1;
			} else {
			  localStorage.clickcount = 1;
			}
			document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s) in this session.";
		  } else {
			document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage";
		  }
    }
</script>
</head>
<body>

<p><button onclick="Counter()" type="button">Click me</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again. The data will be cleared on closing of browser.</p>

</body>
</html>
local storage clear

To understand it more clearly try the above code and check the live demo.

Session Storage Object

Session storage maintains a separate storage area for storing data and acts same as local storage but, it stores data only for a single session and the data is deleted when the browser is closed.

Lets see an example to understand the local storage object more clearly. The following example counts the page reload.

<!DOCTYPE HTML>

<html>
   <body>
      <script type = "text/javascript">
         
         if (typeof(Storage) !== "undefined")
		 {
		        if( sessionStorage.hits )
				  {
                     sessionStorage.hits = Number(sessionStorage.hits) +1;
                  } 
				else 
				{
                    sessionStorage.hits = 1;
                }
                    document.write("Total Hits :" + sessionStorage.hits );
	  
	     }
  
         else
		 {
           document.write("Sorry, your browser does not support web storage");
         }
		
      </script>

      <p>To increase the number of hits, refresh the tab.</p>
      <p>Close the window and reopen it,the counter is reset to default value.</p>

   </body>
</html>
if (typeof(Storage) !== “undefined”) { if( sessionStorage.hits ) { sessionStorage.hits = Number(sessionStorage.hits) +1; } else { sessionStorage.hits = 1; } document.write(“Total Hits :” + sessionStorage.hits ); } else { document.write(“Sorry, your browser does not support web storage”); }

To increase the number of hits, refresh the tab.

Close the window and reopen it,the counter is reset to default value.



Note: In the above example number of hits are the number of page reloads, these hits are stored using session storage.

Session Storage is intended for situations in which a user is performing a single transaction while simultaneously performing multiple transactions in separate windows.