H5 localStorage入門

定義

只讀的 localStorage 允許你訪問一個 Document 的遠端(origin)對象 Storage;數據存儲爲跨瀏覽器會話。localStorage 類似於 sessionStorage,區別在於,數據存儲在 localStorage 是無期限的,而數據存儲在 sessionStorage 會被清除,當頁面會話結束時——也就是說當頁面被關閉。

屬性

length

localStorage 內鍵值對的數量。

localStorage.length // 0
localStorage.setItem('name', 'mazey')
localStorage.length // 1

方法

1.setItem(key, value)

新增/更新 localStorage 的鍵值對。

localStorage.setItem('name', 'mazey')
localStorage.setItem('age', '23')
localStorage // Storage {age: "23", name: "mazey", length: 2}

等同於:

localStorage.name = 'mazey'
localStorage.age = '23'
localStorage // Storage {age: "23", name: "mazey", length: 2}

2.getItem(key)

獲取 localStorage 中指定鍵的值。

localStorage.setItem('name', 'mazey')
localStorage.setItem('age', '23')
localStorage.getItem('name') // mazey
localStorage.getItem('age') // 23
localStorage.getItem('sex') // null

等同於:

localStorage.setItem('name', 'mazey')
localStorage.setItem('age', '23')
localStorage.name // mazey
localStorage['age'] // 23
localStorage.sex // undefined

3.removeItem(key)

移除 localStorage 中指定鍵的鍵值對。

localStorage.setItem('name', 'mazey')
localStorage.setItem('age', '23')
localStorage // Storage {age: "23", name: "mazey", length: 2}
localStorage.removeItem('age') // undefined
localStorage // {name: "mazey", length: 1}
localStorage.removeItem('age') // undefined

4.clear()

清空 localStorage 中所有鍵值對。

localStorage.setItem('name', 'mazey')
localStorage.setItem('age', '23')
localStorage // Storage {age: "23", name: "mazey", length: 2}
localStorage.clear()
localStorage // Storage {length: 0}

存取對象(複雜值)

localStorage 只能存字符串,所以數組/對象等複雜值要先用 JSON.stringify() 轉換成字符串,取出來時再用 JSON.parse() 轉換成複雜值再使用。

let arr = [1, 2, 3]
localStorage.setItem('arr', arr)
localStorage.getItem('arr') // "1,2,3"
// JSON.stringify()
localStorage.setItem('arr', JSON.stringify(arr))
localStorage.getItem('arr') // "[1,2,3]"
JSON.parse(localStorage.getItem('arr')) // [1, 2, 3]

瀏覽器標籤之前通信

讓 window 監聽 localStorage 的 storage,一個標籤的 localStorage 發生改變時,其它標籤做出相應的響應。

test0.html - 改變 localStorage。

<input type="text" id="input" />
<button onclick="setNameForStorage()">Set</button>
<script type="text/javascript">
    function setNameForStorage () {
        localStorage.name = document.querySelector('#input').value
    }
</script>

test1.html - 響應 localStorage 的改變。

<script type="text/javascript">
    window.addEventListener('storage', e => {
        console.log(e.key, e.newValue) // name 123
    })
</script>

注意

  1. localStorage 只能同域名下使用,可以搭配 postMessage 和 iframe 實現跨域通信。
  2. 低版本IE不支持 localStorage。
  3. 需在服務器環境下使用,即不能在 file:// 等非正常環境下使用。
  4. 在移動端 localStorage(H5, IOS, Android)會發生不可預知的問題。

其它

Please Stop Using Local Storage

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章