localStorage

與 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 的其他用法

  1. 同源窗口通信
    根據(jù) localStorage 的特征,當(dāng)數(shù)據(jù)變動(dòng)時(shí)會(huì)觸發(fā) onmessage 事件,同源窗口可以監(jiān)聽事件來(lái)進(jìn)行通信;(參考已實(shí)現(xiàn)的開源項(xiàng)目: crosstab

  2. 將文件緩存在 localStorage 中
    每次請(qǐng)求資源可以從 localStorage 中返回,會(huì)有 xss 風(fēng)險(xiǎn);(以實(shí)現(xiàn)的開源項(xiàng)目:basket.js)

參考

localStorage 還能這么用

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容