The HTML Web Storage API, also known as the Web Storage API or the DOM Storage API, provides a way to store data on the client-side web browser. It allows web applications to store data locally and access it later, even after the browser is closed and reopened. The Web Storage API consists of two mechanisms: localStorage
and sessionStorage
. Here’s an overview of how to use the Web Storage API:
localStorage
:
- The
localStorage
object allows you to store key-value pairs persistently, meaning the data will remain stored even after the browser is closed and reopened. - To store data in
localStorage
, you can use thesetItem()
method, which takes a key and a value as arguments.
localStorage.setItem('key', 'value');
- To retrieve data from
localStorage
, you can use thegetItem()
method, which takes a key as an argument and returns the corresponding value.
const value = localStorage.getItem('key');
- To remove data from
localStorage
, you can use theremoveItem()
method, which takes a key as an argument.
localStorage.removeItem('key');
- You can also clear all data stored in
localStorage
using theclear()
method.
localStorage.clear();
sessionStorage
:
- The
sessionStorage
object allows you to store data similarly tolocalStorage
, but the data is only available for the duration of the browser session. Once the session ends (i.e., the browser is closed), the stored data is cleared. - The methods for storing, retrieving, and removing data in
sessionStorage
are the same as those inlocalStorage
. The only difference is that you use thesessionStorage
object instead oflocalStorage
.
sessionStorage.setItem('key', 'value');
const value = sessionStorage.getItem('key');
sessionStorage.removeItem('key');
sessionStorage.clear();
- Checking for Browser Support:
Before using the Web Storage API, you can check if the browser supports it by verifying the availability of thelocalStorage
orsessionStorage
object.
if (typeof Storage !== 'undefined') {
// Web Storage API is supported
} else {
// Web Storage API is not supported
}
- Limitations:
- The Web Storage API has a storage limit of around 5MB per origin (domain).
- The data stored in
localStorage
andsessionStorage
is specific to the origin, meaning different origins will have their separate storage areas.
The Web Storage API is a useful tool for web applications to store and retrieve data locally on the client-side. It provides a simple key-value storage mechanism that can be accessed across different pages of a website. However, note that sensitive data should not be stored in localStorage
or sessionStorage
due to the potential risk of data exposure.