跳转到内容

JavaScript LocalStorage

来自代码酷
Admin留言 | 贡献2025年4月30日 (三) 19:07的版本 (Page creation by admin bot)

(差异) ←上一版本 | 已核准修订 (差异) | 最后版本 (差异) | 下一版本→ (差异)

JavaScript LocalStorage[编辑 | 编辑源代码]

LocalStorage 是浏览器提供的一种 Web Storage API,允许网页在用户的浏览器中持久存储键值对数据。与 Cookies 不同,LocalStorage 的数据不会随 HTTP 请求发送到服务器,且存储容量更大(通常为 5MB 或更高)。它是 JavaScript BOM(浏览器对象模型)的一部分,常用于保存用户偏好设置、缓存数据或离线应用状态。

基本概念[编辑 | 编辑源代码]

LocalStorage 是 Window 对象的属性,通过 `window.localStorage` 访问。它提供以下核心特性:

  • 持久性:数据在浏览器关闭后仍然保留,除非手动清除。
  • 同源策略:数据仅对同一协议、域名和端口的页面可见。
  • 同步操作:所有操作(读取、写入)都是同步的,可能阻塞主线程。

与 SessionStorage 的区别[编辑 | 编辑源代码]

特性 LocalStorage SessionStorage
生命周期 永久存储,除非手动删除 仅在当前会话有效(关闭标签页/浏览器后清除)
作用域 同源的所有标签页共享 仅限当前标签页

基本操作[编辑 | 编辑源代码]

存储数据[编辑 | 编辑源代码]

使用 setItem(key, value) 方法,其中 value 必须是字符串:

// 存储用户名
localStorage.setItem('username', 'Alice');

读取数据[编辑 | 编辑源代码]

通过 getItem(key) 获取数据:

const username = localStorage.getItem('username');
console.log(username); // 输出: "Alice"

删除数据[编辑 | 编辑源代码]

移除单个键值对:

localStorage.removeItem('username');

清空所有数据:

localStorage.clear();

高级用法[编辑 | 编辑源代码]

存储复杂对象[编辑 | 编辑源代码]

LocalStorage 仅支持字符串,存储对象需使用 JSON.stringify()

const user = { name: 'Bob', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

// 读取时解析
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name); // 输出: "Bob"

监听存储事件[编辑 | 编辑源代码]

当其他同源页面修改 LocalStorage 时触发:

window.addEventListener('storage', (event) => {
  console.log(`键 ${event.key}${event.oldValue} 变更为 ${event.newValue}`);
});

实际案例[编辑 | 编辑源代码]

用户主题偏好[编辑 | 编辑源代码]

保存用户选择的主题模式(深色/浅色):

// 切换主题时保存
function setTheme(theme) {
  document.body.className = theme;
  localStorage.setItem('preferredTheme', theme);
}

// 页面加载时恢复
const savedTheme = localStorage.getItem('preferredTheme') || 'light';
setTheme(savedTheme);

表单自动保存[编辑 | 编辑源代码]

实时保存表单输入,防止意外丢失:

const form = document.getElementById('myForm');

// 输入时保存
form.addEventListener('input', () => {
  localStorage.setItem('formDraft', JSON.stringify({
    name: form.name.value,
    email: form.email.value
  }));
});

// 页面加载时恢复
const draft = JSON.parse(localStorage.getItem('formDraft'));
if (draft) {
  form.name.value = draft.name;
  form.email.value = draft.email;
}

限制与最佳实践[编辑 | 编辑源代码]

容量限制[编辑 | 编辑源代码]

不同浏览器的限制不同(通常 5MB),可用以下代码检测:

function testLocalStorageLimit() {
  const testKey = 'test';
  try {
    localStorage.setItem(testKey, new Array(5 * 1024 * 1024).join('a'));
  } catch (e) {
    console.error('LocalStorage 已满:', e);
  } finally {
    localStorage.removeItem(testKey);
  }
}

安全注意事项[编辑 | 编辑源代码]

  • 不要存储敏感信息(如密码、令牌)
  • 考虑使用 IndexedDB 处理更大数据集
  • 对存储的数据进行校验,防止 XSS 攻击

性能优化[编辑 | 编辑源代码]

对于频繁操作的数据,可缓存到内存中:

let cachedData = null;

function getData() {
  if (!cachedData) {
    cachedData = JSON.parse(localStorage.getItem('largeData'));
  }
  return cachedData;
}

浏览器兼容性[编辑 | 编辑源代码]

LocalStorage 被所有现代浏览器支持,包括:

  • Chrome 4+
  • Firefox 3.5+
  • Safari 4+
  • IE 8+
  • Edge 12+

参见[编辑 | 编辑源代码]