localStorage 和 sessionStorage 的核心区别在于生命周期和作用域:前者持久保存、同源共享,后者仅限当前标签页、关闭即清空;二者均只支持字符串存储,存对象需 JSON 序列化,读取需反序列化。

localStorage 和 sessionStorage 的核心区别在哪
两者都只能存字符串,但生命周期和作用域完全不同:localStorage 持久保存,关浏览器也不丢;sessionStorage 仅限当前标签页,关掉就清空,且不同标签页互不共享。
别指望它们能存对象或数组——直接赋值会自动调用 toString(),结果变成 [object Object]。必须手动序列化:
localStorage.setItem('user', JSON.stringify({name: 'Alice', age: 30}))const user = JSON.parse(localStorage.getItem('user'))
没做 JSON.parse() 就直接用,大概率遇到 TypeError: Cannot read property 'xxx' of null。
setItem / getItem / removeItem 这三个方法怎么安全使用
setItem 会静默失败:当存储超出配额(通常 5–10MB)或浏览器禁用时,不报错也不提示,只丢数据。务必加 try-catch:
立即学习“Java免费学习笔记(深入)”;
try {
localStorage.setItem('theme', 'dark');
} catch (e) {
console.warn('localStorage write failed:', e.name); // 常见 e.name 是 'QuotaExceededError'
}
getItem 找不到键时返回 null,不是 undefined,所以 if (localStorage.getItem('token')) 要小心——空字符串、'null' 字符串也会进 if 分支。
removeItem 删除不存在的键不会报错,可以放心调用;但想清空全部,请用 localStorage.clear(),别循环删——性能差还可能触发 StorageEvent 频繁广播。
监听 storage 变化为什么页面里收不到事件
storage 事件只在「其他同源窗口」修改了存储时才触发,**当前窗口自己改的不会触发**。这是最容易踩的坑。
比如你在控制台执行 localStorage.setItem('count', '5'),当前页面的 window.addEventListener('storage', handler) 根本不会执行。
验证方式:开两个同源页面(如两个 localhost:3000/tab1 和 tab2),在 tab1 里改,tab2 才能收到事件。事件对象里有 key、oldValue、newValue、url 等字段,但注意 newValue 在删除时为 null,不是空字符串。
兼容性和特殊场景要注意什么
IE8+ 支持 localStorage,但 IE9 的隐私模式下会抛 SecurityError;Safari 在无痕模式默认禁用,setItem 直接失败;部分安卓 WebView 对大小限制更严。
服务端渲染(SSR)环境没有 window,直接访问 localStorage 会报 ReferenceError: localStorage is not defined。得先判断:
if (typeof window !== 'undefined') {
localStorage.setItem('pref', 'high');
}
另外,sessionStorage 在页面刷新后保留,但导航到新页面(包括 location.href = '...')仍存在;只有关闭标签页、前进/后退离开当前 session history entry,才会销毁。











