HTML5 提供多種客戶端儲存機制,各有適用場景與容量限制。本文詳細比較 localStorage、sessionStorage、IndexedDB、Cache API、Cookie 的特性,並提供**儲存策略選型決策樹**與**封裝庫實作**,助你根據資料性質、生命週期、容量、查詢需求做出最佳選擇。
| 特性 | localStorage | sessionStorage | IndexedDB | Cache API | Cookie |
|---|---|---|---|---|---|
| 容量 | ~5-10 MB | ~5-10 MB | 數百 MB~GB (視瀏覽器/磁碟) | 數百 MB (配額共享) | 4 KB / 個, 總計 ~300 個/域 |
| 生命週期 | 永久 (手動清除或用戶清除快取) | 分頁關閉即銷毀 | 永久 (需手動清除) | 由 Service Worker 控制 | 由 Expires/Max-Age 控制 |
| 作用域 | 同源 (同協定/域名/埠) | 同源 + 同分頁 (標籤頁隔離) | 同源 | 同源 | 同源 + 路徑/域名可配置 |
| 資料型別 | 字串 (需自行 JSON 序列化) | 字串 | 任意結構化資料 (物件、Blob、File、ArrayBuffer) | Request/Response 物件 | 字串 |
| 查詢能力 | 鍵值獲取 (O(1)) | 鍵值獲取 | 索引、游標、範圍查詢、事務 | Request 匹配 | 無 (隨請求自動送出) |
| 同步/非同步 | 同步 (阻塞主執行緒) | 同步 | 非同步 (Promise/事件) | 非同步 | 同步 (隨請求) |
| 同步傳送至伺服器 | 否 | 否 | 否 | 否 | 是 (每請求自動攜帶) |
| 主要用途 | 偏好設定、Token、簡單快取 | 表單暫存、單頁流程狀態 | 大量結構化資料、離線資料庫、搜尋索引 | 離線快取、PWA 靜態資源 | 身份認證、追蹤、CSRF Token |
開始
│
├─ 需隨每請求自動送至伺服器? ──是──▶ Cookie (HttpOnly, Secure, SameSite)
│
├─ 資料 > 5 MB 或需索引/查詢/事務? ──是──▶ IndexedDB
│
├─ 需離線快取靜態資源 (HTML/JS/CSS/圖片)? ──是──▶ Cache API (Service Worker)
│
├─ 資料需跨分頁/瀏覽器重啟保留? ──是──▶ localStorage
│
└─ 僅單一分頁暫存、關閉即棄? ──────────▶ sessionStorage
/**
* StorageWrapper - 統一 localStorage/sessionStorage/IndexedDB 介面
* 功能:自動 JSON 序列化、過期時間 (TTL)、命名空間隔離、錯誤處理、TypeScript 型別支援
*/
class StorageWrapper {
/**
* @param {'local'|'session'} type
* @param {string} [namespace='app'] - 鍵值前綴,避免衝突
*/
constructor(type = 'local', namespace = 'app') {
this.store = type === 'local' ? localStorage : sessionStorage;
this.ns = namespace;
}
_key(key) { return `${this.ns}:${key}`; }
/** 設定值,可選 TTL (毫秒) */
set(key, value, ttl = 0) {
try {
const payload = { v: value, exp: ttl ? Date.now() + ttl : 0 };
this.store.setItem(this._key(key), JSON.stringify(payload));
return true;
} catch (e) {
console.error('Storage set failed:', e);
return false;
}
}
/** 取得值,自動檢查過期並清理 */
get(key, defaultValue = null) {
try {
const raw = this.store.getItem(this._key(key));
if (!raw) return defaultValue;
const { v, exp } = JSON.parse(raw);
if (exp && Date.now() > exp) {
this.remove(key);
return defaultValue;
}
return v;
} catch (e) {
console.error('Storage get failed:', e);
return defaultValue;
}
}
remove(key) { this.store.removeItem(this._key(key)); }
clear() { Object.keys(this.store).filter(k => k.startsWith(this.ns + ':')).forEach(k => this.store.removeItem(k)); }
keys() { return Object.keys(this.store).filter(k => k.startsWith(this.ns + ':')).map(k => k.slice(this.ns.length + 1)); }
length() { return this.keys().length; }
}
// IndexedDB 封裝 (簡易版,完整建議用 idb 库)
class IDBStore {
constructor(dbName = 'app-db', version = 1) {
this.dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(dbName, version);
req.onupgradeneeded = e => {
const db = e.target.result;
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async _txn(mode, fn) {
const db = await this.dbPromise;
return new Promise((resolve, reject) => {
const tx = db.transaction('kv', mode);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
fn(tx.objectStore('kv'));
});
}
async set(key, value) { await this._txn('readwrite', store => store.put(value, key)); }
async get(key) { return new Promise((resolve, reject) => { const req = (await this.dbPromise).transaction('kv').objectStore('kv').get(key); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); }
async delete(key) { await this._txn('readwrite', store => store.delete(key)); }
async clear() { await this._txn('readwrite', store => store.clear()); }
async keys() { return new Promise((resolve, reject) => { const req = (await this.dbPromise).transaction('kv').objectStore('kv').getAllKeys(); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); }
}
// 使用範例
const local = new StorageWrapper('local', 'myapp');
const session = new StorageWrapper('session', 'myapp');
const idb = new IDBStore('myapp-db');
local.set('token', 'abc123', 3600_000); // 1小時過期
local.set('prefs', { theme: 'dark', lang: 'zh-Hant' }, 30*24*3600_000); // 30天
session.set('formDraft', { name: 'John', email: 'john@example.com' });
console.log(local.get('token')); // 'abc123'
console.log(session.get('formDraft')); // { name: 'John', ... }
localStorage.setItem 拋出 QuotaExceededError 時,需捕獲並清理舊資料 (LRU) 或提示使用者。navigator.storage.estimate() (StorageManager API) 監控剩餘配額。// localStorage 變更會觸發其他分頁的 storage 事件
window.addEventListener('storage', e => {
if (e.key?.startsWith('myapp:')) {
console.log('其他分頁更新:', e.key, e.newValue);
// 同步狀態到當前分頁狀態管理
}
});
// 現代做法:BroadcastChannel (同源、同瀏覽器上下文)
const channel = new BroadcastChannel('myapp-sync');
channel.postMessage({ type: 'TOKEN_UPDATED', payload: newToken });
channel.onmessage = e => { /* 更新狀態 */ };
localStorage.setItem 會拋錯 (配額 0)。try { localStorage.setItem(...) } catch { /* 降級至記憶體 Map */ }。requestIdleCallback 低優先級寫入。JSON.stringify 耗時,考慮 MessagePack/Protocol Buffers 二進位格式。HTML5 Web Storage 家族為前端狀態管理提供了豐富選擇。**沒有銀彈,只有適合場景的工具**:localStorage 適合小型持久化設定,sessionStorage 適合單頁暫存,IndexedDB 是離線優先/大量資料的核心,Cache API 專司靜態資源離線。善用封裝庫統一介面、加入 TTL/命名空間/加密/跨分頁同步,能構建健壯、安全、高效能的客戶端儲存層。