The need to store data in software programs cannot be overemphasized.
On the web, we can use the web browser’s storage to save some data on the user’s machine, which your code can access when it is next executed on that browser.
With
They are as follows:
windows.localStorage
window.sessionStorage
The difference between the two objects is that window.localStorage
retains stored data until the data is removed, which can be any length of time longer than that stored by window.sessionStorage
.
window.sessionStorage
is just for a single session and can be destroyed when the browser is closed.
It is best to check that the client browser supports the HTML storage objects, although this is supported by virtually all modern browsers today.
We can check this support using the HTML <script> ... </script>
code below.
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
//Error message: Hi! please Use a supported browser.
}
localStorage
ObjectThis object will store data in the browser’s local storage almost permanently until it is removed.
localStorage.setItem("key", "value");
document.getElementById("htmlElement").innerHTML = localStorage.getItem("value");
The parameter of the localStorage
object method setItem
is the key that will point to the value to be saved.
The setItem
method is used to collect details about the data to be saved.
In the code we saved the weekday, Monday, using the setItem()
method and retrieved it using the getItem()
method, which is both a method of the localStorage
object.
sessionStorage
objectThis second HTML storage object saves the data of concern for just a single session. The saved data is deleted when the browser is closed.
sessionStorage.AnyMethodOfChoice(args)
The sessionStorage
object has several methods which it can use.
See the below code for practical use of the sessionStorage
object.
In the below code, the clickcount()
method was used to increase a counter based on how many times a user from a particular session clicked a button.