document.cookie 是瀏覽器提供的同步 API,讀取時回傳當前文檔**所有可存取 Cookie** 的字串 (以 ; 分隔);寫入時可設定單一 Cookie 的完整屬性。本文詳細解析讀寫格式、屬性選項、編碼規範、封裝工具類與安全最佳實踐。
// 回傳範例
"__gads=ID=xxx:T=123:S=yyy; ASPSESSIONID=ABC; _ga=GA1.2.xxx; theme=dark"
特點:
; (分號+空格) 分隔。function parseCookies(cookieStr = document.cookie) {
const cookies = {};
cookieStr.split('; ').forEach(pair => {
const idx = pair.indexOf('=');
if (idx > 0) {
const name = pair.slice(0, idx);
const value = pair.slice(idx + 1);
try {
cookies[name] = decodeURIComponent(value);
} catch {
cookies[name] = value; // 非標準編碼兜底
}
}
});
return cookies;
}
// 使用
const cookies = parseCookies();
console.log(cookies.theme); // "dark"
document.cookie =
`${encodeURIComponent(name)}=${encodeURIComponent(value)}` +
`; expires=${expiresDate.toUTCString()}` + // 過期時間 (GMT 字串)
`; path=${path}` + // 路徑,預設當前路徑
`; domain=${domain}` + // 域名,預設當前主機名 (不含子域)
`; secure` + // 僅 HTTPS 傳送
`; samesite=${sameSite}`; // Strict / Lax / None (需 Secure)
function setCookie(name, value, days = 7, options = {}) {
const { path = '/', domain, secure = true, sameSite = 'Lax' } = options;
const expires = new Date(Date.now() + days * 864e5).toUTCString();
let cookieStr = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; expires=${expires}; path=${path}`;
if (domain) cookieStr += `; domain=${domain}`;
if (secure) cookieStr += '; secure';
cookieStr += `; samesite=${sameSite}`;
document.cookie = cookieStr;
}
setCookie('user_token', 'abc123', 30, { domain: '.example.com', sameSite: 'None' });
function deleteCookie(name, options = {}) {
// 設定過期為過去時間,path/domain 必須與設定時一致
document.cookie = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${options.path || '/'}${options.domain ? '; domain=' + options.domain : ''}`;
}
class CookieStore {
static parse(str = document.cookie) {
const obj = {};
str.split('; ').forEach(p => {
const i = p.indexOf('=');
if (i > 0) obj[p.slice(0,i)] = decodeURIComponent(p.slice(i+1));
});
return obj;
}
static get(name) { return this.parse()[name]; }
static getAll() { return this.parse(); }
static set(name, value, opts = {}) {
const { days=365, path='/', domain, secure=true, sameSite='Lax' } = opts;
const exp = new Date(Date.now() + days*864e5).toUTCString();
let c = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; expires=${exp}; path=${path}`;
if (domain) c += `; domain=${domain}`;
if (secure) c += '; secure';
c += `; samesite=${sameSite}`;
document.cookie = c;
}
static remove(name, opts = {}) {
document.cookie = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${opts.path||'/'}${opts.domain?'; domain='+opts.domain:''}`;
}
static has(name) { return name in this.parse(); }
static keys() { return Object.keys(this.parse()); }
}
| 屬性 | 作用 | 建議設定 |
|---|---|---|
| HttpOnly | JS 無法讀取,防 XSS 竊取 | **敏感 Cookie (session, token) 必須開啟** (需後端 Set-Cookie 設定) |
| Secure | 僅 HTTPS 傳送 | 生產環境**必須開啟** |
| SameSite | 跨站請求攜帶策略 | Lax (預設,平衡體驗安全),Strict (高安全),None (跨站需求,必須配合 Secure) |
| Domain | 允許哪些主機名讀取 | 最小權限:.example.com 含子域,example.com 僅精確匹配 |
| Path | 允許哪些路徑讀取 | 通常 /,敏感功能可限制 /admin |
| Expires/Max-Age | 過期時間 | Session Cookie (無期限) 瀏覽器關閉即失效;持久化設定合理天數 |
encodeURIComponent / decodeURIComponent。path/domain 必須與建立時**完全一致**。domain=.example.com (帶點),子域頁面即可讀寫。localStorage / IndexedDB。document.cookie 是老牌但仍不可或缺的客戶端儲存機制。核心口訣:**讀時解析字串、寫時完整屬性、敏感資料 HttpOnly+Secure+SameSite、編碼不可忘、大小有上限**。封裝 CookieStore 類別統一管理,專案維護更安心。