LocalStorage 解決了 Cookie 4KB 容量限制、隨請求發送浪費頻寬、IE6 20 個/域名限制等痛點,提供 5MB 純客戶端持久化鍵值存儲,是現代 Web 應用離線緩存、狀態保持、跨標籤頁通信的基石。
| 特性 | Cookie | userData (IE) | Flash SharedObject | Google Gears | LocalStorage |
|---|---|---|---|---|---|
| 容量 | ~4KB | 64KB | 100KB+ | 無限制 | 5MB/域(主流瀏覽器統一) |
| 隨請求發送 | 是 | 否 | 否 | 否 | 否 |
| 跨瀏覽器 | ✅ | ❌ | 需外掛 | 需外掛 | ✅ (IE8+) |
| API 易用性 | 文檔操作 | XML 操作 | AS3 API | SQL-like | 鍵值對,極簡 |
// 存儲/更新
localStorage.setItem(key, value) // 僅支援字符串
localStorage[key] = value // 等價寫法
// 讀取
localStorage.getItem(key)
localStorage[key]
// 刪除
localStorage.removeItem(key)
// 清空
localStorage.clear()
// 枚舉
localStorage.length // 鍵值對數量
localStorage.key(index) // 獲取第 index 個鍵名
// 事件監聽(跨標籤頁同步)
window.addEventListener('storage', e => {
// e.key, e.oldValue, e.newValue, e.url, e.storageArea
console.log(`${e.key} 從 ${e.oldValue} 變為 ${e.newValue}`);
});
| 陷阱 | 現象 | 對策 |
|---|---|---|
| 只能存字符串 | 物件/陣列直接存會變 "[object Object]" | JSON.stringify() 存,JSON.parse() 取 |
| iOS Safari 隱私模式 | setItem 拋 QUOTA_EXCEEDED_ERR | 先 removeItem 再 setItem,或 try-catch 降級 |
| 同步阻塞主線程 | 大量寫入導致卡頓 | 分批寫入、Web Worker + IndexedDB |
| 無過期機制 | 數據永久駐留 | 自帶 timestamp 字段,讀取時檢查過期自動清理 |
| storage 事件不觸發 | 同頁面修改不觸發、IE/Firefox 事件對象屬性不全 | 僅用於跨標籤頁同步,同頁用自定義事件 |
<button id="btn">刷新計數</button>
<span id="count">0</span>
<script>
const countEl = document.getElementById('count');
const btn = document.getElementById('btn');
let count = parseInt(localStorage.getItem('pageViews') || '0', 10);
countEl.textContent = count;
btn.addEventListener('click', () => {
count++;
localStorage.setItem('pageViews', count.toString());
countEl.textContent = count;
});
// 跨標籤頁同步演示
window.addEventListener('storage', e => {
if (e.key === 'pageViews') {
count = parseInt(e.newValue, 10);
countEl.textContent = count;
}
});
</script>
// 存儲
const user = { id: 1, name: '張三', tags: ['vip', 'beta'] };
localStorage.setItem('currentUser', JSON.stringify(user));
// 讀取
const saved = localStorage.getItem('currentUser');
const user = saved ? JSON.parse(saved) : null;
// 注意:IE8 支援 JSON 但若強制 IE7 模式 () 則失效
LocalStorage 適合:用戶偏好、簡單狀態、Token、小型緩存、跨標籤頁信號同步。