萬盛學電腦網

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

JavaScript Cookie 操作封裝庫:設置、獲取、刪除的完整實現與最佳實踐

Cookie 操作三部曲:原生 API 的痛點

原生 document.cookie 既是讀取器也是寫入器,但功能極其基礎:

  • 寫入:只能單個設置 document.cookie = "k=v"
  • 讀取:返回所有 Cookie 字符串 "a=1; b=2; c=3",需手動解析
  • 刪除:無直接 API,需設置過期時間為過去
  • 無類型支持、無默認路徑/域管理

因此,封裝統一工具函數是每個前端項目的必修課。

完整封裝實現(生產級)

1. 設置 Cookie:setCookie

/**
 * 設置 Cookie
 * @param {string} name - 鍵名
 * @param {string} value - 值(自動 encodeURIComponent)
 * @param {Object} options - 配置選項
 *   @property {number} expires - 過期時間(小時),可傳 Date 對象
 *   @property {string} path - 路徑,默認 "/"
 *   @property {string} domain - 域名
 *   @property {boolean} secure - 僅 HTTPS
 *   @property {string} sameSite - 'Strict'|'Lax'|'None'
 */
function setCookie(name, value, options = {}) {
    var str = name + "=" + encodeURIComponent(value);
    
    // 過期時間處理:支持數字(小時)或 Date 對象
    if (options.expires !== undefined) {
        var date;
        if (typeof options.expires === "number") {
            date = new Date();
            date.setTime(date.getTime() + options.expires * 3600 * 1000);
        } else if (options.expires instanceof Date) {
            date = options.expires;
        }
        if (date) str += "; expires=" + date.toGMTString();
    }
    
    str += "; path=" + (options.path || "/");
    if (options.domain) str += "; domain=" + options.domain;
    if (options.secure) str += "; secure";
    if (options.sameSite) str += "; SameSite=" + options.sameSite;
    
    document.cookie = str;
    return true;
}

2. 獲取 Cookie:getCookie

/**
 * 獲取 Cookie 值
 * @param {string} name - 鍵名
 * @returns {string|null} 解碼後的值,不存在返回 null
 */
function getCookie(name) {
    var cookies = document.cookie.split("; ");
    for (var i = 0; i < cookies.length; i++) {
        var parts = cookies[i].split("=");
        // 注意:值中可能包含 =,所以只分割第一個
        var key = parts.shift();
        var val = parts.join("=");
        if (key === name) {
            return decodeURIComponent(val);
        }
    }
    return null;
}

3. 刪除 Cookie:deleteCookie

/**
 * 刪除 Cookie(設置過期時間為過去)
 * @param {string} name - 鍵名
 * @param {string} path - 必須與設置時相同
 * @param {string} domain - 必須與設置時相同
 */
function deleteCookie(name, path, domain) {
    // 先檢查是否存在,避免無謂寫入
    if (getCookie(name) !== null) {
        var opts = { expires: -1/3600 }; // 1秒前過期
        if (path) opts.path = path;
        if (domain) opts.domain = domain;
        setCookie(name, "", opts); // 值置空
        return true;
    }
    return false;
}

面向對象封裝:CookieManager 類

class CookieManager {
    constructor(defaultOptions = {}) {
        this.defaults = {
            path: "/",
            sameSite: "Lax",
            ...defaultOptions
        };
    }

    set(name, value, options = {}) {
        const opts = { ...this.defaults, ...options };
        let str = name + "=" + encodeURIComponent(value);
        
        if (opts.expires !== undefined) {
            const date = opts.expires instanceof Date ? opts.expires : 
                         (typeof opts.expires === 'number' ? new Date(Date.now() + opts.expires * 3600 * 1000) : null);
            if (date) str += "; expires=" + date.toGMTString();
        }
        
        str += "; path=" + opts.path;
        if (opts.domain) str += "; domain=" + opts.domain;
        if (opts.secure) str += "; secure";
        if (opts.sameSite) str += "; SameSite=" + opts.sameSite;
        
        document.cookie = str;
        return this; // 鏈式調用
    }

    get(name) {
        const cookies = document.cookie.split("; ");
        for (const cookie of cookies) {
            const [key, ...valParts] = cookie.split("=");
            if (key === name) return decodeURIComponent(valParts.join("="));
        }
        return null;
    }

    getAll() {
        const result = {};
        document.cookie.split("; ").forEach(cookie => {
            const [key, ...valParts] = cookie.split("=");
            result[key] = decodeURIComponent(valParts.join("="));
        });
        return result;
    }

    remove(name, path, domain) {
        if (this.get(name) !== null) {
            this.set(name, "", { 
                expires: new Date(0), 
                path: path || this.defaults.path, 
                domain: domain || this.defaults.domain 
            });
            return true;
        }
        return false;
    }

    has(name) {
        return this.get(name) !== null;
    }

    clearAll(path, domain) {
        const all = this.getAll();
        Object.keys(all).forEach(name => this.remove(name, path, domain));
    }
}

// 單例模式導出
const Cookie = new CookieManager({ path: "/", sameSite: "Lax" });

// 使用示例
Cookie.set("theme", "dark", { expires: 24*30 }); // 30天
Cookie.set("token", "abc123", { expires: 2, secure: true, sameSite: "Strict" }); // 2小時,僅 HTTPS
console.log(Cookie.get("theme")); // "dark"
console.log(Cookie.getAll()); // { theme: "dark", token: "abc123" }
Cookie.remove("token");
Cookie.clearAll(); // 清空當前域所有 Cookie

實戰應用場景

場景一:記住登錄狀態(30天免登)

function login(username, password, rememberMe) {
    return api.login(username, password).then(res => {
        if (res.token) {
            Cookie.set("auth_token", res.token, { 
                expires: rememberMe ? 24*30 : 2, // 記住我:30天,否則2小時
                secure: true, 
                sameSite: "Lax"
            });
            Cookie.set("username", username, { expires: 24*30 });
        }
    });
}

// 頁面初始化檢查
if (Cookie.has("auth_token")) {
    autoLogin(Cookie.get("auth_token"));
}

場景二:用戶偏好持久化(主題、語言)

// 設置
function setTheme(theme) {
    document.body.className = "theme-" + theme;
    Cookie.set("user_theme", theme, { expires: 24*365 }); // 1年
}

// 讀取並應用
var savedTheme = Cookie.get("user_theme") || "light";
setTheme(savedTheme);

場景三:購物車臨時存儲(會話級)

// 不設置 expires,關閉瀏覽器自動失效
function addToCart(product) {
    var cart = JSON.parse(Cookie.get("cart") || "[]");
    cart.push(product);
    Cookie.set("cart", JSON.stringify(cart)); // 會話級 Cookie
}

調試技巧:開發者工具查看 Cookie

  1. Chrome DevTools → Application → Cookies → 域名
  2. Console 輸入 document.cookie 查看原始字符串
  3. 編輯/刪除單個 Cookie 測試邏輯
  4. Network 面板查看請求頭 Cookie: 與響應頭 Set-Cookie:

常見坑與避坑指南

坑現象原因解決
路徑不匹配設置了但讀不到寫入 path=/a,讀取時在 /b統一 path=/ 或精確匹配
域不匹配子域無法讀取主域 Cookie未設置 domain=.example.com顯式設置 domain,注意公共後綴列表
Secure 標記HTTP 頁面寫入失敗secure 僅 HTTPS 生效本地開發用 lvh.me 或 mkcert 配置 HTTPS
SameSite=None 無 Secure瀏覽器拒絕設置SameSite=None 必須配合 Secure同時設置 secure: true
中文亂碼讀取出亂碼未 encodeURIComponent寫入編碼、讀取解碼

總結

Cookie 操作看似簡單,實則細節決定成敗。封裝健壯的 CookieManager 類,統一處理編碼、過期時間格式化、路徑域默認值、SameSite/Secure 等現代屬性,並提供鏈式調用、批量操作、類型安全接口,能極大提升開發效率並減少 Bug。現代項目中,配合 localStorage/sessionStorage 分層存儲策略:Cookie 存服務端必須讀取的少量標識(Token、SessionID),localStorage 存大量客戶端狀態,sessionStorage 存臨時會話數據。

copyright © 萬盛學電腦網 all rights reserved