javascript存储数据有哪些方式_localStorage和sessionStorage怎么用

7次阅读

localStorage 和 sessionStorage 是轻量键值对存储,API 相同但生命周期不同:前者持久保存,后者关闭标签页即清空;存对象需 JSON.stringify 序列化,读取需 JSON.parse 解析并加 try-catch 防护。

javascript 存储数据有哪些方式_localStorage 和 sessionStorage 怎么用

JavaScript 存储数据主要有四种方式:cookielocalStoragesessionStorageIndexedDB。其中 localStoragesessionStorage 是最常用、最轻量的客户端 键值对 存储方案,适合存用户偏好、表单草稿、临时状态等非 敏感数据

怎么用 localStorage.setItemsessionStorage.setItem

两者 API 完全一致,核心就是四个方法:setItemgetItemremoveItemclear区别 只在生命周期——localStorage 持久保存(除非手动删),sessionStorage 关闭标签页即清空。

常见错误现象:

  • 直接存对象报错:localStorage.setItem('user', {name: 'Alice'}) → 实际存的是 [object Object],读出来无法还原
  • 没做 JSON.parse 就访问属性,报 Cannot read property 'name' of null

正确做法:

立即学习Java 免费学习笔记(深入)”;

const user = {name: 'Alice', age: 28}; // ✅ 序列化后存 localStorage.setItem('user', JSON.stringify(user)); // ✅ 读取时加 try-catch 防解析失败 try {const saved = JSON.parse(localStorage.getItem('user'));   console.log(saved.name); // Alice } catch (e) {console.error('localStorage 数据损坏或为空'); }

为什么不能直接存对象?JSON.stringify 有哪些坑

localStoragesessionStorage 只接受字符串作为值。任何非字符串类型(数字、布尔、对象、数组)都会被隐式转成字符串,导致信息丢失。

容易踩的坑:

  • undefinedfunctionSymbolDate 对象在 JSON.stringify 中被忽略或转成空对象
  • 循环引用对象会直接抛 TypeError: Converting circular structure to JSON
  • 存了 nullgetItem 返回 null,但 JSON.parse(null) 返回 null(不报错),容易漏判

建议写个安全封装:

function safeSet(key, value) {try {     localStorage.setItem(key, JSON.stringify(value));   } catch (e) {console.warn(`localStorage set ${key} failed:`, e);   } } function safeGet(key, fallback = null) {const raw = localStorage.getItem(key);   if (!raw) return fallback;   try {return JSON.parse(raw);   } catch (e) {console.warn(`localStorage parse ${key} failed:`, e);     return fallback;   } }

什么时候该用 localStorage,什么时候选 sessionStorage

选错会导致数据意外丢失或长期残留,影响用户体验和隐私合规。

典型场景对比:

  • localStorage:用户主题设置(深色 / 浅色)、语言偏好、城市选择、已读文章 ID 列表 —— 跨会话、跨页面复用,且不敏感
  • sessionStorage:多步表单的中间步骤、搜索筛选条件暂存、临时 token(如 OAuth 重定向中的一次性 code)、页面滚动位置(仅当前页有效)

特别注意:

  • 不要用 sessionStorage 存登录态(比如 token)并指望它“比 cookie 更安全”——它对 XSS 攻击完全不设防,且新开标签页就失效,反而破坏体验
  • localStorage 的数据在同源所有标签页共享,如果多个页面同时操作同一 key(如购物车数量),可能产生竞态;需要自己加逻辑同步或避免并发写

storage 事件监听只响应「其他标签页」的变更

这是最容易误解的一点:你在当前页面调用 localStorage.setItem,不会触发本页的 storage 事件。它只在同源的 ** 其他打开的标签页 ** 修改 storage 时才触发。

用途很明确:

  • 实现多标签页状态同步(比如 A 标签页切换主题,B 标签页自动更新 UI)
  • 登出广播(一个标签页登出,其他同源页收到事件后清空自身状态)

示例:

window.addEventListener('storage', (e) => {if (e.key === 'theme') {document.documentElement.setAttribute('data-theme', e.newValue || 'light');   } });

最后提醒:所有本地存储都受同源策略限制,https://a.comhttps://b.com 互不可见;也别存密码、银行卡号、JWT refresh token 这类敏感字段——它们对页面内任意脚本都是明文可读的。

text=ZqhQzanResources