This is the fourth day of my participation in Gwen Challenge

Client storage technology

In order to improve the user experience, there is a growing need to store user information directly on the client. Whether it is to achieve automatic login, personal preferences, skin functions, etc., can be achieved using client storage. This article introduces several common storage methods of Web clients, analyzes them based on actual application scenarios, and shares relevant codes

First of all, the knowledge of this paper is summarized

1. Cookie

A Cookie is some data stored in a text file on your computer. Before HTML5 came along, cookies were the primary storage method.

The history of cookies is too shallow to discuss :pensive:

1.1 Restrictions on Cookies

Because the cookie is stored on the client’s machine, the browser limits it to make sure it can’t be used maliciously, and you’ll be fine as long as you follow the following rules, right

  • No more than 300 cookies
  • Each cookie does not exceed 4096 bytes, i.e4k
  • There are no more than 20 cookies per field
  • Each field does not exceed 81920 bytes

The total number of cookies that can be set per domain is also limited, but the limits vary from browser to browser

Note: When the total number of cookies exceeds the upper limit for a single domain, the browser deletes the cookies previously set

1.2 Composition of cookie

A cookie in a browser is made up of the following parameters

  1. The name of the: Cookie name is case insensitive, thereforemyCookieandMyCookieIt’s the same name. In practice, however, it is best tocookieTreating names as case-sensitive not only improves code readability, but also avoids unnecessary misunderstandings
  2. value: stored in acookieThe string value in
  3. Domain: domain indicates the domain where the cookie resides. The default domain of the cookie is the current domain name.
  4. The pathRequest:URLContains this pathcookieSend to the server. For example, specify the cookie path ashttp://www.baidu.com/my/ljchttp://www.baidu.com/my/The following page will not be sentcookie
  5. Expiration time: Indicates when to deletecookieThat is, no longer sent to the server. The default is browserAfter the sessionAll cookies are deleted. However, deletion can be setcookieSpecific time so that even when the browser is closedcookieIt is also saved on the user’s local machine. Deletion can be achieved by setting the expiration time to a past timecookie
  6. Safety sign: Only when SSL is used for secure connectioncookieSend to the server. For example, HTTPS requests can be sentccokieHTTP requests do not addsecure“Can be opened

These parameters are separated by semicolons in use

1.3 The use of cookies in JavaScript

Here we will talk about it in combination with the automatic login function, which will go through four steps: setting cookies, obtaining cookies, removing cookies, and initializing operations

1.3.1 setting cookies

function setCookie() {
	let date = new Date(a); date.setTime(date.getTime() +30 * 24 * 60 * 60 * 1000);
	document.cookie = 'username=' + valId.value + '; path=/; expires=' + date.toGMTString();/ / user name
	document.cookie = 'psd=' + valPsd.value + '; path=/; expires=' + 	date.toGMTString();/ / password
}
Copy the code

In the code above, set the cookie named username and PSD, set the path to be accessible under any path, expire at 30 days,

Note: there will be an error of 8 hours, because the browser time is the time of the current location, and the code converted by toGMTString is Greenwich Mean Time (GMT), Beijing is in the 8th east region, so the time will be 8 hours earlier, if the correct 30 days, add 8 hours

Note: The password can be encrypted when saving the account

1.3.2 remove cookies

As mentioned above, when the current time exceeds the cookie expiration time, the cookie will be automatically cleared. We use this feature to achieve the function of removing cookies

function removeCookie() {
    let date = new Date(a); date.setTime(date.getTime() -60 * 60 * 1000);// Time in the past
    document.cookie = 'username=path=/; expires=' + date.toGMTString();
    document.cookie = 'psd=; path=/; expires=' + date.toGMTString();
}
Copy the code

In the code above, focus on the third line and reset the timestamp to expire in the past so that the cookie is automatically cleared.

Note: When we set the cookie with the same name, it will overwrite the previous cookie, thus realizing the function of removing the cookie

1.3.3 Obtaining cookie Values

The operation of obtaining cookies is complicated. There are not too many apis in JavaScript for us to operate cookies, only the Document. cookie attribute in BOM. It can be used to set cookies when it exists as a key. When called as a value, all cookies under the current address can be returned as a string

Note: If multiple cookies are returned together, use; Separated. name1=value1; Name2 =value2, so the following steps are taken to obtain the cookie value

  1. Using a stringsplitMethod to pass the returned string;The identifier is split to return an array
  2. Then through traversing the segmented cookie array, judge the cookie name to be obtained one by one, and finally get the cookie value by processing the array value.
function getCookie(cookieName) {
    cookieName += '=';
    let cookieList = document.cookie.split('; ');
    for (let i = 0; i < cookieList[i].length; i++) {
        let cookieItem = cookieList[i].trim(); // remove whitespace
        if(cookieItem.indexOf(cookieName) ! = -1) {
            return cookieItem.substring(cookieName.length, cookieItem.length)
        }
    }
}
Copy the code

There are many array and string apis in the code, so let’s take a look at them one by one

  • In line 4, the string APIsplitThis method splits a string by a specific identifier and returns a split array. For example:
let str = "How=are; you=doing";
let n = str.split(";");
console.log(n);// ["How=are", "you=doing"]
Copy the code
  • It is used in line 5trimMethod to remove leading and trailing whitespace to prevent whitespace from affecting subsequent processing values
  • The string method is used in line 6indexOf, is used to find whether there is the cookie name we need to obtain in the string. If the returned value is found, it is the index that first appears; otherwise, it is- 1

The inedxOf method returns the first occurrence of a specified string value in a string. Returns -1 if no matching string is found.

  • The string method is used in line 7substringThe change method is used to cut a string by passing in two arguments, the initial position of the cut and the final position

1.3.4 Initialization Operations

With the previous paving, here is relatively easy, we just need to determine whether there is a cookie under the current address, user name and password, if there is, we will automatically log in for them, this step is generally placed in the front of the code, the user opens the page to judge first

function initData() {
    if (getCookie('username') && getCookie('psd')) {
        // The operation to be performed}}Copy the code

Note: there may be some questions here, as long as the user name password is good?

  • My answer is: yes, because when the user logs in, only after the user logs in successfully, we will set cookies for it, so there is no need to worry about the problem of password error.

So that’s how you set, get, and remove automatic login using cookies in JavaScript


The limitations and features of cookies mean that cookies are not an ideal way to store large amounts of data. As a result, other client-side technologies have emerged

Note: Do not store important or sensitive information in cookies. Cookie data is not stored in a secure place.

2. Web Storage

Two storage methods sessionStorage and localStorage have been introduced in HTML5. The purpose of Web Storage is to solve the problem of using cookies to store data that does not need to be sent back to the server frequently through the client.

LocalStorage and sessionStorage are stored in the user’s local browser, unlike cookies carried in HTTP request header fields, effectively avoiding performance problems. LocalStorge also uses the same-origin policy to limit the storage capacity, most of which limit the storage capacity to 5M of the same domain name.

The focus here is on local storage, and the method for temporary storage is the same

Note: Values stored in either way can only be strings

2.1 the localStorage object

LocalStorage: No time limit, duration beyond the current session, data is still available when the browser is closed and opened (note the same domain)

Localstorage is stored in the form of key-value. First, we will understand the following operation methods

  1. Localstorage. length: Gets the number of key-value pairs in the current storage

  2. Localstorage. key(index) : Obtains the key value of an index

  3. Localstorage. getItem(key) : reads the data of the corresponding key value

  4. Localstorage. setItem(key,value) : sets the corresponding key and value pairs to save data

  5. Localstorage. remove(key) : clears specified data

  6. Localstorage.clear () : clears all stored data

2.1.1 small demo

The next step is to implement a simple save search function, as follows

  • Save the name of the user and the amount of money they have
  • Query the amount of money by user name

Code implementation

function set() {
    let myName = document.querySelector('#myName').value;// Get the user name to save
    let money = document.querySelector('#money').value;// Amount of money
    localStorage.setItem(myName, money);/ / save
}
Copy the code

First of all, when we need to save data, we will call the set function, by obtaining the current data to save, directly save

function find() {
    let searchName = document.querySelector('#searchName').value;
    let youMoney = localStorage.getItem(searchName);
    let findEnd = document.querySelector('#findEnd');// Render position on the page
    findEnd.innerHTML = youMoney;
}
Copy the code

When we need to get the user’s money count, we call find to determine who we need to get, and then use getItem to get the key value from the local store and render it to the page.

This allows us to implement a simple local store, and if we need to do something else, like delete the local store, this example deletes data

Delete specified data

//delete localStorage.myName;
localStorage.removeItem(myName)
Copy the code

There are two ways to delete data using delete and removeItem

I don’t want to talk about the rest of it. Same method.


From the above operation we will find that we need to create too many new storage information, each user information we need to create a new local storage for them, the more we store the data will be more complex, this method will become more troublesome

As shown in the picture, this approach is not friendly, so we need to optimize it.

2.1.2 Object Storage Mode

When a large amount of information about a single user needs to be stored, we can use object storage to store the information such as the name, age, and gender of a user in an object

let user = {
    username: 'ljc'.age: '20'.sickName : 'little monkey'.sex : 'male'
}
user = JSON.stringify(user)
localStorage.setItem('my', user);
Copy the code

Since only string data can be stored, we use the json.stringify method to convert the object to a string and store the resulting value as:

LJC "{" username" : ", "age" : "20", "sickName" : "little monkey", "sex", "male"}

So we have the operation we want.

  • When we need to store more user data, instead of just one user data, we can continue to optimize in the above code. We can store the user data in an arrayJSON.stringifyConvert an array to a string, thereby modifying the above code
let userArr = []
userArr.push(user) 
userArr = JSON.stringify(userArr)
Copy the code

Now let’s look at the storage results

[{" username ":" LJC ", "age" : "20", "sickName" : "little monkey", "sex", "male"}]

We can see that the value is now stored in an array, and we can continue to append user information through the push method, thus achieving the desired optimization

When we retrieve locally stored data, we need to parse the retrieved data into objects for reuse

2.2 sessionStorage object

Also called temporary storage, as the name implies only temporary storage, in the browser session window closed, will be cleared

The operation method and localStorage are exactly the same, but more elaboration

3. The difference between several people

  1. Cookies are sent to the server on every request, which wastes bandwidth
  2. The operation method in cookie needs to be encapsulated by itself, which is available in Web StoragesetItem.getItemMethods such as
  3. Cookies can interact with the server. Web Storage only stores data locally
  4. The size limits for storing data are different,cookieGenerally 4 k,web StorageGenerally 5 m
  5. The life cycle of data is not consistent. Cookies can set the time, local storage is permanent, and temporary storage can be said to be one-time
  6. Different scopes,sessionStorageNot shared between different browser Windows,localstorageandcookieIs shared in all origin Windows;

The above is a summary of several common ways of client storage, and I hope you can learn something from it

References: JavaScript Advanced Programming (4th edition)