Cookie 4KB 限制、隨請求自動發送、汙染 HTTP 流量,移動端項目中已不再適合作為業務數據存儲。LocalStorage(~5MB、不隨請求發送、持久化)成為首選,但需妥善處理容量、隱私模式、性能、過期、爬蟲不可讀等坑點。
| 方法/屬性 | 說明 |
|---|---|
localStorage.setItem(key, value) | 存儲字符串鍵值對 |
localStorage.getItem(key) | 讀取值,不存在返回 null |
localStorage.removeItem(key) | 刪除指定鍵 |
localStorage.clear() | 清空當前域下所有數據 |
localStorage.key(index) | 獲取指定索引的鍵名 |
localStorage.length | 鍵值對數量 |
注意:只能存字符串,物件需 JSON.stringify/parse。
sessionStorage:會話級,標籤頁關閉即銷毀,適合臨時表單、單次流程狀態。localStorage:持久級,跨會話保留,適合用戶偏好、緩存數據、Token 等。expireTime,讀取時自動清理過期項。clear()。SYSTEM_KEY_TIMEOUT_MAP 映射表,避免遍歷全庫檢查過期。QuotaExceededError,執行淘汰後重試。sign 區分緩存版本。{value, inDate, timeout, sign}define([], function () {
var Storage = _.inherit({
propertys: function () {
this.sProxy = window.localStorage;
this.defaultLifeTime = 2592000000; // 30天
this.keyCache = 'SYSTEM_KEY_TIMEOUT_MAP';
this.removeNum = 5;
},
set: function (key, value, timeout, sign) {
var entity = this.buildStorageObj(value, Date.now(), timeout || Date.now()+this.defaultLifeTime, sign);
try {
this.sProxy.setItem(key, JSON.stringify(entity));
this.setKeyCache(key, entity.timeout);
return true;
} catch (e) {
if (e.name === 'QuotaExceededError') {
if (!this.removeLastCache()) throw '存儲量過大';
return this.set(key, value, timeout, sign); // 遞歸重試
}
return false;
}
},
removeOverdueCache: function () { /* 遍歷 keyCache 清理過期 */ },
removeLastCache: function () { /* 按 timeout 排序刪除 removeNum 條 */ },
// ... get、buildStorageObj、setKeyCache 等輔助方法
});
return new Storage();
});
| 場景 | 存儲策略 | 過期/更新 |
|---|---|---|
| 搜索頁出發/到達城市 | localStorage,Key 固定 | 用戶主動修改時更新,長期保留 |
| 城市列表數據(大數據) | localStorage,分頁/分字母存儲 | 服務端推送版本號,版本變更時標記過期 |
| 用戶 Token/登錄態 | localStorage + 內存雙寫 | 登出/過期時清除,攔截器統一處理 |
| 表單草稿 | sessionStorage | 提交成功清除,關閉標籤自動銷毀 |
localStorage 讀寫拋異常 → try-catch 降級內存存儲。jd_mall_city_list)。