const Cookie = {
/**
* 設置 Cookie
* @param {string} name
* @param {string} value
* @param {Object} options
* - expires: number(天) | Date
* - maxAge: number(秒)
* - path: string (默認 '/')
* - domain: string
* - secure: boolean
* - sameSite: 'Strict' | 'Lax' | 'None'
*/
set(name, value, options = {}) {
if (typeof name !== 'string') throw new TypeError('Cookie name must be string');
const opts = {
path: '/',
sameSite: 'Lax',
...options
};
let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`;
if (opts.expires) {
const date = opts.expires instanceof Date ? opts.expires : new Date(Date.now() + opts.expires * 864e5);
cookie += `; expires=${date.toUTCString()}`;
}
if (opts.maxAge) cookie += `; max-age=${opts.maxAge}`;
if (opts.path) cookie += `; path=${opts.path}`;
if (opts.domain) cookie += `; domain=${opts.domain}`;
if (opts.secure) cookie += `; secure`;
if (opts.sameSite) cookie += `; samesite=${opts.sameSite}`;
document.cookie = cookie;
return this;
},
/**
* 獲取 Cookie
* @returns {string|null} 解碼後的值,不存在返回 null
*/
get(name) {
if (!document.cookie) return null;
const escaped = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${escaped}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : null;
},
/**
* 刪除 Cookie(設置過期)
*/
remove(name, options = {}) {
return this.set(name, '', { ...options, expires: -1 });
},
/**
* 獲取所有 Cookie 為對象
*/
getAll() {
const cookies = {};
if (!document.cookie) return cookies;
document.cookie.split(';').forEach(pair => {
const [name, ...rest] = pair.trim().split('=');
if (name) cookies[decodeURIComponent(name)] = decodeURIComponent(rest.join('='));
});
return cookies;
},
/**
* 檢查是否存在
*/
has(name) {
return this.get(name) !== null;
}
};
// 使用示例
Cookie.set('theme', 'dark', { expires: 365, sameSite: 'Strict' });
Cookie.set('session_id', 'abc123', { maxAge: 3600, secure: true, sameSite: 'None' }); // 跨站需 Secure
console.log(Cookie.get('theme')); // 'dark'
console.log(Cookie.getAll()); // { theme: 'dark', session_id: 'abc123' }
Cookie.remove('session_id');
// 原文問題:
// 1. 使用 jQuery.trim 但未引入 jQuery → 替換為 .trim() 或自定義
// 2. 正則 /(^[s]*)|([s]*$)/g 中 \s 寫錯為 s
// 3. 未 encodeURIComponent → 中文/特殊字符會導致解析錯誤
// 4. 未支援 SameSite、maxAge 等現代屬性
// 修正版 trim polyfill(若環境無 String.prototype.trim)
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
| 屬性 | 建議 | 說明 |
|---|---|---|
| HttpOnly | 服務端設置 | 防 XSS 竊取,JS 無法讀取(document.cookie 不可見) |
| Secure | HTTPS 站點必開 | 僅 HTTPS 傳輸 |
| SameSite | Lax (默認) / Strict | 防 CSRF;跨站需求用 None+Secure |
| Path | 最小權限路徑 | 避免洩露給無關路徑 |
| Domain | 不設或父域 | 避免過度共享 |
| __Host- 前綴 | 高安全 Cookie | 強制 Secure、Path=/、無 Domain |
| __Secure- 前綴 | 高安全 Cookie | 強制 Secure |
// 異步、Promise-based、Service Worker 可用
if ('cookieStore' in window) {
// 獲取
const cookie = await cookieStore.get('theme');
console.log(cookie?.value);
// 設置
await cookieStore.set('theme', 'dark', {
expires: Date.now() + 864e5, // 毫秒時間戳
path: '/',
sameSite: 'lax'
});
// 刪除
await cookieStore.delete('theme', { path: '/' });
// 監聽變更(含 Service Worker)
cookieStore.addEventListener('change', (e) => {
console.log('Changed:', e.changed.map(c => c.name));
console.log('Deleted:', e.deleted.map(c => c.name));
});
// 獲取所有
const all = await cookieStore.getAll();
}
Cookie 操作看似簡單,實則涉及編碼、安全屬性、跨域策略、過期計算等眾多細節。**封裝統一工具類**並嚴格遵循安全最佳實踐,是前端工程化的基本功。現代專案應逐步遷移至 **Cookie Store API** 或減少 Cookie 依賴,轉向 `localStorage`/`IndexedDB` + `HttpOnly Cookie` 分離架構。