萬盛學電腦網

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

JavaScript 精確獲取指定 Cookie 的工具函數與最佳實踐

核心難點

`document.cookie` 返回**所有 Cookie 的單一字串**(以 `; ` 分隔),且**無法直接按名稱索引**。需手動解析,注意:

  • Cookie 名稱可能包含特殊字符(需 `encodeURIComponent` 存、對應 `decodeURIComponent` 取)
  • 值可能包含 `=`、`;`,不能簡單 `split('=')`
  • 大小寫敏感、路徑/域作用域隔離

健壯的獲取函數(現代寫法)

/**
 * 獲取指定名稱的 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);

完整 Cookie 工具類

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 的情況(瀏覽器自動處理,但邏輯上應注意)

現代替代:Cookie Store API(實驗階段)

// 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 無法讀取
Securetrue (HTTPS)僅 HTTPS 傳輸
SameSiteLax / Strict防 CSRF;跨站需求用 None+Secure
Path/ 或具體路徑最小權限原則
Domain不設或父域避免過度共享

結語

Cookie 解析看似簡單,邊界情況極多。生產環境**直接使用封裝良好的工具函數**(如上 `CookieUtil`),並配合服務端設定 `HttpOnly`、`Secure`、`SameSite` 保障安全。現代專案逐步遷移至 **Cookie Store API** 或 **IndexedDB / localStorage** 減少 Cookie 依賴。

copyright © 萬盛學電腦網 all rights reserved