只讀的 localStorage 容許你訪問一個 Document 的遠端(origin)對象 Storage;數據存儲爲跨瀏覽器會話。localStorage 相似於 sessionStorage,區別在於,數據存儲在 localStorage 是無期限的,而數據存儲在 sessionStorage 會被清除,當頁面會話結束時——也就是說當頁面被關閉。javascript
localStorage 內鍵值對的數量。html
localStorage.length // 0 localStorage.setItem('name', 'mazey') localStorage.length // 1
新增/更新 localStorage 的鍵值對。java
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}
獲取 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
移除 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
清空 localStorage 中全部鍵值對。session
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() 轉換成複雜值再使用。post
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 發生改變時,其它標籤作出相應的響應。code
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>