HTML5 introduced two new mechanisms for client-side data storage: Web Storage and IndexedDB. In this tutorial, we will focus on Web Storage, which includes two types of storage: localStorage and sessionStorage. These storage options provide a way to store key-value pairs in the browser without requiring a server.
localStorage has no expiration time. It persists even after the browser window is closed.sessionStorage is cleared when the tab or browsing context is closed.localStorage, typically around 5-10MB per origin.To store data, use the setItem() method. This method takes two parameters: a key and a value (which must be a string).
// Storing data in localStorage
localStorage.setItem('username', 'JohnDoe');
// Storing data in sessionStorage
sessionStorage.setItem('theme', 'dark');
To retrieve data, use the getItem() method. This method takes one parameter: the key.
// Retrieving data from localStorage
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe
// Retrieving data from sessionStorage
const theme = sessionStorage.getItem('theme');
console.log(theme); // Output: dark
To remove a specific item, use the removeItem() method. To clear all items, use the clear() method.
// Removing a specific item from localStorage
localStorage.removeItem('username');
// Clearing all items in sessionStorage
sessionStorage.clear();
// Storing an object in localStorage
const user = { name: 'JohnDoe', age: 30 };
localStorage.setItem('user', JSON.stringify(user));
// Retrieving the object from localStorage
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser); // Output: { name: 'JohnDoe', age: 30 }
Web Storage provides an event called storage that is triggered when a storage area (either localStorage or sessionStorage) changes in another document with the same origin.
window.addEventListener('storage', function(event) {
console.log(`Key changed: ${event.key}`);
console.log(`Old value: ${event.oldValue}`);
console.log(`New value: ${event.newValue}`);
});
HTML5 Web Storage provides a powerful and flexible way to store client-side data in the browser. By understanding the differences between localStorage and sessionStorage, and following best practices, you can effectively manage user data and enhance the functionality of your web applications.
By leveraging these features, you can create more interactive and efficient web applications that provide a better user experience.