What is the HTML 5 web storage?
Introduction
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.
Storing data with HTML 5
With
They are as follows:
windows.localStoragewindow.sessionStorage
Local storage vs session storage
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.
Checking client browser support
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.
}
How to store data using the storage objects
The localStorage Object
This object will store data in the browser’s local storage almost permanently until it is removed.
Syntax
1. To store
localStorage.setItem("key", "value");
2. To retrieve
document.getElementById("htmlElement").innerHTML = localStorage.getItem("value");
Explanation of syntax
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.
Code
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.
The sessionStorage object
This second HTML storage object saves the data of concern for just a single session. The saved data is deleted when the browser is closed.
Syntax
sessionStorage.AnyMethodOfChoice(args)
The sessionStorage object has several methods which it can use.
See the below code for practical use of the sessionStorage object.
Code
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.