HTML Web Storage API
The HTML Web Storage API provides a way to store key-value pairs locally in the user's browser.
There are two types of storage mechanisms provided by this API:
localStorage
and sessionStorage
.
Both types of storage have a similar API, but they differ in their persistence and scope.
The localStorage
localStorage
allows you to store data that persists even after the browser is closed and reopened. The data stored in localStorage
is shared between all tabs and windows opened from the same origin (i.e., same protocol, host, and port).
As an example:
// set the value of a key
localStorage.setItem("username", "johndoe");
// retrieve the value of a key
const username = localStorage.getItem("username");
console.log(username); // prints "johndoe"
// remove a key-value pair
localStorage.removeItem("username");
// remove all key-value pairs
localStorage.clear();
The sessionStorage
sessionStorage
is similar to localStorage
, but the data stored in sessionStorage
is only available for the duration of the session (i.e., until the browser is closed or the tab is closed). The data stored in sessionStorage
is also shared between all tabs and windows opened from the same origin.
As an example:
// set the value of a key
sessionStorage.setItem("username", "johndoe");
// retrieve the value of a key
const username = sessionStorage.getItem("username");
console.log(username); // prints "johndoe"
// remove a key-value pair
sessionStorage.removeItem("username");
// remove all key-value pairs
sessionStorage.clear();
Both localStorage
and sessionStorage
have a limit on the amount of data that can be stored (typically around 5-10 MB), and they can only store data as strings.