經典 jQuery Cookie 插件核心源碼解析
// 簡化版核心邏輯
jQuery.cookie = function(name, value, options) {
// 設置模式
if (value !== undefined) {
options = options || {};
// value === null 表示刪除
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires === 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires === 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
var sameSite = options.sameSite ? '; SameSite=' + options.sameSite : ''; // 現代瀏覽器必需
document.cookie = [
encodeURIComponent(name), '=', encodeURIComponent(value),
expires, path, domain, secure, sameSite
].join('');
}
// 讀取模式
else {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
使用示例
// 1. 簡單設置(會話級,瀏覽器關閉失效)
$.cookie('user_pref', 'dark_mode');
// 2. 設置持久化 Cookie(7天,全站可用)
$.cookie('user_id', '12345', {
expires: 7,
path: '/',
domain: 'example.com',
secure: true, // 僅 HTTPS
sameSite: 'Lax' // CSRF 防護
});
// 3. 讀取
var uid = $.cookie('user_id'); // "12345" 或 undefined
// 4. 刪除
$.cookie('user_id', null); // 設置 expires=-1
// 5. 讀取原始值(不解碼)
var raw = document.cookie.split('; ').find(c => c.startsWith('user_id='));
現代替代:js-cookie(輕量、無依賴、TypeScript 支持)
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js"></script>
// 或 npm i js-cookie
// 使用(API 幾乎相同,但更規範)
Cookies.set('theme', 'dark', { expires: 365, sameSite: 'Lax' });
Cookies.get('theme'); // 'dark'
Cookies.getJSON('user'); // 自動 JSON.parse
Cookies.remove('theme', { path: '/' });
// 支持默認值
var lang = Cookies.get('lang') || 'zh-CN';
更現代:Web Storage (localStorage/sessionStorage)
| 特性 | Cookie | localStorage | sessionStorage |
| 容量 | 4KB | 5-10MB | 5-10MB |
| 過期 | 手動設置 | 永久(手動清除) | 標籤頁關閉清除 |
| 隨請求發送 | 是 | 否 | 否 |
| 同源策略 | Domain/Path 控制 | 嚴格同源 | 嚴格同源+標籤隔離 |
| API | 字串解析 | 鍵值對 API | 鍵值對 API |
統一存儲適配器模式
const Storage = {
// 自動選擇最佳存儲
_getStore() {
try {
localStorage.setItem('__test__', '1');
localStorage.removeItem('__test__');
return localStorage;
} catch (e) {
// 無痕模式/禁用 localStorage 降級到 Cookie
return {
getItem: k => Cookies.get(k),
setItem: (k, v) => Cookies.set(k, v, { expires: 365, path: '/' }),
removeItem: k => Cookies.remove(k, { path: '/' })
};
}
},
store: null,
init() {
this.store = this._getStore();
},
set(key, value, ttlDays) {
const data = { value, expiry: ttlDays ? Date.now() + ttlDays * 864e5 : null };
this.store.setItem(key, JSON.stringify(data));
},
get(key, defaultValue = null) {
try {
const item = this.store.getItem(key);
if (!item) return defaultValue;
const { value, expiry } = JSON.parse(item);
if (expiry && Date.now() > expiry) {
this.remove(key);
return defaultValue;
}
return value;
} catch (e) {
return defaultValue;
}
},
remove(key) {
this.store.removeItem(key);
},
clear() {
this.store.clear();
}
};
// 初始化
Storage.init();
// 使用
Storage.set('token', 'abc123', 30); // 30天過期
Storage.get('token'); // 'abc123'
安全最佳實踐
- HttpOnly Cookie: 敏感 Token 必須由服務端設置 HttpOnly,前端不可讀寫,防 XSS
- SameSite=Lax/Strict: 防禦 CSRF,現代瀏覽器默認 Lax
- Secure 標誌: 僅 HTTPS 傳輸
- 前端加密: localStorage 存敏感數據前用 AES-GCM 加密(Web Crypto API)
- 定期清理: 實現存儲配額監控與過期數據清理機制