Cookie Store API
获取和设置 cookie 的信息
- 无法获取
HttpOnly
标记的 cookie expires
为 null 时,表示会话结束时过期domain
只有在domain
为当前域名的主域名时才显示(不包含子域名),否则为 null.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0" />
<title>Cookie Store API</title>
</head>
<body>
<strong>获取和设置 cookie 的信息</strong>
<hr />
<button type="button" class="btn-add">增</button>
<button type="button" class="btn-del">删</button>
<button type="button" class="btn-update">改</button>
<button type="button" class="btn-get">查</button>
<button type="button" class="btn-clear">清空</button>
<script>
// Cookie Store API 获取和设置 cookie 的信息
// 无法获取 HttpOnly 标记的 cookie
// expires 为 null 时,表示会话结束时过期
// domain 只有在 domain 为当前域名的主域名时才显示(不包含子域名),否则为 null.
const cookieListUl = document.querySelector('.cookie-list');
const btnAdd = document.querySelector('.btn-add');
const btnDel = document.querySelector('.btn-del');
const btnUpdate = document.querySelector('.btn-update');
const btnGet = document.querySelector('.btn-get');
const btnClear = document.querySelector('.btn-clear');
/** @type {CookieStore} */
const cookieStore = globalThis.cookieStore;
// 监听 cookie 的变化
cookieStore.addEventListener('change', async (e) => {
/* changed、deleted */
console.log('cookie change => ', e);
const cookies = await cookieStore.getAll();
console.log('cookies => ', cookies);
});
btnAdd.addEventListener('click', () => addCookie({ name: 'a', value: '1' }));
btnDel.addEventListener('click', () => delCookie({ name: 'a' }));
btnGet.addEventListener('click', () => getCookie({ name: 'a' }));
btnUpdate.addEventListener('click', () => updateCookie({ name: 'a', value: '2' }));
btnClear.addEventListener('click', () => clearAllCookie());
// 新增 cookie
function addCookie(option) {
cookieStore.set(option);
}
// 删除 cookie
function delCookie(option) {
cookieStore.delete(option);
}
// 更新 cookie
function updateCookie(option) {
addCookie(option);
}
// 获取 cookie
function getCookie(option) {
return cookieStore.get(option);
}
// 获取所有的 cookie
function getAllCookie(option) {
return cookieStore.getAll(option);
}
// 清除所有的 cookie
async function clearAllCookie() {
const cookies = await cookieStore.getAll();
cookies.forEach((cookie) => delCookie(cookie.name));
}
</script>
</body>
</html>
标签:const,option,API,cookie,cookieStore,querySelector,Cookie,document,Store
From: https://www.cnblogs.com/chlai/p/18164367