localStorage is a built-in property of the browser. The read-only localStorage property allows you to access an object Storage of a Document source (origin); the stored data 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, that is, when the page is closed.
It should be noted 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 use of localStorage is also very simple, divided into storing and reading, and can be bound to event methods.
// Storing
const arr = 100;
localStorage.setItem("key", JSON.stringify(arr));
// Reading
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 "key".const arr = JSON.parse(localStorage.getItem("key"));
is used to read the parameter value with the parameter name "key" 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 the page would display the default settings, but now you can read the stored parameters every time the page is refreshed.
It is very useful in some scenarios, such as developing a Tampermonkey script, and so on.
To clear localStorage, you can 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);