This is the 10th day of my participation in the First Challenge 2022, for more details: First Challenge 2022

Hi, everyone, I’m Starqin. Today is the second day of the first lunar month in 2022. The front end is here to wish you a happy New Year.

What is a cookie and what does it do

As all computer people know, HTTP is a stateless transport protocol, that is, the server cannot identify the client, in order to solve this problem cookie came into being.

The purpose of a cookie is to let the browser remember who I am. For example, as long as WE do not actively log out during a period of time after the browser logs in to a platform, I only need to log in once and the browser will remember me.

In addition, I think cookies are similar to localStorage and sessionStorage in JS BOM, which are used to store data.

The data form of cookie

Cookie data is in the form of a string of key-value pairs, for example: name=starqin; age=22

Note that the space before age is also cookie data, and I didn’t accidentally type it in.

Browser view cookies

1. Shortcuts2. Browser console

Set the cookie

document.cookie = 'name=Starin';

To set a cookie, assign a string of key-value pairs to the cookie; In the above code, name is the key, Starqin is the value, and the key values are connected by ‘=’. For example, there is the following code:

<! DOCTYPEhtml>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>

<body>
    <script>
        document.cookie = 'name=Starqin';
    </script>
</body>
</html>
Copy the code

Check whether the cookie is set successfully

The cookie will be destroyed as soon as the session is closed, similar to sessionStorage It’s similar because cookies differ from sessionStorage in that cookies are time-sensitive data storage.

Set the cookie timeliness

Timeliness when not set

Max-age Next, we set the cookie’s Age for one day

    <script>
        // A day is 86,400 seconds
        document.cookie = 'name=Starqin; Max-Age=86400';
    </script>
Copy the code

Note: js is in milliseconds, but max-age is in seconds, so be careful when setting it

Set the cookie after expiration

Issues needing attention when setting cookies

  1. If multiple cookies need to be set, multiple document. cookies need to be set separately
  2. Set cookie timeliness to max-age The unit of time is second

To get a cookie

Document. Cookie Yes, that’s a simple statement.

It returns a string of cookies

For example, I write console.log(document.cookie) in the page where I just set cookies;

This is a case where there is only one cookie, so what if there are multiple cookies? The following code

<script>

        document.cookie = 'name=Starqin; Max-Age=86400';

        document.cookie = 'age=20; Max-Age=86400';

        console.log(document.cookie);

    </script>
Copy the code

How can I only get the name in the cookie?

Encapsulate the function that gets the cookie

function getCookie() {
    // Get the cookie of the page
    let cookie = document.cookie;
    // Check whether cookie string contains'; ', indicating that more than one cookie value exists
    if (cookie.includes('; ')) {
        // Set the cookie string to '; 'Cut into arrays
        let arr = cookie.split('; ');
        // Create an empty object
        let obj = new Object(a);// Iterate over the cut array
        arr.forEach(function(v) {
            // Create a new empty array
            let newArr = [];
            /* Each element of the arR is of the form: key=value, so we once again cut the string into a new array according to '=' and store it in the new array */
            newArr = v.split('=');
            // Store the first value of the final array as the key name of the obj object, and the second value as the value of obj
            obj[newArr[0].trim()] = newArr[1];
        })
        // Return the obj object
        return obj;
    } else {
        // If there is no '; If there is only one cookie value, it can be directly cut into an array according to '='
        let newArr = cookie.split('=');
        // Create an empty object
        let obj = new Object(a);// Store the first value of the final array as the key name of the obj object, and the second value as the value of obj
        obj[newArr[0]] = newArr[1];
        // Return the obj object
        returnobj; }}Copy the code

Use the above function to get the cookies in the page

This way we can get the specified cookie!