跳到主要内容

客户端存储

  • 明文存储 http 请求会话信息;
  • 至多 4096 字节;
构成
  • 名称 + 值 + 域 + 路径 + 过期时间 + 有效时间 + 安全标志 + http 标识;
    • domain: 指定对应域名携带 cookie;
    • path: 指定对应路径携带 cookie;
    • expires: 指定 cookie 过期时间, 超过清楚;
    • max-age: 指定 cookie 存在时间, 超过清楚;
    • secure: 指定只有在 https 协议下才会发送 cookie;
    • httpOnly: 指定 cookie 无法通过 js 获取;
    • SameSite: 限制 cookie 跨站点请求;
  • Document.cookie: string;
// 获取 cookie
document.cookie;
// 设置 cookie
document.cookie = "name=Nicholas";
安全措施
  • 使用 httpOnly 限制 xss 攻击;
  • 使用 SameSite 限制 CSRF 攻击;
  • 使用 Secure 保证数据安全;

Web Storage

sessionStorage
  • 存储会话数据;
  • 键值对;
  • 同源存储;
    • 浏览器新建标签页, 新建 sessionStorage;
    • 标签页跳转同源标签页, 共享 sessionStorage;
localStorage
  • 键值对;
  • 同源存储;
  • 持久化存储;
localStorage API
  • Storage.prototype.setItem(key: string, value: string): void 实例方法: 存储数据;
  • Storage.prototype.getItem(key: string): string | null 实例方法: 获取数据;
  • Storage.prototype.removeItem(key: string): void 实例方法: 删除数据;
  • Storage.prototype.clear(): void 实例方法: 删除所有数据;
  • Storage.prototype.key(index: number): string | null 实例方法: 根据索引获取键;
  • Storage.prototype.length: number 实例属性: 存储键值对数量;
  • Window.prototype.addEventListener("storage", (event: StorageEvent) => void): void 实例方法: 监听存储变化事件;
// event 具有 domain + key + newValue + oldValue 四个属性
window.addEventListener("storage", (event) => console.log("Storage changed for ${event.domain}"));
容量限制
  • 一般限制为 5 mb;
隐式转换
  • Storage 只能存储字符串;
  • 非字符串存储之前自动转换为字符串;

IndexedDb

IndexedDb

  • KV 数据库;
  • 持久化存储;
  • 容量限制取决于硬盘容量;
  • 同源存储;

IndexedDb 架构

  • 数据库: 一组对象存储的集合;
  • 事务: 数据库操作通过事务完成;
  • 游标: 多次查询数据库;
  • 键范围: 用于限制游标处理范围;
  • 索引: 使用索引读写数据库;

使用逻辑

  • 使用 indexedDB 创建/打开数据库;
  • 使用 IDBOpenDBRequest/IDBRequest 响应事件;
  • 使用 IDBDatabase 操作数据库, 创建事务, 创建对象存储;
  • 使用 IDBTransaction 建立对象存储读写数据库;
  • 使用 IDBObjectStore 读写数据库, 定义并使用游标, 建立索引, 使用索引;
  • 使用 IDBCursor 定义游标, 使用键范围;
  • 使用 IDBKeyRange 定义键范围;
  • 使用 IDBIndex 读写数据库;