與 sessionStorage 的區(qū)別
- sessionStorage 存儲(chǔ)的數(shù)據(jù)只在當(dāng)前窗口可以訪問(wèn),重現(xiàn)打開窗口不可用
- localStorage 數(shù)據(jù)可以永久存儲(chǔ),同源窗口可共享數(shù)據(jù);一般瀏覽器大小限制為 5M
localStorage 基本使用
- localStorage.setItem(key, value)
- localStorage.getItem(key)
使用 localStorage 的錯(cuò)誤處理
- 用戶禁用 localStorage,此時(shí)僅僅時(shí)訪問(wèn) localStorage 對(duì)象就會(huì)報(bào)錯(cuò)
// Assuming you’re not in global scope…
var localStorage;
try {
localStorage = window.localStorage;
} catch(e) {
// Access denied :-(
}
- 數(shù)據(jù)大小超出限制
try {
localStorage.setItem(key, value);
} catch(e) {
// 一些瀏覽器的錯(cuò)誤碼可能不同
if (e.code == 22) {
// Storage full, maybe notify user or do some clean-up
}
}
- 當(dāng)存儲(chǔ)的數(shù)據(jù)越多時(shí),
getItem()訪問(wèn)速度越慢
localStorage 的其他用法
同源窗口通信
根據(jù) localStorage 的特征,當(dāng)數(shù)據(jù)變動(dòng)時(shí)會(huì)觸發(fā) onmessage 事件,同源窗口可以監(jiān)聽事件來(lái)進(jìn)行通信;(參考已實(shí)現(xiàn)的開源項(xiàng)目: crosstab)將文件緩存在 localStorage 中
每次請(qǐng)求資源可以從 localStorage 中返回,會(huì)有 xss 風(fēng)險(xiǎn);(以實(shí)現(xiàn)的開源項(xiàng)目:basket.js)