Session Handling Using localStorage
2. localStorage
2.1. localStorage methods
Additional methods that can be used to for local storage are as follows:
- localStorage.clear() – removes all key-value pairs stored in the local storage
- localStorage.removeItem(key) – accepts one argument – the key name – and deletes the corresponding key-value pair from the local storage.
The code below shows another example of using localStorage. In this example, a user is asked to enter a name. If there is no name currently stored, the new name is stored. If there is a value stored and it is equal to the name entered by the user, a welcome message is printed. If the value stored is not the same as the name entered by the user, a message is displayed saying that the visitor is not the expected user.
<div id="result"></div>
<script>
//Check if the browser supports the local storage object
if (typeof(Storage)!=="undefined"){
var yourName = prompt("Enter your username: ");
//retrieve the stored value
var stored = localStorage.getItem("userName");
if (stored == yourName){
//set a value for storage
localStorage.setItem("userName", yourName);
}
if (stored == yourName){
document.getElementById("result").innerHTML = "Welcome back "+yourName+"!";
}
else{
document.getElementById("result").innerHTML = "You are not "+stored+ "!";
}
} else{
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage.";
}
</script>
To see another example of how local storage is used in web pages, you can view an example from mozilla.org by clicking on this link (https://mdn.github.io/dom-examples/web-storage/). To see the code for localStorage in this example, right-click on the page, click “View page source” and click on the “main.js” link at the bottom of the page.
For sessionStorage, the methods are the same as local storage and they are listed below. You can try implementing the sample code above using session storage.
- sessionStorage.setItem(key, value)
- sessionStorage.getItem(key)
- sessionStorage.clear()
- sessionStorage.removeItem()