HTML Web Storage
The Web Storage is one of the great features of HTML5. With the Web Storage feature, web applications can locally store data within the browser on the client side. It stores data in the form of key/value pair on the browser. Web Storage sometimes also known as DOM storage.
Storing data with the help of web storage is similar to cookies, but it is better and faster than cookies storage.
In compared to cookies Web Storage has Following Advantages:
Types of Web Storage
There are two types of web storage with different scope and lifetime.
Note: For both storage type, web storage data will not be available for different browsers, and Storage size may vary from browser to browser.
Browser support for Web Storage
Before learning for web Storage we must check whether our browser is supporting the web Storage or not. So you can check by executing the following code:Test it Now
The localStorage Object
The localStorage object stores data locally within the browser. The data stored by localStroage object does not have any expiration date. Hence the stored data will not be deleted if the browser is closed or reopened.
Each piece of data is stored in simple key-value pairs. The key/values are always stored as String, and can be accessed with localStorage.getItem() and localStorage.setItem() methods.
Example:Test it Now
Note: You can check the local storage items in the form of key/value pair by inspecting elements on the web page and then go to the Application option where you will find the local storage and Session storage and can check stored items in the list.
You can check the following screenshot with key/value pairs.
Example 2:Test it Now
In the above example, we have shown a counter which will increase as you will click on the counter button.
We have used localStorage.hits to set a counter
Note: It will show the total number of count even if you close the browser.
The sessionStorage Object:
The sessionStorage object is same as the localStorage object, but the difference is that it stores data only for one session. If you close the browser, then data will be lost or deleted.Test it Now
The above example is working same as local storage counter example, but the difference is we have used sessionStorage.hits for session storage.
Here the counter will reset if you close the browser and it will start from the initial value.
Remove Web Storage:
As we have seen the session storage data will automatically be deleted, when you close the browser but the data saved by local storage will remain in the browser even if you close it.
Hence to delete the local storage data, you need to call two methods:
ExampleTest it Now
In the above example we have used localStorage.removeItem("name"); Which will delete the value for the key "name".
You can remove id for a particular key, or you can also remove all data using localStorage.clear() method.