api and encapsulation of cookie s

Posted by Chris-the dude on Fri, 18 Feb 2022 04:40:35 +0100

The last article compared the differences among cookies, localstorage and sessionstroage. It mentioned that cookies need to be specially encapsulated, while the other two have special get and set methods. Today is the main day. Look at the encapsulation of cookies in the actual project.

First, let's take a look at the properties and methods of cookie s.

In fact, there are only two, one to read and one to write.

1, Read

allCookies = document.cookie

We passed the document cookie can obtain all cookies under the current domain name and its subdomain name, which is marked with " (semicolon + space) a string in the form of a key value pair as a separator.

For example, you can open the console under the mdn website to input

document.cookie

Will appear

'_ga=GA1.2.1682758841.1619014911; preferredlocale=en-US; lux_uid=164510371039082338; _gid=GA1.2.750491686.1645103711'

Of course, different computers are different.

2, Write

document.cookie = newCookie

It is worth noting here that the newCookie is also a string, which contains 1 + 5 parameters, which are

1. String consisting of key name and key value. Required

"${name}=${value}"

It is worth noting that if value is a semicolon or a space, it will be deleted. I just learned it after experiencing it

2,path

;path=*path*

path is used to determine which request the cookie is sent with

Suppose your browser currently has two cookies:

cookie1: name=name1; value=value1; path=/boyue/; cookie2: name=name2; value=value2; path=/boyue/tongxue/.

When visiting http://localhost/boyue/ *When, the request header will contain cookie1 instead of cookie2.

When visiting http://localhost/boyue/tongxue/ *When, the request header will contain the above two.

That is, when accessing the child path, the Cookie of its parent path will be included, while when accessing the parent path, the Cookie of the child path will not be included. This is actually quite logical when you think about it, otherwise this parameter will be meaningless.

3,domain

;domain=*domain*

Set the domain. Some students may think that why do I need the domain parameter when I have path? It is mainly to share or distinguish some parameters under different domain names, such as a.boyue COM and b.boyue.com COM is a different domain name, but they can all get boyue COM, but they can't get each other. Remember to bring a "." Otherwise, this parameter can only be obtained when the domain name is exactly the same.

4,max-age

;max-age=*max-age-in-seconds*

It's easy to understand how long it will expire

5,;expires=date-in-GMTString-format

Set the expiration time and date, similar to the above

6,;secure

Indicates whether cookie s can only be transmitted through https protocol

If true, even if js gets the corresponding cookie, the http request cannot carry this parameter.

3, Encapsulation

Encapsulation is mainly to modify its writing and obtaining methods, especially the obtaining methods. After all, what I need is the corresponding value rather than all key value pairs. Here's a simple implementation

const cookie = {
  get: function (sKey) {
  // According to the stored rules (different key value pairs are distinguished by semicolons and spaces, and small attributes are distinguished by semicolons), use ";" first Cut, and then take out the contents of the first equal sign and the first semicolon
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" +       encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  // Write it in and it will directly overwrite the original key value pair
  set: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  // Set the corresponding expiration time to be less than the current time
  remove: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  }
};