TNTWeb – The full name of Tencent news front end team, partners in the group have practiced and accumulated experience in Web front end, NodeJS development, UI design, mobile APP and other large front end fields.

At present, the team mainly supports the front-end development of Tencent news business. Besides business development, some front-end infrastructure has been accumulated to enable business efficiency improvement and product innovation.

The team advocates open source construction, has a variety of technical masters, the team Github address: github.com/tnfe

The author is wenzi0github

We usually add, delete, change and check cookie operations, are operating document. Cookie, here we introduce a new method cookieStore.

1. How do I operate cookies

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

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

If you’re manipulating cookies, you’re manipulating Document.cookie. For example, here is a piece of code I often use:

/** * write cookies *@param {string} Name Key * for writing cookies@param {string|number} Value Indicates the cookie value *@param {number} Day Specifies the storage duration. The default value is 30 days */
export const setCookie = (name: string.value: string | number, day = 30) :void= > {
  const exp = new Date(a); exp.setTime(exp.getTime() + day *24 * 60 * 60 * 1000);
  document.cookie = `${name}=The ${escape(value.toString())}; path=/; expires=${exp.toUTCString()}`;
};

/** * Read cookies *@param {string} Name Name of the cookie to be obtained *@param {number|boolean} Type whether to retrieve the corresponding value directly, if stored in true value, directly return, otherwise decoding */
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 cookie to be deleted */
export const delCookie = (name: string) = > {
  if(! name)return;
  const ex: Date = new Date(a); ex.setTime(ex.getTime() -1);
  document.cookie = `${name}=; expires=${ex.toUTCString()}; path=/`;
};
Copy the code

As you can see, setting, retrieving, and deleting cookies are all done on document.cookie.

2. New way cookieStore

Now Chrome has a more convenient way to manipulate cookies, which was added in Chrome87 and isn’t quite as compatible.

The following is a compatibility overview as of the current date 2021/03/15. You can see that cookieStore is only supported by the Chrome OS.

But let’s see how it works first.

CookieStore is now accessible only through HTTPS domain names. In other HTTP domain names, cookieStore is undefined, or the setting fails.

2.1 Basic Methods

CookieStore is an object variable similar to localStorage.

You can see cookieStore has five main methods:

  • Set: Sets the cookie, either set(name, value) or set({name, value}).
  • Get: get cookies, can be get(name), or get({name});
  • GetAll: gets all cookies;
  • Delete: deletes the cookie.
  • Onchange: monitors cookie changes.

The first four naturally support Promise. Let’s take a look at them one by one.

2.2 setting cookies

The cookiestore. set method sets cookies and returns a Promise state indicating success.

cookieStore
  .set('username'.'wenzi')
  .then(() = > console.log('Set username successfully'))
  .catch(() = > console.error('Failed to set username'));
Copy the code

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

cookieStore
  .set({
    name: 'age'.value: 18.expires: new Date().getTime() + 24 * 60 * 60 * 1000,
  })
  .then(() = > console.log('Age set successfully'))
  .catch(() = > console.error('Setting age failed'));
Copy the code

All data in value is executed toString() by default before being stored, so it is best to convert data of non-basic types first.

The above are all cases where we set cookies successfully, so when will the setting fail? Setting localhost fails in the local environment.

Localhost, we can get the global variable cookieStore and execute the corresponding method, but cannot set it successfully:

cookieStore.set('username'.'wenzi');
Copy the code

The browser will prompt you that you cannot set a cookie with set in CookieStore under an insecure domain name:

Uncaught (in promise) TypeError: Failed to execute 'set' on 'CookieStore': Cannot modify a secure cookie on insecure origin
Copy the code

When you add catch, you catch this error:

cookieStore
  .set('username'.'wenzi')
  .then(() = > console.log('Set username successfully'))
  .catch(() = > console.error('Failed to set username'));
Copy the code

Therefore, if you want to use cookieStore, you can not directly determine the following way, but also need to add a new page URL protocol to determine:

typeof cookieStore === 'object'; // The localhost will also exist
Copy the code

Should use:

const isSupportCookieStore = typeof cookieStore === 'object' && location.protocol === 'https:'; CookieStore is used only under HTTPS
Copy the code

2.3 get a cookie

The cookiestore.get (name) method retrieves the cookie corresponding to name and returns all properties in the Promise format:

await cookieStore.get('username');
Copy the code

The get() method can also accept an Object, and when tested, the key can only be name:

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

When the obtained cookie does not exist, a Promise< NULL > is returned.

2.4 Get all cookies

The cookiestore.getall () method retrieves all of the current cookies, returning them as promised <[]>, with each item in the array in the same format as the one obtained by get(); An empty array if the current field has no cookies, or the specified cookie cannot be obtained.

await cookieStore.getAll();
Copy the code

The getAll() method can also pass in a name to retrieve the corresponding cookie:

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

2.5 delete the cookie

Cookiestore.delete (name) deletes the specified cookie:

cookieStore
  .delete('age')
  .then(() = > console.log('Age deleted successfully'))
  .catch(() = > console.error('Delete age failed'));
Copy the code

If the deletion succeeds, a message is displayed indicating that the deletion succeeds.

Even if a non-existent cookie is deleted, the deletion succeeds. Therefore, when the above code is executed again, it will be prompted as usual.

Similarly, in the localhost environment, deletion failed.

2.6 Monitor cookie changes

We can listen for cookie changes by adding the change event, either through cookieStore or directly through document.cookie.

Add listening events:

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 now${type}Operation, cookie has:The ${JSON.stringify(data)}`);
});
Copy the code

There are two important fields in the changed array and deleted array. When setting cookies, the changed array contains the cookies that were just set. When the cookie is deleted, the deleted cookie is in the deleted array.

2.6.1 Setting Operations

When the set() method is called, the change event is emitted and the affected cookie is placed in the Event.Changed array.

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

The change event is triggered each time a cookie is set, even if the name and value are exactly the same.

cookieStore.set('math'.90);
Copy the code

2.6.2 Deleting a vm

When an existing cookie is deleted using the delete() method, the change event is triggered and the deleted cookie is placed in the Event.deleted array.

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

cookieStore.delete('math');
Copy the code

As you can see, the change event is not triggered when the cookie with name math is deleted the second time.

3. Summary

We have learned about the use and operation of cookieStore in the whole article. It is much easier than us to operate cookies directly, and we can also monitor the changes of cookies through our own change event.