TNTWeb-the full name of Tencent News front-end team, the small partners in the group have practiced and accumulated in the front-end fields such as Web front-end, NodeJS development, UI design, and mobile APP.
At present, the team mainly supports the front-end development of Tencent News's various businesses. In addition to business development, it has also accumulated some front-end infrastructure to empower business efficiency and product innovation.
The team advocates open source and co-construction, and has a variety of technical experts. The team Github address: https://github.com/tnfe
The author of this article wenzi0github
We usually add, delete, modify, check and other operations on cookies, all of which are operating document.cookie. Here we introduce a new method cookieStore
.
1. How to operate cookies
document.cookie can get all the cookie strings of the current domain. Each cookie is separated by a semicolon:
document.cookie; // "a=1; b=2; c=wenzi"
To manipulate cookies is to manipulate document.cookie. For example, the following is a piece of code I often use:
/**
* 写cookies
* @param {string} name 写cookie的key
* @param {string|number} value 写cookie的值
* @param {number} day 存储的时间,默认30天
*/
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()}`;
};
/**
* 读取cookies
* @param {string} name 要获取的cookie名称
* @param {number|boolean} type 是否直接获取对应的值,若存入真值,则直接返回,否则进行解码
*/
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;
};
/**
* 删除cookie
* @param name 删除的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, getting, and deleting cookies are all performed on document.cookie.
2. New way cookieStore
Now Chrome has a more convenient way to manipulate cookies, cookieStore
. This method was added in Chrome87, and the compatibility is not very good.
The figure below is an overview of the compatibility 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.
The cookieStore can only https protocol; other http protocol domain names will prompt that the cookieStore is undefined or the setting fails.
2.1 Basic method
cookieStore is an object type variable 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 cookie, can be get(name), or get({name});
- getAll: get all cookies;
- delete: delete the cookie;
- onchange: monitor cookie changes;
The first 4 methods naturally support Promise. Next, let's understand one by one.
2.2 Set cookies
The cookieStore.set method can set the cookie and return a Promise status to indicate whether the setting is successful.
cookieStore
.set('username', 'wenzi')
.then(() => console.log('设置username成功'))
.catch(() => console.error('设置username失败'));
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成功'))
.catch(() => console.error('设置age失败'));
All data in value will execute toString()
default, and then store it. Therefore, some non-basic data should be converted first.
The above are all cases where we set the cookie successfully, so when will the setting fail? It will fail to set in the local localhost environment.
Local localhost, we can get cookieStore
, and we can also execute the corresponding method, but it cannot be set successfully:
cookieStore.set('username', 'wenzi');
The browser will issue a prompt, and the cookie cannot be set through the 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
After adding catch, you can catch this error:
cookieStore
.set('username', 'wenzi')
.then(() => console.log('设置username成功'))
.catch(() => console.error('设置username失败'));
Therefore, when you want to use cookieStore, you can't directly judge by the following method, and you have to add a page url protocol to judge:
typeof cookieStore === 'object'; // 判断不准确,本地localhost也会存在
Should use:
const isSupportCookieStore = typeof cookieStore === 'object' && location.protocol === 'https:'; // 只有在https协议下才使用cookieStore
2.3 Get cookies
cookieStore.get(name)
method can get the cookie corresponding to name, and will return all the attributes 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
cookieStore.getAll()
method can get all the current cookies, and return them in the form of Promise<[]>. Each item in the array has the same format as the get() method; if the current domain does not have a cookie, or cannot be obtained The specified cookie is an empty array;
await cookieStore.getAll();
The getAll() method can also pass in a name to obtain the corresponding cookie:
await cookieStore.getAll('username');
await cookieStore.getAll({ name: 'username' });
2.5 Delete cookies
cookieStore.delete(name)
used to delete the specified cookie:
cookieStore
.delete('age')
.then(() => console.log('删除age成功'))
.catch(() => console.error('删除age失败'));
After the deletion is successful, it will prompt that the deletion is successful.
Even if a cookie that does not exist is deleted, it will prompt that the deletion is successful. Therefore, when the above code is executed again, it will still prompt normally.
Similarly, in the localhost environment, it will prompt deletion failure.
2.6 Monitoring cookie changes
We can monitor the cookie changes by adding the change
event, whether it is through the cookieStore operation or the document.cookie directly.
Add a listener 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(`刚才进行了 ${type} 操作,cookie有:${JSON.stringify(data)}`);
});
There are two important fields, changed
array and deleted
array. When a cookie is set, the changed array will contain the cookie just set; when the cookie is deleted, the deleted array will contain 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 the cookie, not deleting it.
Each time the cookie is set, even if the name and value are exactly the same twice, the change
event will be triggered.
cookieStore.set('math', 90);
2.6.2 Delete operation
When an existing cookie is deleted through the delete() method, the change event will be triggered, and the deleted cookie will be placed in the event.deleted
array.
If a cookie that does not exist is deleted, the change event will not be triggered.
cookieStore.delete('math');
As you can see, when the cookie whose name is math is deleted for the second time, the change event is not triggered.
3. Summary
We have learned about the cookieStore
throughout this article. It is much easier than we can directly manipulate cookies, and we can also monitor cookie changes through our own change event.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。