萬盛學電腦網

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

JavaScript Cookie 完整操作指南:設置、讀取、刪除與封裝

Cookie 是客戶端持久化存儲的經典方案。本文整理完整的 Cookie 操作封裝,涵蓋會話級、固定過期、自定義過期三種設置模式,並提供統一的讀取、刪除工具函數。

封裝對象:CookieUtil

var CookieUtil = {
  // 設置 Cookie
  set: function(name, value, expires, path, domain, secure) {
    var cookieText = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    
    if (expires instanceof Date) {
      cookieText += '; expires=' + expires.toGMTString();
    } else if (typeof expires === 'number') {
      // 支持傳入天數
      var date = new Date();
      date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);
      cookieText += '; expires=' + date.toGMTString();
    } else if (typeof expires === 'string') {
      // 支持 "30d", "12h", "20m" 格式
      var match = expires.match(/^(\d+)([dhms])$/);
      if (match) {
        var val = parseInt(match[1], 10);
        var unit = match[2];
        var ms = { d: 86400000, h: 3600000, m: 60000, s: 1000 }[unit];
        var date = new Date(Date.now() + val * ms);
        cookieText += '; expires=' + date.toGMTString();
      }
    }
    
    if (path) cookieText += '; path=' + path;
    if (domain) cookieText += '; domain=' + domain;
    if (secure) cookieText += '; secure';
    
    document.cookie = cookieText;
  },
  
  // 讀取 Cookie
  get: function(name) {
    var cookieName = encodeURIComponent(name) + '=';
    var cookieStart = document.cookie.indexOf(cookieName);
    var cookieValue = null;
    
    if (cookieStart > -1) {
      var cookieEnd = document.cookie.indexOf(';', cookieStart);
      if (cookieEnd === -1) cookieEnd = document.cookie.length;
      cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
    }
    return cookieValue;
  },
  
  // 刪除 Cookie
  remove: function(name, path, domain, secure) {
    this.set(name, '', new Date(0), path, domain, secure);
  }
};

使用示例

// 會話級 Cookie(瀏覽器關閉失效)
CookieUtil.set('session_id', 'abc123');

// 30 天過期
CookieUtil.set('remember_me', 'true', 30);

// 自定義過期:2小時
CookieUtil.set('temp_token', 'xyz', '2h');

// 讀取
var token = CookieUtil.get('temp_token');

// 刪除
CookieUtil.remove('remember_me');

最佳實踐提醒

  • 敏感數據勿存入 Cookie,應使用 HttpOnly、Secure 標志並配合 HTTPS。
  • 單個 Cookie 不超過 4KB,總數每域名約 20-50 個。
  • 現代項目優先考慮 localStorage/sessionStorage 或 IndexedDB。
copyright © 萬盛學電腦網 all rights reserved