萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Cookie 存取工具類:封裝、選項、安全屬性與現代 Cookie Store API

原生 document.cookie 痛點

  • 字串格式:`"name1=val1; name2=val2"` 需手動解析
  • 無法直接獲取/設置過期時間、域、路徑、SameSite
  • 寫入需手動拼接字串,易出錯

完整工具類(生產就緒)

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 不可見)
SecureHTTPS 站點必開僅 HTTPS 傳輸
SameSiteLax (默認) / Strict防 CSRF;跨站需求用 None+Secure
Path最小權限路徑避免洩露給無關路徑
Domain不設或父域避免過度共享
__Host- 前綴高安全 Cookie強制 Secure、Path=/、無 Domain
__Secure- 前綴高安全 Cookie強制 Secure

現代替代:Cookie Store API(Chrome 87+、Edge 87+、Firefox 109+)

// 異步、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();
}

遷移建議

  • 敏感數據:Token、Session ID → **HttpOnly Cookie**(服務端設置,JS 不可讀)
  • 客戶端狀態:主題、偏好設定 → `localStorage` / `IndexedDB`(更大容量、無自動發送)
  • 跨標籤頁同步:`BroadcastChannel` + `localStorage` 或 `cookieStore` 事件
  • 漸進增強:檢測 `cookieStore` 可用時優先使用,降級至 `document.cookie`

結語

Cookie 操作看似簡單,實則涉及編碼、安全屬性、跨域策略、過期計算等眾多細節。**封裝統一工具類**並嚴格遵循安全最佳實踐,是前端工程化的基本功。現代專案應逐步遷移至 **Cookie Store API** 或減少 Cookie 依賴,轉向 `localStorage`/`IndexedDB` + `HttpOnly Cookie` 分離架構。

copyright © 萬盛學電腦網 all rights reserved