主题
Web Storage
概述
Web Storage 是一种在用户浏览器中存储数据的机制,主要包括 localStorage 和 sessionStorage。
共同点(Web Storage)
localStorage与sessionStorage,方法相同:setItem(key, value)getItem(key)removeItem(key)clear()key(index)length
- 存储类型:仅保存字符串,复杂对象需
JSON.stringify/JSON.parse。 - 访问范围:同源(协议、主机、端口相同)下的页面可访问。
- 同步 API:读写为同步操作,可能阻塞主线程,尽量避免频繁大数据读写。
LocalStorage(持久化)
- 生命周期:永久(除非被显式清除或用户/浏览器清理),浏览器或标签关闭不会删除。
- 作用域:同源全局可见,跨标签/窗口共享(同源下)。
- 限制:通常每域约 5MB(浏览器差异),写入超限会抛出
QuotaExceededError。
示例:
js
// 存储对象
localStorage.setItem('prefs', JSON.stringify({ theme: 'dark' }))
const prefs = JSON.parse(localStorage.getItem('prefs') || '{}')
// 删除
localStorage.removeItem('prefs')SessionStorage(会话级)
- 生命周期:与标签页/窗口会话绑定,同一窗口的刷新不会清除,但关闭标签页/窗口即清除。
- 作用域:同源且同一顶层浏览器上下文(标签/窗口)可见,不会在同源的其他标签共享。
示例:
js
sessionStorage.setItem('draft', JSON.stringify({ text: 'hello' }))
const draft = JSON.parse(sessionStorage.getItem('draft') || 'null')跨标签/窗口同步(storage 事件)
- 当同源的其他窗口/标签修改
localStorage(或sessionStorage在同一顶层上下文下),会触发storage事件:
js
window.addEventListener('storage', (e) => {
// e.key, e.oldValue, e.newValue, e.url
console.log('storage changed', e.key, e.newValue)
})- 注意:触发方的窗口不会接收到该事件,只有其他窗口会。
