How to store data in the browser with the HTML5 localStorage API?


HTML5 localStorage saves string data in the browser and lasts beyond the current session. localStorage stores the data, with no expiration, whereas sessionStorage is limited to the session only. When the browser is closed, the session is lost.

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 learn how to work with HTML5 localStorage

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 on the website:" + 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: 25-Feb-2020

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements