localStorage 提供簡單的鍵值持久化儲存 (同源、同瀏覽器),容量約 5MB,不隨 HTTP 請求發送。本文深入解析特性、與 sessionStorage/cookie 差異、序列化策略、配額管理、隱私模式限制與生產級封裝庫設計。
| 特性 | localStorage | sessionStorage | Cookie |
|---|---|---|---|
| 生命週期 | 永久 (手動清除/清除瀏覽資料才消失) | 分頁/視窗關閉即銷毀 | 可設定 Expires/Max-Age |
| 容量 | ~5 MB (各瀏覽器略異) | ~5 MB | 4 KB / 個,每域 ~300 個 |
| 網路傳輸 | **從不**隨請求發送 | 不發送 | **每請求自動攜帶** |
| 同源策略 | 嚴格 (scheme+host+port) | 嚴格 + 同分頁 | 可設 Domain/Path 放寬 |
| 資料型別 | 字串 (需自行序列化) | 字串 | 字串 |
| 事件通知 | storage 事件 (跨分頁同步) | 無 | 無 |
localStorage.setItem('key', 'value');
const val = localStorage.getItem('key'); // null 若不存在
localStorage.removeItem('key');
localStorage.clear(); // 清空該源所有鍵
const len = localStorage.length;
const key = localStorage.key(index); // 遍歷用
// 通用 JSON 封裝
const Storage = {
set(key, value) {
try { localStorage.setItem(key, JSON.stringify(value)); }
catch (e) { if (e.name === 'QuotaExceededError') handleQuota(); }
},
get(key, defaultValue = null) {
const raw = localStorage.getItem(key);
if (raw === null) return defaultValue;
try { return JSON.parse(raw); }
catch { return defaultValue; } // 防禦性:損壞資料回預設
},
remove(key) { localStorage.removeItem(key); },
clear() { localStorage.clear(); }
};
// 使用
Storage.set('user', { id: 1, name: 'Alice', tags: ['vip','beta'] });
const user = Storage.get('user', { id: 0, name: 'Guest', tags: [] });
QuotaExceededError (Safari 私有模式下寫入也會拋出)。navigator.storage.estimate() (Storage API) 查詢剩餘配額。try { localStorage.setItem('test','1'); localStorage.removeItem('test'); } catch { /* 降級 */ } 偵測可用性。window.addEventListener('storage', e => {
if (e.key === 'auth_token' && e.newValue !== e.oldValue) {
// 另一分頁更新了 token,當前分頁同步刷新狀態
authStore.updateToken(e.newValue);
}
});
注意:storage 事件**不在發出分頁觸發**,僅在其他同源分頁觸發。
interface StorageOptions {
prefix?: string; // 鍵名前綴避免衝突
serializer?: (v: any) => string;
deserializer?: (s: string) => any;
ttl?: number; // 毫秒,過期自動失效
encrypt?: (s: string) => string; // 可選加密
decrypt?: (s: string) => string;
}
function createStorage(localStorage: Storage, opts: StorageOptions = {}) {
const { prefix = '', serializer = JSON.stringify, deserializer = JSON.parse, ttl, encrypt, decrypt } = opts;
const now = () => Date.now();
return {
set(key: string, value: any) {
const payload = { value, timestamp: now() };
let data = serializer(payload);
if (encrypt) data = encrypt(data);
localStorage.setItem(prefix + key, data);
},
get(key: string) {
const raw = localStorage.getItem(prefix + key);
if (!raw) return null;
let data = decrypt ? decrypt(raw) : raw;
try {
const { value, timestamp } = deserializer(data);
if (ttl && now() - timestamp > ttl) { this.remove(key); return null; }
return value;
} catch { return null; }
},
remove(key) { localStorage.removeItem(prefix + key); },
clear() { /* 只清除帶 prefix 的鍵 */ },
keys() { /* 遍歷並過濾 prefix */ }
};
}
// 使用
const appStore = createStorage(localStorage, { prefix: 'myapp:', ttl: 7*24*3600*1000 });
appStore.set('session', { token: 'abc', expires: Date.now()+3600*1000 });
localStorage.setItem('k', {a:1}) → 變成 "[object Object]"。QuotaExceededError 導致靜默失敗。LocalStorage 適合「小量、非關鍵、需跨分頁同步」的持久化場景;複雜查詢、大資料、離線優先請改用 IndexedDB / OPFS / SQLite (WASM)。