localStorage is a built-in property of the browser. The read-only localStorage property allows you to access an object Storage for a Document's origin; the data stored will be saved in the browser session. localStorage is similar to sessionStorage, but the difference is that the data stored in localStorage can be retained for a long time, while the data stored in sessionStorage will be cleared when the page session ends, i.e., when the page is closed.
Note that whether the data is stored in localStorage or sessionStorage, they are specific to the page's protocol.
In addition, key-value pairs in localStorage are always stored as strings. (Note that compared to JavaScript objects, key-value pairs being stored as strings means that numeric types will be automatically converted to string types.)
The usage of localStorage is also very simple, divided into storing and retrieving, which can be bound to event methods.
// Storing
const arr = 100;
localStorage.setItem("key", JSON.stringify(arr));
// Retrieving
const arr = JSON.parse(localStorage.getItem("key"));
Here, "key"
refers to the parameter name stored in the browser, and arr
is the parameter value.
localStorage.setItem("key", JSON.stringify(arr));
This method stores the arrayarr
in the browser's localStorage, and its parameter name is calledkey
.const arr = JSON.parse(localStorage.getItem("key"));
is used to retrieve the parameter value with the parameter namekey
stored in the browser.
For example, to statically save a certain setting parameter, you can write it into an array and then store it using localStorage. Originally, refreshing would display the default settings, but now you can read the stored parameters every time you refresh.
It is very useful in some scenarios, such as developing a Tampermonkey script, and so on.
To clear localStorage, you can either clear all stored values or clear a specific key.
// Clear all values in local storage
localStorage.clear();
// Remove a specific item from local storage
localStorage.removeItem(key);