HTML Web Storage

By | February 4, 2020

Web storage is also one of the great vistas of HTML5. With web storage we can store data in web browser.HTML5 uses web storage to store data similar to cookies on the computer. But it has a better end than cookies. In cookies you can store up to 4kb data but in web store you can store up to 5MB data. Web store is not more secure than cookies. We cannot send web store information against cookies on the server. Web storage is faster than cookies because it does not send data to the server side.

There are mainly two types of web storage

1.Local storage:-

Local storage contains all the data that remains for several days or months, this data remains until you delete it. This storage window uses the localstorage object to retain data even if the browser is closed.

2.Session storage:-

Session storage is for a single browser window. Session storage uses sessionStorage object to store data.If the browser or window is closed, it eats the data.

Browser Support:-

HTML5 web storage facility is supported in all modern browsers.

Web Storage Objects:-

HTML5 Web Storage provides two types of objects for storing data.

localStorage Object:-

It stores data without expiry date.There is no data property date. Even if the browser is closed, the data is not rendered.

<body>

<div id="storage"></div>

<script>
     // check browser support
     if(typeof(Storage) !== "undefined"){
          // Store
          localStorage.setItem("lastname", "Smith");
          // Retrieve
          document.getElementById("storage").innerHTML = localStorage.getItem("lastname");
     } else {
     document.getElementById("storage").innerHTML = "Sorry Your Browser does not support Web storage";
     }
</script>


</body>

sessionStorage Object:-

It acts like local storage but the difference is that if the user closes their browser or window then the data gets delimited.


<body>

<p><button onclick="clickCounter()" type="button">Click Me</button></p>
<div id="storage"></div>
<p>Click the button to see the counter increase</p>
<p>close the browser tab and try again and the counter is reset</p>

<script>
function clickCounter(){
     if(typeof(Storage) !== "undefined"){
          if (sessionStorage.clickcount) {
          sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
     } else {
          sessionStorage.clickcount = 1;
     }
     document.getElementById("storage").innerHTML = "you have click the button"
     + sessionStorage.clickcount + " time(s) in this session";
} else {
     document.getElementById("storage").innerHTML = "Sorry your browser does not support web storage";
}
}
</script>


</body>
Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *