HTML Web Storage

The web storage feature in HTML 5 helps you store information on the client computer in a similar way to how cookies are stored. However, there are distinct differences between the two. Web storage allows you to store larger files (up to 5 MB) compared to cookies that only allow you to store 4 KB. Additionally, the web storage feature is faster than cookies because once information is stored on the space it allocates, there is no further interchange between the client and the web server.

You can either use the LocalStorage object, which allows you to store data for your website permanently or the SessionStorage object that allows users to store data for a single window or tab on a temporarily basis. Data stored using the SessionStorage object disappears once a window or tab that was using it is closed.

 

<!DOCTYPE html>  
<html>  
<body>  
 <div id="result"></div>  
 <script>  
  if(typeof(Storage)!=="undefined") {  
   document.getElementById("result").innerHTML = "Hey, Your browser supports the Web Storage.";  
  }  
  else{  
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage";  
  }  
</script>  
</body>  
</html>

 

Check the code examples below to see how you can store data using both the LocalStorage and SessionStorage objects.

LocalStorage

<!DOCTYPE html>  
<html>  
<head>  
  <title>Web Storage API</title>  
  <style>  
    body{  
      color: green;  
      text-align: center;  
      font-size: 30px;  
      margin-top: 30px;  
      font-style: italic;  
    }  
  </style>  
</head>  
<body>  
<script>  
 if(typeof(Storage)!=="undefined") {  
  localStorage.setItem("name","Harshita");  
  localStorage.setItem("Country", "India");  
   document.write("Hi"+" "+localStorage.name+" "+"from" +" "+ localStorage.Country);  
}  
 else{  
  alert("Sorry! your browser is not supporting the browser")  
 }  
</script>  
</body>  
</html>

SessionStorage

<!DOCTYPE html>  
<html>  
<head>  
  <title>Web Storage API</title>  
  <style>  
     body{  
      color: green;  
      text-align: center;  
      font-size: 30px;  
      margin-top: 30px;  
      font-style: italic;  
      }  
  </style>  
</head>  
<body>  
<button onclick="remove();">Remove item</button>  
<div id="output"></div>  
  
<script>  
 if(typeof(Storage)!=="undefined") {  
  localStorage.setItem("name","Harshita");  
  localStorage.setItem("Country", "India");  
  document.getElementById('output').innerHTML= "Hii, my name is"+ " "+ localStorage.name +" "+"and i belongs to"+" "+localStorage.Country;  
   }  
  else{  
  alert("Sorry! your browser is not supporting the browser")  
 }  
  function remove() {  
 localStorage.removeItem("name");  
   document.getElementById('output').innerHTML= "Hii, my name is"+ " "+ localStorage.name +" "+"and i belongs to"+" "+localStorage.Country;  
}  
</script>  
</body>  
</html>