Html5 Web Storage

local and session storage
Html5 Local and Session Storage

HTML5 Web storage can store data on client side, same like cookies. But Cookies can store only 4kb data in string type , whereas html5 web storage can store upto 5mb data in key-value pair.Unlike cookies, they are easy to use, have more storage capacities and can be used on different tabs of same browser.


Type of web storage

  • Local Storage
  • Session Storage

Check Web Storage support on browsers.

		
<script>
	if(window.localStorage)
	{
	alert("Local storage is supported")
	}
	else
	{
	alert("Local storage is not supported")
	}

</script>	

Check Web Storage

 


Local Storage

local storage
Html5 Local Storage

HTML5 Local Storage can store upto 5 mb data,( can vary on different browsers) on client side same like cookies. But cookies can store only upto 4kb data, and data is stored in string type only. Local storage can store data in key-value pair.


<script>
	if(window.localStorage){ 
		localStorage.setItem("name","Avinash Malhotra");
		var name=localStorage.getItem("name");
		alert("Your name is " + name)
	}
	else{
		alert("local storage not supported")
	}
	
</script>			
( refresh page to check )

Your name is

Remove Local Storage Item

To remove a item from localStorage, we use removeItem Method. delete operator can also delete item from local storage. To clear localStorage completely, clear method is used.


<script>
localStorage.removeItem("name");			// remove item name from local storage 
delete localStorage.name;				// remove item name from local storage

localStorage.clear();					//remove all data from local storage    
</script>

Session Storage

Session storage
Html5 Session Storage

Session Storage can store data on client side, but only for current session. That means once you close your browser tab, all data stored in session storage will be erased. Session storage data is also stored in key-valuepair.


<script>
	if(window.sessionStorage){ 
		sessionStorage.setItem("user","Tech Altum");
		var name=sessionStorage.getItem("user");
		alert("Your name is " + name)
	}
	else{
		alert("session storage not supported")
	}
		

You can close this tab and open same page in new tab to check new session.

Remove Session Storage Item

Session Storage removes all data when we close the tab. To remove a item from sessionStorage manually, we use removeItem Method and delete operator. To clear sessionStorage completely, clear method can also be is used.


<script>
sessionStorage.removeItem("name");			// remove item name from session storage 
delete sessionStorage.name;				// remove item name from session storage

sessionStorage.clear();					//remove all data from session storage    
</script>

Html5 Local and Session Storage are not supported in HTML4 based Browsers. But we can use cookies instead on html4 based browsers like IE 8 and below.