HTML Web Storage API
HTML web storage; better than cookies.
HTML Web Storage, also commonly referred to as Web Storage or Local Storage, is a web browser feature that allows web applications to store data locally within the user's browser. This storage mechanism is designed to provide a simple key-value pair storage system that can persist data between browser sessions. Web Storage includes two related mechanisms: localStorage and sessionStorage.
localStorage:
- Data stored using localStorage has no expiration time and persists even when the browser is closed and reopened.
- The data stored in localStorage is accessible across different browser tabs and windows for the same origin (same protocol, domain, and port).
sessionStorage:
- Data stored using sessionStorage is available only for the duration of the page session. It gets cleared when the page session ends, typically when the user closes the browser tab or window.
- Unlike localStorage, data stored in sessionStorage is not shared between different tabs or windows; each tab or window has its own session storage area.
Here's a simple example of using localStorage:
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Web Storage Example</title> </head> <body> <script> // Storing data in localStorage localStorage.setItem( "username", "JohnDoe"); localStorage.setItem( "theme", "light"); // Retrieving data from localStorage var storedUsername = localStorage.getItem( "username"); var storedTheme = localStorage.getItem( "theme"); console.log( "Stored Username:", storedUsername); console.log( "Stored Theme:", storedTheme); // Removing an item from localStorage localStorage.removeItem( "theme"); // Clearing all items from localStorage // localStorage.clear(); </script> </body> </html>You can click on above box to edit the code and run again.
Output
In this example:
- Data is stored using localStorage.setItem(key, value).
- Data is retrieved using localStorage.getItem(key).
- An item is removed using localStorage.removeItem(key)
- All items are cleared using localStorage.clear()
It's important to note that the data stored in localStorage and sessionStorage is accessible only on the client-side (browser) and is limited to a specific domain. Also, web storage has size limits (usually around 5-10 MB per domain), and sensitive information should not be stored without proper encryption.
Browser Support
The numbers in the table specify the first browser version that fully supports Web Storage.