HTML5 Web Storage

Web applications can store data locally within the user’s browser with help of web storage.

Before HtML5 cookies are used to perform the same task but there was limitation like storage capacity and information was never transferred to the server.

Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

Web Storage Objects

Web storage provides two objects for storing data on the client side:

  • window.sessionStorage – stores data for one session means all information is lost when the browser tab is closed.
  • window.localStorage – stores data with no expiration date.

The sessionStorage Object

The sessionStorage object stores the data for only one session. The data is deleted when the user closes the browser tab.

The following example counts the number of times a user has clicked a button, in the current session:

<!DOCTYPE HTML>

<html>
   <body>
      <script type = "text/javascript">
         
         if( sessionStorage.hits ) {
            sessionStorage.hits = Number(sessionStorage.hits) +1;
         } else {
            sessionStorage.hits = 1;
         }
         document.write("Total Hits :" + sessionStorage.hits );
      </script>
    
      <p>Refresh the page to increase the number of hits.</p>
      <p>Close the window and open it again and check the result.</p>

   </body>
</html>

The localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next time you open the browser.

The following example counts the number of times a user has clicked a button:

<!DOCTYPE HTML>

<html>
   <body>
      <script type = "text/javascript">
         
         if( localStorage.hits ) {
            localStorage.hits = Number(localStorage.hits) +1;
         } else {
            localStorage.hits = 1;
         }
         document.write("Total Hits :" + localStorage.hits );
      </script>
        
      <p>Refresh the page to increase the number of hits.</p>
      <p>Close the window and open it again and check the result.</p>

   </body>
</html>