webStorage
Basic concepts
webStorage provides two storage methods, localStorage and sessionStorage.
- localStorage is a persistent storage, and the stored content will exist permanently if it is not deleted actively
- sessionStorage is session level storage. Close the browser and destroy it
The specific difference is
- After closing the web page and reopening it, localStorage will be retained and sessionStorage will not be retained
- Jump in the page, localStorage and sessionStorage will be retained
- Jump outside the page (open a new page), localStorage will be retained, and sessionStorage will not be retained
Properties and methods
Both localStorage and sessionStorage have the following properties and methods
- Set value setItem(key, value)
- Get the value key(index) through the index
- Get the value getItem(key) through key
- Remove a key removeItem(key)
- clear()
- Length the length of the stored data
localStorage.setItem('name', 'alice') localStorage.setItem('age', 20)
The stored content can be viewed through the Application in the developer tool
Because locaStorage and sessionStorage are attributes on the window, they can also be operated directly on the Console
Tool encapsulation
localStorage and sessionStorage can only store strings. When an object is encountered, it will be directly converted to a string such as "[object]". In this way, it can only be read to "[object]" in the future, and the data will be lost
const lesson = { subject: "Math", }; localStorage.setItem("lessonObj", lesson); localStorage.setItem("lessonStr", JSON.stringify(lesson));
Therefore, when storing objects, we need to convert the objects into strings first
Every time you store data, you need to serialize the data by stringify. You need to parse the data into objects. You can encapsulate the repeated code into tool functions
class iceStore { constructor(flag) { this.storage = flag ? localStorage : sessionStorage; } setItem(key, value) { const str = JSON.stringify(value); this.storage.setItem(key, str); } getItem(key) { let value = this.storage.getItem(key); if (value) { return JSON.parse(value); } } key(index) { return this.storage.key(index); } removeItem(key) { return this.storage.removeItem(key); } clear() { return this.storage.clear(); } length() { return this.storage.length; } } const localCache = new iceStore(true); const sessionCache = new iceStore(false); export { localCache, sessionCache };
You can import it where you need to use localStorage/sessionStorage~
indexedDB
indexedDB is a database for the client. It uses key value pairs to store a large amount of data, some like NoSQL.
First open the connection to indexedDB through the following code
// Open a database named iceDB. If not, create a new one const dbRequest = indexedDB.open("iceDB") // Call function when opening / version updating for the first time dbRequest.onupgradeneeded = function(event){ // Get db object of operation database const db = event.target.result // Create some storage objects, such as table structures. keyPath will be used as the primary key of the table to distinguish uniqueness, // Every piece of data stored in users needs an id attribute db.createObjectStore("users", { keyPath: 'id' }) } let db = null dbRequest.onsuccess = function(event){ // Get the db object, save it in the global, and use it to operate the database db = event.target.result }
At this point, a database named iceDB has been created with a table named user
// The first parameter in the transaction can be an array, and readwrite can read and write const transaction = db.transaction("users", "readwrite") // The objectStore method gets the store object from the above transaction const store = transaction.objectStore("users") // increase const request = store.add({ id: 1, name: 'kiki', 18}) // Callback for completion of one operation request.onsuccess = function(){} // Callback for a failed operation request.onerror = function(){} // When all transactions are completed, a callback is passed in transaction.oncomplete = function(){} // Query, open cursor const request = store.openCursor() request.onsuccess = function(event){ // event contains a cursor. When the cursor has no value, it indicates that it has reached the end const cursor = event.target.result if(cursor){ // Stop query on a condition if(...){ }else{ // Cursor continue lookup cursor.continue() } } } // modify // First query the specified data and change the data directly through the cursor const value = cursor.value; value.name = "lucy"; cursor.update(value) // delete // Query the specified data first and call the delete method of the cursor cursor.delete()
Effect of final storage
cookie
Although cookies are also the storage scheme of the browser, they are generally set by the server through the set cookie field of the http request header. The browser will carry them every time it sends a request
Classification of cookie s
- The memory Cookie is maintained by the browser and saved in memory. When the browser closes, the Cookie will be destroyed
- The hard disk Cookie is saved in the hard disk and has an expiration time. It will not be cleared until the user manually clears it or the expiration time expires
cookie set expiration time
- expires: date is set toUTCString()
- Max age: set the seconds of expiration, for example, 60 * 60 * 24 * 365 for a year
Other properties of cookie s
- If the domain is not specified, the default is origin, excluding subdomain names, and including subdomain names after specifying
- path specifies which paths under the host can accept cookie s
The illustration is as follows
Setting cookie s on the browser side
Through document If httpOnly is set on the server, the browser cannot change the cookie set by the server
For specific cookie settings, please refer to this server article~
How to authenticate through cookie and session (nodejs/koa)
The above is the content related to browser storage. There are still many places for developers to master about js advanced. You can see other blog posts I wrote and keep updating~