How to use HTML5 localStorage and sessionStorage?


HTML5 introduced two mechanisms, similar to HTTP session cookies, for storing structured data on the client side and to overcome the following drawbacks.

  • Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data.
  • Cookies are limited to about 4 KB of data. Not enough to store required data.

The two mechanisms for storage are session storage and local storage and they would be used to handle different situations.

Session Storage

The Session Storage is designed for scenarios where the user is carrying out a single transaction but could be carrying out multiple transactions in different windows at the same time.

You can try to run the following to set a session variable and access that variable

Example

Live Demo

<!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 number of hits.</p>
      <p>Close the window and open it again and check the result.</p>
   </body>
</html>

Local Storage

The Local Storage is designed for storage that spans multiple windows and lasts beyond the current session. In particular, Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.

You can try to run the following code to set a local storage variable and access that variable every time this page is accessed, even next time when you open the window.

Example

Live Demo

<!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 number of hits.</p>
      <p>Close the window and open it again and check the result.</p>
   </body>
</html>

Updated on: 18-May-2020

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements