The interviewer asked: what is your understanding of cookie s?

Posted by IndianaRogers on Thu, 03 Mar 2022 04:09:28 +0100

Foreword: I believe junior front-end engineers will think of local storage and sessionStorage. Then I will answer the difference between the three. Please, these are not the key information that the interviewer wants to get. Cookies belong to the basic knowledge of computer networks. Next, let's unveil the mystery of cookie s from Baidu Encyclopedia. (the content is all from the blogs and community platforms of the bigwigs)

cookie concept

Cookie s, sometimes in the plural. The type is "small text file", which is the data (usually encrypted) stored on the user's local terminal by some websites in order to identify the user's identity and track the Session, and the information temporarily or permanently saved by the user's client computer.

cookie is like an identity card issued by the server to the client. With this identity card, as long as the client carries this identity card with him The server can identify us

Composition of cookie s

A Cookie is a small piece of text data of no more than 4KB, which is composed of a Name, a Value and several other optional attributes used to control the validity, security and scope of use of the Cookie

  1. Name/Value: set the name of the Cookie and the corresponding Value. For authentication cookies, the Value includes the access token provided by the Web server.
  2. Expires property: sets the lifetime of the Cookie. There are two storage types of cookies: conversational and persistent. By default, the expires attribute is a conversational Cookie, which is only saved in the client memory and expires when the user closes the browser; The persistent Cookie will be saved in the user's hard disk and will not expire until the lifetime expires or the user directly clicks the "logout" button in the web page to end the session.
  3. Path property: defines the directory on the Web site where the Cookie can be accessed.
  4. Secure attribute: Specifies whether to send cookies using HTTPS security protocol. Using HTTPS security protocol can protect cookies from being stolen and tampered during the transmission between browser and Web server. Due to the lack of security awareness of many users, it is still possible to connect to the website forged by Pharming attack.
  5. HTTPOnly attribute: used to prevent client script from passing through document The Cookie attribute accesses cookies to help protect cookies from being stolen or tampered with by cross site scripting attacks. However, the application of HTTPOnly still has limitations. Some browsers can prevent the client script from reading cookies, but allow writing operations; In addition, most browsers still allow set Cookie headers in HTTP responses to be read through XMLHTTP objects.

Read, write, delete and modify cookie s

1. Read cookie s

console.log(document.cookie) 

Between multiple cookie s; If we want to find an object, we can encapsulate a method:

/** Get a cookie
 * @param {string} key The name of the cookie to get
 * @retrun {string} The value of the current cookie
 */
getCookie (key) {
    var str = document.cookie
    var arr = str.split('; ')
    var obj = new Object()
    arr.forEach(item => {
        var subArr = item.split('=')
        obj[subArr[0]] = decodeURIComponent(subArr[1])
    })
    return obj[key]
}

2. Write cookie s

Simply store a cookie

document.cookie = 'username=zansan'

Encapsulate a method to store cookie s

/** Save a cookie
 * @param {string} key The name of the cookie to save
 * @param {string} value The value of the cookie to save
 * @param {object} [options] Optional parameters, expiration time and directory, such as: {path: '/', expires: 7} cookie with 7-day expiration in stub directory
 */
function setCookie (key, value, options) {
    var str = `${key}=${encodeURIComponent(value)}`
    // First judge whether the options are passed in
    if (options) {
        // If it comes in, judge which attribute it has
        if (options.path) {
            // The path is spliced in
            str += `;path=${options.path}`
        }
        if (options.expires) {
            var date = new Date()
            // Date set to expiration time
            date.setDate(date.getDate() + options.expires)
            str += `;expires=${date.toUTCString()}`
        }
    }
    document.cookie = str
}

3. Delete cookie s

The method of deleting cookie s is very simple. You only need to set the expiration time to the past time.

/** Delete a cookie
 * @param {string} key The name of the cookie to delete
 * @param {path} [path] Optional parameter: the path of the cookie to be deleted. If it is the current path, this parameter can not be passed
 */
function removeCookie (key, path) {
    var date = new Date()
    date.setDate(date.getDate() - 1) // The expiration time is set to yesterday
    var str = `${key}='';expires=${date.toUTCString()}`
    if (path) {
        str += `;path=${path}`      
    }
    document.cookie = str
}

4. Modify cookie s

Modification is to rewrite the cookie, which is no different from the operation of writing the cookie.

Topics: Javascript Front-end Mini Program