The HTML5 web storage is used to store data on user's browser.
What is Web Storage
The HTML5's web storage feature lets you store some information locally on the user's computer, similar to cookies but it is more secure and faster.
"The information stored in the web storage isn't sent to the web server as opposed to the cookies where data sent to the server with every request. Also, where cookies lets you store a small amount of data (nearly 4KB), the web storage allows you to store up to 5MB of data".
There are two types of web storage, which differ in scope and lifetime:
Local storage — The local storage uses the
localStorageobject to store data for your entire website, permanently. That means the stored local data will be available on the next day, the next week, or the next year unless you remove it.
Session storage — The session storage uses the
sessionStorageobject to store data on a temporary basis, for a single window (or tab). The data disappears when session ends i.e. when the user closes that window (or tab).
Tip:The HTML5's web storage feature is supported in all major modern browsers like Firefox, Chrome, Opera, Safari and Internet Explorer 8+.
The localStorage Object
As stated earlier, the localStorage object stores the data with no expiration date. Each piece of data is stored in a key/value pair. The key identifies the name of the information (like 'first_name'), and the value is the value associated with that key (say 'xyz').
- localStorage.setItem(key, value): Stores a value associated with a key.
- localStorage.getItem(key): Retrieves the value associated with the key.
You can also remove a particular item from the storage by passing the key value to the
removeItem() method, like
However, if you want to remove the complete storage use the
clear() method, like
clear() method clears all key/value pairs from localStorage at once, so think carefully before you using it.
Note:The web storage data (both local and session) will not be available between different browsers, for example the data stored in Firefox browser will not available in Google Chrome, Internet Explorer or other browsers.
The sessionStorage Object
sessionStorage object work in the same way as
localStorage, except that it stores the data only for one session i.e. the data remains until the user closes that window (or tab).