Cookie是HTTP协议层的请求头机制,受大小、同源、HttpOnly等强约束;localStorage适合存小量非敏感UI状态,无过期机制且阻塞主线程;IndexedDB是唯一支持离线、结构化、大量数据的异步事务型数据库。JavaScript 本地存储不是“选一个就好”,而是得看你要存什么、存多久、谁来读、要不要跨域同步。Cookie、
localStorage 和 IndexedDB 根本不是同一类工具,硬比容量或 API 简洁度会踩坑。
很多人误以为 document.cookie 是“前端自己存数据的地方”,其实它只是浏览器自动在每次 HTTP 请求中帮你在请求头塞上 Cookie 字段——服务端能读、能写、能删,前端只能拼字符串操作,且受大小(通常 ≤4KB)、同源、HttpOnly、Secure 等策略强约束。
document.cookie = "user=abc; expires=Fri, 31 Dec 9999 23:59:59 GMT" 安全地存敏感 token——只要没设 HttpOnly,JS 就能被 XSS 直接盗走max-age 和 expires 都要手动算时间戳,漏写就变会话级 Cookie,关浏览器就丢JSON.stringify + encodeURIComponent
localStorage 是纯前端同步 API,最大约 5–10MB(各浏览器不同),但它是阻塞主线程的——localStorage.setItem("theme", "dark") 看似简单,如果刚写完又立刻 getItem,在某些低配安卓 WebView 里可能读不到最新值(因写入未落盘完成)。
https://a.com 和 https://b.com 的 localStorage 完全隔离removeItem 或用户清缓存theme,页面 B 不会自动知道,得靠 storage 事件 + 同源 iframe 或广播配合undefined、Symbol,JSON.stringify({x: undefined}) 会直接丢掉 x 字段IndexedDB 是异步、事务型、键值+索引的数据库,适合存用户离线日志、缓存 API 响应、甚至小型文档编辑器的内容快照。但它不是“localStorage 加个索引”——它的打开、读写、升级版本都必须走回调或 Promise 链,出错不抛异常,只触发 error 事件。
indexedDB.open("mydb", 1) 会触发 upgradeneeded,必须在里面建 objectStore,否则后续所有操作都会失败transaction.objectStore("logs").add(...) 就不能再用autoIncrement: true),也可以是对象里的某个字段(keyPa
th: "id"),但二者不能共存cursor 遍历比用 getAll 更省内存,尤其数据量 >1000 条时;getAll 会一次性把所有匹配记录加载进内存const request = indexedDB.open("notes", 2);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains("items")) {
db.createObjectStore("items", { keyPath: "id" });
}
};
request.onsuccess = (event) => {
const db = event.target.result;
const tx = db.transaction("items", "readwrite");
const store = tx.objectStore("items");
store.put({ id: 1, title: "Hello", content: "World" });
};
JWT 存 localStorage 是常见错误——它不会自动过期,无法被服务端主动吊销,XSS 一打就穿。正确做法是:登录后由后端 set-cookie(带 HttpOnly + Secure),前端只管发起请求,让浏览器自动带;需要前端读的部分(如用户昵称)另走轻量接口或放 sessionStorage。
反过来,用 IndexedDB 存主题色、语言设置就过度设计了——没事务需求、无并发冲突、体积小、不需索引查询,localStorage 足够,还省去版本管理、错误监听等一堆胶水代码。
真正容易被忽略的是:三者对 Service Worker 的可见性不同。Cookie 默认不可见(除非显式配置 credentials: 'include'),localStorage 在 SW 中完全不可访问,只有 IndexedDB 可被 SW 直接读写——做离线优先应用时,这点决定架构能否闭环。