原生 document.cookie 既是讀取器也是寫入器,但功能極其基礎:
document.cookie = "k=v""a=1; b=2; c=3",需手動解析因此,封裝統一工具函數是每個前端項目的必修課。
/**
* 設置 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;
}
/**
* 獲取 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;
}
/**
* 刪除 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;
}
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
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
}
document.cookie 查看原始字符串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 存臨時會話數據。