Explain the native method of operating cookies, cookie store

  • 1. How to operate cookies at ordinary times
  • 2. New way: cookiestore
    • 2.1 basic methods
    • 2.2 setting cookies
    • 2.3 obtaining cookies
    • 2.4 get all cookies
    • 2.5 deleting cookies
    • 2.6 monitoring cookie changes
  • 3. Summary

    1. How to operate cookies at ordinary times

    Document.cookie can obtain all cookie strings of the current domain. Each cookie is separated by a semicolon:

    document.cookie; // "a=1; b=2; c=wenzi"

    The operation of cookies is in the operation of document.cookie. For example, the following is a code I often use:

     *Write cookies
     *@ param {string} name key to write cookie
     *@ param {string|number} value write the value of the cookie
     *The storage time of @ param {number} day is 30 days by default
    export const setCookie = (name: string, value: string | number, day = 30): void => {
      const exp = new Date();
      exp.setTime(exp.getTime() + day * 24 * 60 * 60 * 1000);
      document.cookie = `${name}=${escape(value.toString())};path=/;expires=${exp.toUTCString()}`;
     *Read cookies
     *@ param {string} name name of the cookie to get
     *Whether the @ param {number|boolean} type directly obtains the corresponding value. If the true value is stored, it will be returned directly. Otherwise, it will be decoded
    export const getCookie = (name: string): string | null => {
      const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
      const arr = document.cookie.match(reg);
      if (arr) {
        return unescape(arr[2]);
      return null;
     *Delete cookie
     *@ param name name of the deleted cookie
    export const delCookie = (name: string) => {
      if (!name) return;
      const ex: Date = new Date();
      ex.setTime(ex.getTime() - 1);
      document.cookie = `${name}=; expires=${ex.toUTCString()};path=/`;

    You can see that setting, obtaining and deleting cookies are all performed on document.cookie.

    2. New way: cookiestore

    Now Chrome has a more convenient way to operate cookies, cookie store. This method is added in chrome 87, and its compatibility is not very good.

    The following figure shows the compatibility overview of the current date 2021 / 03 / 15. It can be found that only the chrome system supports cookiestore.

    But we can first understand its usage.

    Cookiestore can only be accessed through the domain name under HTTPS protocol; The domain name of other HTTP protocols will prompt that the cookie store is undefined, or the setting fails.

    2.1 basic methods

    Cookiestore is an object type variable similar to localstorage.

    You can see that there are five main methods for cookiestore:

    • Set: set the cookie, which can be set (name, value) or set ({name, value});
    • Get: get the cookie, which can be get (name), or get ({name});
    • Getall: get all cookies;
    • Delete: delete cookies;
    • Onchange: listen for changes in cookies;

    The first four methods naturally support promise. Next, let’s learn about it one by one.

    2.2 setting cookies

    The cookie store.set method can set cookies and return a promise status indicating whether the setting is successful.

      .set('username', 'wenzi')
      . then (() = > console.log ('setting username succeeded '))
      . catch (() = > console. Error ('failed to set username ');

    If we want to set more properties, such as expiration time, we can pass in an object type:

        name: 'age',
        value: 18,
        expires: new Date().getTime() + 24 * 60 * 60 * 1000,
      . then (() = > console.log ('setting age succeeded '))
      . catch (() = > console. Error ('setting age failed ');

    All data in value will be stored after tostring() by default. Therefore, it is better to convert some non basic types of data first.

    The above is all about the success of setting cookies, so when will the setting fail? Setting fails in the local localhost environment.

    Local localhost, we can get the global variable cookiestore and execute the corresponding methods, but we can’t set it successfully:

    cookieStore.set('username', 'wenzi');

    The browser will prompt that cookies cannot be set through the set in the cookie store under an insecure domain name:

    Uncaught (in promise) TypeError: Failed to execute ‘set’ on ‘CookieStore’: Cannot modify a secure cookie on insecure origin

    After adding catch, you can catch this error:

      .set('username', 'wenzi')
      . then (() = > console.log ('setting username succeeded '))
      . catch (() = > console. Error ('failed to set username ');

    Therefore, when you want to use the cookie store, you can’t judge it directly in the following way. You have to add a protocol for page URL to judge it:

    typeof cookieStore === 'object'; //  If the judgment is not accurate, the local localhost will also exist

    Should use:

    const isSupportCookieStore = typeof cookieStore === 'object' && location.protocol === 'https:'; //  Cookiestore can only be used under HTTPS protocol

    2.3 obtaining cookies

    The cookie store.get (name) method can obtain the cookie corresponding to name and return all properties in promise format:

    await cookieStore.get('username');

    The get () method can also receive an object type. After testing, it is found that the value of key can only be Name:

    await cookieStore.get({ name: 'username' });

    When the obtained cookie does not exist, a promise < null > is returned.

    2.4 get all cookies

    The cookie store. Getall() method can obtain all the current cookies and return them in the form of promise < [] >. The format of each item in the array is the same as that obtained through get(); If there is no cookie in the current domain, or the specified cookie cannot be obtained, it is an empty array;

    await cookieStore.getAll();

    The getall () method can also pass in a name to get the corresponding Cookie:

    await cookieStore.getAll('username');
    await cookieStore.getAll({ name: 'username' });

    2.5 deleting cookies

    Cookie store.delete (name) is used to delete the specified Cookie:

      . then (() = > console. Log ('delete age succeeded '))
      . catch (() = > console. Error ('delete age failed ');

    After the deletion is successful, you will be prompted that the deletion is successful.

    Even if you delete a cookie that does not exist, you will be prompted that the deletion is successful. Therefore, when you execute the above code again, you will still be prompted normally.

    Similarly, in the localhost environment, you will be prompted that the deletion failed.

    2.6 monitoring cookie changes

    We can listen for changes in cookies by adding change events, whether through cookie store operation or direct operation of document.cookie.

    Add listening event:

    cookieStore.addEventListener('change', (event) => {
      const type = event.changed.length ? 'change' : 'delete';
      const data = (event.changed.length ? event.changed : event.deleted).map((item) => item.name);
      Console.log (` just performed ${type} operation, and the cookies include ${JSON. Stringify (data)} ');

    There are two important fields: changed array and deleted array. When a cookie is set, the changed array is the cookie just set; When the cookie is deleted, the deleted array is the cookie just deleted.

    2.6.1 setting operation

    When the set () method is called, the change event will be triggered, and the affected cookies will be placed in the event.changed array.

    Cookies set or deleted through document.cookie are considered to be modifying cookies rather than deleting them.

    Each time a cookie is set, the change event will be triggered even if the name and value are exactly the same twice.

    cookieStore.set('math', 90);

    2.6.2 deleting

    When an existing cookie is deleted through the delete () method, a change event will be triggered, and the deleted cookie will be placed in the event.deleted array.

    If you delete a cookie that does not exist, the change event will not be triggered.


    You can see that when the cookie with name math is deleted for the second time, the change event is not triggered.

    3. Summary

    We have learned about the use and operation of the cookie store throughout this article, which is much easier than directly operating cookies, and we can also monitor the changes of cookies through our own change event.

    The above is a detailed explanation of the native method cookie store for operating cookies. For more information about the native method cookie store of cookies, please pay attention to other developeppaer related articles!