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>