`document.cookie` 返回**所有 Cookie 的單一字串**(以 `; ` 分隔),且**無法直接按名稱索引**。需手動解析,注意:
/**
* 獲取指定名稱的 Cookie 值
* @param {string} name - Cookie 名稱
* @returns {string|null} 解碼後的值,不存在返回 null
*/
function getCookie(name) {
if (!document.cookie) return null;
// 使用正則精確匹配:名稱開頭、後跟 =、捕獲值直到 ; 或結尾
// 需轉義名稱中的正則特殊字符
const escapedName = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
const regex = new RegExp(`(?:^|;\\s*)${escapedName}=([^;]*)`);
const match = document.cookie.match(regex);
return match ? decodeURIComponent(match[1]) : null;
}
// 使用
const token = getCookie('auth_token');
if (token) console.log('已登入:', token);
const CookieUtil = {
/**
* 設定 Cookie
* @param {string} name
* @param {string} value
* @param {Object} options - { expires: number|Date, path: string, domain: string, secure: boolean, sameSite: 'Strict'|'Lax'|'None' }
*/
set(name, value, options = {}) {
const opts = {
path: '/',
sameSite: 'Lax',
...options
};
let cookieStr = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
if (opts.expires) {
const date = opts.expires instanceof Date ? opts.expires : new Date(Date.now() + opts.expires * 864e5);
cookieStr += `; expires=${date.toUTCString()}`;
}
if (opts.maxAge) cookieStr += `; max-age=${opts.maxAge}`;
if (opts.path) cookieStr += `; path=${opts.path}`;
if (opts.domain) cookieStr += `; domain=${opts.domain}`;
if (opts.secure) cookieStr += `; secure`;
if (opts.sameSite) cookieStr += `; samesite=${opts.sameSite}`;
document.cookie = cookieStr;
},
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;
},
remove(name, options = {}) {
// 設定過期時間為過去
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;
}
};
// 使用示例
CookieUtil.set('theme', 'dark', { expires: 365, sameSite: 'Strict' });
CookieUtil.set('session', 'abc123', { maxAge: 3600, secure: true }); // 1 小時,僅 HTTPS
console.log(CookieUtil.get('theme')); // 'dark'
CookieUtil.remove('session');
// 原文問題:
var cookieValue = cookie.substring(cookieName.length + 2, cookie.length);
// 1. 未 decodeURIComponent → 中文/特殊字符會亂碼
// 2. trim() 使用錯誤正則:/s 應為 \\s
// 3. 未處理名稱包含正則特殊字符的情況
// 4. 未處理同名 Cookie 不同 path/domain 的情況(瀏覽器自動處理,但邏輯上應注意)
// Chrome 87+ / Edge 87+ 支援(需 HTTPS)
if ('cookieStore' in window) {
// 異步、Promise-based
const cookie = await cookieStore.get('auth_token');
await cookieStore.set('theme', 'dark', { expires: Date.now() + 864e5 });
await cookieStore.delete('session');
// 監聽變化
cookieStore.addEventListener('change', e => {
console.log('Cookie 變更:', e.changed, e.deleted);
});
}
| 屬性 | 建議值 | 說明 |
|---|---|---|
| HttpOnly | 服務端設定 | 防 XSS 竊取,JS 無法讀取 |
| Secure | true (HTTPS) | 僅 HTTPS 傳輸 |
| SameSite | Lax / Strict | 防 CSRF;跨站需求用 None+Secure |
| Path | / 或具體路徑 | 最小權限原則 |
| Domain | 不設或父域 | 避免過度共享 |
Cookie 解析看似簡單,邊界情況極多。生產環境**直接使用封裝良好的工具函數**(如上 `CookieUtil`),並配合服務端設定 `HttpOnly`、`Secure`、`SameSite` 保障安全。現代專案逐步遷移至 **Cookie Store API** 或 **IndexedDB / localStorage** 減少 Cookie 依賴。