浏览器存储指南
存储方案对比
| 存储 | 容量 | 持久性 | 可访问方 | 最适合 |
|---|---|---|---|---|
| localStorage | 5–10 MB | 直到清除 | 同源,仅 JS | 用户偏好、非敏感设置 |
| sessionStorage | 5–10 MB | 标签页会话 | 同源,仅 JS | 临时状态、向导步骤 |
| IndexedDB | 50–100+ MB | 直到清除 | 同源,JS + Worker | 离线数据、结构化数据、Blob |
| Cookie | 4 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)