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

html5的本地存储怎么做的

HTML5本地存储通过 localStorageSessionStorage实现,以键值对形式存储数据,示例: localStorage.setItem('key', 'value'),读取用 getItem,支持JSON序列化存储对象,数据持久化且容量约5MB,需注意安全风险

HTML5本地存储实现方式详解

Web Storage(本地存储与 session 存储)

特点

  • 提供 localStorage(持久化)和 sessionStorage(会话级)两种接口
  • 键值对存储,值以字符串形式保存
  • 同源策略限制(协议+域名+端口必须一致)
  • 容量约5MB(不同浏览器可能有差异)

API 方法
| 方法 | 说明 |
|———|———|
| setItem(key, value) | 存储数据 |
| getItem(key) | 获取数据 |
| removeItem(key) | 删除指定数据 |
| clear() | 清空所有数据 |

示例代码

// 存储数据
localStorage.setItem('username', 'JohnDoe');
localStorage.setItem('age', 25); // 数字需转为字符串
// 读取数据
const name = localStorage.getItem('username');
console.log(name); // JohnDoe
// 删除数据
localStorage.removeItem('age');
// 清空所有数据
localStorage.clear();

IndexedDB(结构化数据库)

特点

  • 支持复杂数据类型(对象、数组等)
  • 容量大(通常可达数百MB)
  • 支持事务和索引,适合存储大量结构化数据
  • 操作异步执行,需使用回调或 Promise

基本使用步骤

  1. 打开数据库连接
  2. 创建事务对象
  3. 执行增删改查操作

示例代码

// 打开数据库
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = function(event) {
  const db = event.target.result;
  // 创建对象仓库(表)
  db.createObjectStore('users', { keyPath: 'id' });
};
request.onsuccess = function(event) {
  const db = event.target.result;
  const transaction = db.transaction(['users'], 'readwrite');
  const store = transaction.objectStore('users');
  // 添加数据
  store.add({ id: 1, name: 'Alice' });
  // 查询数据
  const request = store.get(1);
  request.onsuccess = function(event) {
    console.log(event.target.result); // {id:1, name:"Alice"}
  };
};

Cookies(传统存储方式)

特点

  • 每次HTTP请求自动携带
  • 容量小(约4KB)
  • 可设置过期时间
  • 常用于会话管理或小规模数据存储

示例代码

// 设置Cookie
document.cookie = "token=abc123; max-age=3600"; // 有效期1小时
// 读取Cookie
const getCookie = (name) => {
  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;])`));
  return match ? match[2] : null;
};
console.log(getCookie('token')); // abc123

存储方式对比表

特性 localStorage sessionStorage IndexedDB Cookies
生命周期 长期持久化 窗口/标签页关闭失效 长期持久化 可设置过期时间
容量限制 ~5MB ~5MB 数百MB ~4KB
数据类型 字符串 字符串 对象/二进制 字符串
浏览器支持 IE8+ IE8+ IE10+ 全平台支持
最佳用途 简单键值存储 临时会话数据 复杂数据管理 状态保持

相关问题与解答

问题1:如何彻底清除所有本地存储数据?

解答

  • localStorage.clear() 可清空当前域名下的所有本地存储数据
  • sessionStorage.clear() 同理,但仅影响当前会话
  • IndexedDB需遍历删除所有对象仓库中的数据,或删除数据库(需用户确认)

问题2:选择本地存储方案时应注意什么?

解答

  1. 数据量
    • 少量简单数据用 localStorage/sessionStorage
    • 大量或结构化数据用 IndexedDB
  2. 持久性需求
    • 需要长期保存选 localStorageIndexedDB
    • 临时数据用 sessionStorage
  3. 兼容性

    确保目标浏览器支持(如IE低版本不支持IndexedDB)

  4. 性能敏感场景
    • 避免频繁操作 localStorage(可能阻塞渲染)
    • 大数据量操作优先
0