浏览器存储指南

存储方案对比

存储容量持久性可访问方最适合
localStorage5–10 MB直到清除同源,仅 JS用户偏好、非敏感设置
sessionStorage5–10 MB标签页会话同源,仅 JS临时状态、向导步骤
IndexedDB50–100+ MB直到清除同源,JS + Worker离线数据、结构化数据、Blob
Cookie4 KB可配置HTTP + JS(非 httpOnly)认证令牌、会话 ID
Cache API配额限制直到清除JS + Service Worker网络请求缓存(PWA)

localStorage

// 设置 localStorage.setItem('theme', 'dark'); localStorage.setItem('user', JSON.stringify({ name: 'Alice', id: 42 })); // 获取 const theme = localStorage.getItem('theme'); // "dark" const user = JSON.parse(localStorage.getItem('user')); // 移除 localStorage.removeItem('theme'); // 清空全部 localStorage.clear(); // 监听其他标签页的变化 window.addEventListener('storage', (e) => { console.log('键变化:', e.key, e.oldValue, e.newValue); });

IndexedDB (使用 idb 库)

import { openDB } from 'idb'; // 打开/创建数据库 const db = await openDB('my-app', 1, { upgrade(db) { const store = db.createObjectStore('products', { keyPath: 'id' }); store.createIndex('category', 'category', { unique: false }); } }); // 添加记录 await db.add('products', { id: 1, name: '小工具', category: 'tools', price: 9.99 }); // 获取记录 const product = await db.get('products', 1); // 通过索引获取 const toolProducts = await db.getAllFromIndex('products', 'category', 'tools'); // 删除 await db.delete('products', 1);

安全 Cookie 属性

// 服务端设置 Cookie(Go/Gin) c.SetCookie("session_id", sessionToken, 86400, "/", ".example.com", true, true) // Cookie 字符串 Set-Cookie: session_id=abc123; Max-Age=86400; Path=/; Domain=.example.com; Secure; HttpOnly; SameSite=Strict // SameSite 选项: // Strict — 仅同站请求 // Lax — 允许顶级 GET(默认) // None — 跨站(需要 Secure)