浏览器存储:Cookie / localStorage / indexDB
Cookie:随每次请求自动携带,容量小(约 4KB),有域名 / 路径 / 过期 / httpOnly / SameSite 属性,适合存身份凭证(sessionId 时代)与少量状态。localStorage:容量 5~10MB,持久存储(不主动删就一直在),同源共享,API 同步简单;适合存主题、用户偏好等非敏感状态。
sessionStorage 与 localStorage 唯一区别是“标签页会话级”关闭即清。indexDB 是浏览器里的 NoSQL 数据库:容量大(数百 MB+)、异步 API、支持事务与索引,适合离线应用(PWA)与大量结构化数据。选型一句话:凭证用 Cookie(httpOnly),偏好用 localStorage,临时态用 sessionStorage,大数据用 indexDB。
- Cookie:4KB、随请求走、httpOnly 防 JS 读取,放身份凭证
- localStorage 持久 / sessionStorage 会话级,同源共享、同步 API
- indexDB:大容量异步 NoSQL,适合离线应用与大量数据
JS
// 三种存储 API 对比 localStorage.setItem('theme', 'dark'); // 持久,关浏览器还在 sessionStorage.setItem('draft', '正在编辑'); // 关标签页即清 console.log(localStorage.getItem('theme')); // dark // Cookie:服务端下发,JS 可读写(除非 httpOnly) document.cookie = 'pref=zh; max-age=3600; path=/'; console.log('cookie:', document.cookie); // 只能拿到非 httpOnly 的 // 存储事件:同源多标签页通信(localStorage 变化会广播) window.addEventListener('storage', e => { console.log('别的标签页改了', e.key, '→', e.newValue); }); // indexDB 极简封装(异步、事务) function openDB(name, version) { return new Promise((res, rej) => { const req = indexedDB.open(name, version); req.onupgradeneeded = () => req.result.createObjectStore('todos', { keyPath: 'id' }); req.onsuccess = () => res(req.result); req.onerror = () => rej(req.error); }); } openDB('app', 1).then(db => { const tx = db.transaction('todos', 'readwrite'); tx.objectStore('todos').put({ id: 1, text: '面试复习' }); tx.oncomplete = () => console.log('indexDB 写入完成'); });
本节要点选型口诀:凭证 Cookie(httpOnly)、偏好 localStorage、临时 sessionStorage、大数据 indexDB。




