当前位置:首页 > 行业动态 > 正文

html5本地存储数据库

HTML5本地存储含localStorage(持久)、sessionStorage(会话级)及IndexedDB(结构化),均基于浏览器端,免服务器交互,支持离线数据存取,适配轻量

HTML5 本地存储机制详解

本地存储类型对比

存储类型 数据结构 持久性 容量限制 作用域 浏览器支持
localStorage 键值对(字符串) 永久 ~5MB 同源窗口/标签页 IE8+/Chrome4+/Firefox3.5+
sessionStorage 键值对(字符串) 会话级 ~5MB 同源窗口/标签页 IE8+/Chrome4+/Firefox3.5+
IndexedDB 键值对(对象) 永久 ~500MB 同源窗口/标签页 IE10+/Chrome12+/Firefox13+
Cookie 键值对(字符串) 可设置过期时间 ~4KB 跨域(需服务器配置) 所有浏览器

IndexedDB 核心特性

  1. ACID 事务支持
    通过事务对象保证数据操作的原子性、一致性、隔离性和持久性

  2. 对象存储(Object Store)
    类似数据库表结构,支持主键索引和自定义索引

    html5本地存储数据库  第1张

  3. 异步 API
    所有操作基于事件回调或 Promise(需封装)

  4. 游标遍历
    支持双向遍历数据记录,类似数据库游标操作

IndexedDB 基础操作示例

// 打开数据库
const request = indexedDB.open('myDatabase', 2);
request.onupgradeneeded = (event) => {
  const db = event.target.result;
  // 创建对象仓库并定义主键
  db.createObjectStore('users', { keyPath: 'id' });
};
request.onsuccess = (event) => {
  const db = event.target.result;
  // 事务操作
  const transaction = db.transaction(['users'], 'readwrite');
  const store = transaction.objectStore('users');
  // 添加数据
  store.add({ id: 1, name: 'Alice' });
  // 查询数据
  store.get(1).onsuccess = (e) => console.log(e.target.result);
};

存储类型选型建议

应用场景 推荐方案 原因
简单配置缓存 localStorage 轻量级键值存储,无需复杂操作
会话级临时数据 sessionStorage 窗口关闭自动清除
结构化大数据持久化 IndexedDB 支持复杂查询和事务,容量大
服务器端会话管理 Cookie 自动随请求发送,支持服务器验证

常见问题与解答

Q1:如何判断浏览器是否支持 IndexedDB?
A:可通过检测 indexedDB 属性是否存在:

if (window.indexedDB) {
  console.log('支持 IndexedDB');
} else {
  console.log('不支持 IndexedDB');
}

Q2:LocalStorage 存储复杂对象时需要注意什么?
A:需手动序列化/反序列化 JSON 数据:

// 存储对象
const user = { name: 'Bob', age: 30 };
localStorage.setItem('user', JSON.stringify(user));
// 读取对象
const userData = JSON.parse(localStorage.getItem('user'));
0