Session Handling Using localStorage
2. localStorage
There are two objects that can be used for web storage. The first is localStorage which stores data that is not deleted even when the browser is closed. The next time the user opens the webpage, the data stored in localStorage can be used again. The second is the sessionStorage object and it stores data that is present only for the duration of the user’s time with the webpage (one session). Once the browser is closed or the session is ended (i.e, the user closed the tab), the data is deleted. Data stored in this object is also available when the page is reloaded or refreshed.
The code snippet below shows an example of checking if the browser supports local storage, setting a key-value pair for local storage if it is supported, and retrieving that key-value pair.
<div id="result"></div>
<script>
//Check if the browser supports the local storage object
if (typeof(Storage)!=="undefined"){
//set a value for storage
localStorage.setItem("greeting", "Hello World!");
//retrieve the stored value
document.getElementById("result").innerHTML = localStorage.getItem("greeting");
}else{
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage.";
}
</script>
Sample Output if browser supports localStorage:
Hello World!
Code explanation:
- localStorage.setItem(key, value) – accepts two arguments – the key and the value for the data being saved. If the key already exists in storage, its value overwritten,
- localStorage.getItem(key) – accepts one argument – the key name – and retrieves the value corresponding to that key.
