HTML5 Web Storage
The HTML5 Web Storage API provides a mechanism that allows browsers to securely store key-value pair data on the client side. It's simpler and more intuitive than using Cookies, and has larger storage capacity.
Web storage is divided into two main types:
localStorage: Permanent storage. Data persists even if the user closes the browser or restarts the computer, until explicitly deleted. Data is shared across all same-origin (same protocol, domain, port) windows and tabs in the same browser.sessionStorage: Session-level storage. Data is only valid during the current browser session. When the user closes the tab or browser window that created the data, the data is deleted.
Advantages of Web Storage
- Larger capacity: Typically provides at least 5MB of storage space, far exceeding Cookie's 4KB.
- More secure: Data is not sent to the server with every HTTP request like Cookies, reducing unnecessary data transfer and security risks.
- Simpler API: Provides a very simple set of
setItem,getItem,removeItemmethods.
Using localStorage
The localStorage object is used to store data with no expiration time.
Storing Data with setItem()
Reading Data with getItem()
Deleting Data with removeItem()
Clearing All Data with clear()
Note: Web storage can only store strings. If you want to store a JavaScript object, you need to first convert it to a JSON string using JSON.stringify(), and when reading, parse it back using JSON.parse().
Using sessionStorage
The sessionStorage object's API is exactly the same as localStorage; the only difference is its lifecycle.
When you close this browser tab, the session_id data will be automatically cleared. Data in localStorage, however, will be retained.