In JavaScript, local storage is a way to store data on a user's browser, which allows web pages to retain cross-session information without additional data transfer with the server. There are three main local storage methods: sessionStorage, localStorage, cookie and indexDB.
JavaScript has 4 data storage methods, namely:
- sessionStorage
- localStorage
- cookier
- indexDB
1. SessionStorage of javaScript local storage
sessionStorage is only valid in the current session and will be cleared after closing the page or browser. That is to say, sessionStorage only exists during the window (page) active period. Once the window is closed, sessionStorage will delete data.
There are several methods for sessionStorage
- setItem(key,value) sets data
- getItem(key) Get data
- removeItem(key) Remove data
- clear() clear() clear all values
sessionStorage instance:
// Add data("name","Li Si") ("age",18) // Get data(("name")) // Li Si // Clear a certain data("gender") // Clear all data()
2. LocalStorage of javaScript local storage
localStorage is a technology introduced in HTML5 to store data on a user's browser for a long time until the user deletes it manually. Similar to sessionStorage, but the data stored in localStorage does not expire. It also provides setItem, getItem, removeItem and clear methods to manipulate data.
There are several methods for localStorage
- setItem(key,value) sets data
- getItem(key) Get data
- removeItem(key) Remove data
- clear() clear() clear all values
//Storage data("name", "Zhang San"); ("age", 20); ("gender", "male"); // Get data(("name")); // Output: Zhang San // Delete data("gender"); // Clear all data();
localStorage can also manually set the expiration time of data by adding a timestamp and expiration time. Since localStorage can only store strings, it needs to be converted to a JSON string when storing an object and parsed on read.
= (key, value, expire) => { let obj = { data: value, time: (), expire: expire }; //The value set by localStorage cannot be an object, and is converted to a json string (key, (obj)); } = key => { let val = (key); if (!val) { return val; } val = (val); if (() - > ) { (key); return null; } return ; } //How to use('userId','zhangsan',5000); (()=>{ (("userId")); },1000)
- Summarize
- Persistent storage, even if the window is closed, it will still be retained unless manually deleted
- Page refresh data will not be lost
- The storage range generally does not exceed 5M
- The same browser supports multi-window (multiple page) sharing
- Suppose the same browser opens three pages of the same origin..com/;.com/;**.com/;Then these three windows can share localstorage
- Save as key-value pairs
- Save the value with (key, valueStr), valueStr must be a string, and to store the object, the string must be serialized first, and when obtaining the value, it is restored through ()
- Use keys to get value
- Get the value with value=(key), if it does not exist, return null
- Restricted by homologous policies
- Pages from different sources cannot access localStorage. For example, if a localStorage is opened/stored in the browser, it cannot access it if it is opened/storage in the browser. Because they have two different sources
- When operating localstorage, storage events that are not currently available will be triggered.
- When we set localStorage on page A, the storage event of other pages will be triggered, which will facilitate us to listen to the storage status and make subsequent responses. For example, complete login on the login page, store the login successful logo logSuc in localStorage, ('logSuc', true); then the personal center page can determine that the login has been logged through the storage event, and read personal information for preloading.
- Supports single deletion and all deletion, respectively, implemented through removeItem(key) and clear() methods
3. Cookies for local storage of javascript
- Cookies are data stored in text files on your computer and are used to store user information on web pages.
- Cookie data exists in the form of key-value pairs, each key-value pair has an expiration time. If the time is not set, the browser is closed and the cookie will disappear. Of course, users can also manually clear the cookie.
- Cookies are carried in HTTP headers every time. If you use cookies to save too much data, it will cause performance problems.
- Cookie memory size is limited. Generally, each domain name is about 4K, and each domain name can store about 50 key-value pairs.
Cookies can be created, modified and retrieved through access. By default, cookies are deleted when the browser is closed. You can also add an expiration time to a key-value pair of the cookie. If a key already exists when a new cookie is set, the corresponding value of this key will be updated, otherwise they will exist in the cookie at the same time.
// Set cookies = "username=orochiz" = "age=20" // Read cookiesvar msg = (msg) // username=orochiz; age=20 // Add expiration time (unit: days)var d = new Date() // Current time 2019-9-25var days = 3 // 3 days(() + days) = "username=orochiz;"+"expires="+d // Delete cookies (set expiration time for a key-value pair)(() - 1) ()
4. IndexDB for local storage of javaScript
- The storage methods mentioned above are all stored in the form of strings. What should we do if our current requirement is to store a large amount of structured data? Then use indexDB
- This is a serious database. All students working on the server know about the database, and this is no different from the database. It's just that they exist on the client.
- If this is the case, it means that there are many advantages, including the following points
- There is no upper limit for storage
- All operations are asynchronous, with higher performance than LocalStorage synchronous operations, especially when the data volume is large.
- Natively support objects that store JS
- It is a serious database, which means that the database can do everything - how does it operate it specifically? Everyone says that it is a database, so follow the general operation process of the database.
- Establish a connection and open the database, operate the database addition, deletion, modification and search, but in order to better use the client, some fine-tuning may be made in certain steps or programs, so we will operate a real-time operation
class DBOpration{ constructor() { = null } getType(val) { let type = typeof val == 'object' return type } // Open the database open(parm) { return new Promise((res, rej) => { let request = (, ) = function(event) { (event) // Error handling rej() ('Open the database and report an error') } = event => { = ('The database is successfully opened') res() // Successfully processed } // Callback when database updates = event => { = (parm) } }) } // Create library table createdDB(parm) { (parm) if (!()) { (, { keyPath: 'id' }) // ("data", "data", { unique: false }); // unique name may be repeated } } // New (no need to use) async add(parm = { dbName, objName, param, response }) { await (parm) // await (dbName); return new Promise((res, rej) => { let type = () let type1 = () let transaction = ([], 'readwrite') let objectStore = () // The user reads the data, the parameter is the primary key let request = ({ id: type ? () : , data: type1 ? () : }) (request) = function(event) { res(event) ('Data written successfully') } = function(event) { rej() ('Data write failed') } }) } // Read library table data async read(parm = { dbName, objName, param, response }) { await (parm) return new Promise((res, rej) => { let type = () var transaction = ([]) var objectStore = () // The user reads the data, the parameter is the primary key var request = (type ? () : ) = function(event) { ('Transaction failed') rej() } = function(event) { if () { let data = () res(data) } else { res() ('No data record obtained') } } }) } // Modify the library table data, but because the library table is created directly when creating the database, it is enough to remove this whether it is added or modified. async update(parm = { dbName, objName, param, response }) { await (parm) return new Promise((res, rej) => { let type = () let type1 = () (parm) var request = .transaction([], 'readwrite') .objectStore() .put({ id: type ? () : , data: type1 ? () : }) = function(event) { res() ('Data update successfully') } = function(event) { rej() ('Data update failed') } }) } // Delete the data of a certain table async remove(parm = { dbName, objName, param, response }) { await (parm) return new Promise((res, rej) => { let type = () var request = .transaction([], 'readwrite') .objectStore() .delete(type ? () : ) = function(event) { res() ('Data deletion succeeded') } }) } } let db=new DBOpration()//Create a database instance//Next, add, delete, modify, check and retrieve the corresponding methods
Summary: Use scenarios of different storage methods for localStorage, sessionStorage, cookie, indexDB
Cookies, suitable for marking users and tracking user behavior
localStorage, suitable for saving users' local data for a long time, such as tokens
sessionStorage, suitable for one-time login for sensitive accounts
indexDB is suitable for storing a large amount of structured data, such as the editing history saving of rich text editors, etc.
These four local storage methods are all saved on the browser side, but they have the following differences:
The cookie data is sent to the server in every HTTP request, while the sessionStorage and localStorage are only saved locally.
The cookie data size is limited to 4KB, while sessionStorage and localStorage can reach 5MB or more.
sessionStorage is only valid for the current session, localStorage is always valid, and cookies are valid before the set expiration time.
sessionStorage is not shared in different browser windows, while localStorage and cookies are shared in all homologous windows.
- indexDB is a database that can store a large amount of data. It supports storing JS objects natively. All operations are asynchronous and have higher performance than LocalStorage synchronous operations.
Local storage provides a convenient way to persist user data, but it should be noted that they all follow a same-origin policy and different websites cannot share the same storage space. In addition, since localStorage and sessionStorage only support string type storage, type conversion is required when storing data of non-string type.
The above is the detailed content of the 4 methods and usage scenarios of local storage in JavaScript. For more information about the 4 methods and usage methods of local storage in JavaScript, please pay attention to my other related articles!