The Web Storage API provides a way to store key/value pairs locally within the user's browser. It's useful for storing small amounts of data persistently across page reloads or even when the browser is closed and reopened. There are two types of Web Storage: localStorage and sessionStorage.
localStorage
is designed for persistent storage.localStorage
remains available even after the browser is closed and reopened.sessionStorage
is intended for storing data for the duration of a browsing session.sessionStorage
is cleared when the browsing session ends, such as when the tab or window is closed.localStorage
, sessionStorage
is limited to the tab or window that created it, providing data isolation between different tabs.setItem()
method, providing a key and a corresponding value.
localStorage.setItem('key', 'value');
sessionStorage.setItem('key', 'value');
getItem()
method, passing the key of the desired item.
const data = localStorage.getItem('key');
removeItem()
method, passing the key of the item to be removed.
localStorage.removeItem('key');
JSON.stringify()
and JSON.parse()
.storage
event is triggered when a storage area (localStorage
or sessionStorage
) changes in another browser tab or window of the same origin.
window.addEventListener('storage', (event) => {
if (event.key === 'key') {
// Handle the event
}
});
The Web Storage API in JavaScript provides a convenient way to store data locally within the browser. Whether it's for caching user preferences, storing session data, or implementing offline functionality, Web Storage offers a simple and efficient solution. By understanding its basic usage, advanced features, and best practices, developers can leverage this API effectively in their web applications. Happy coding !❤️