Reference Web API reference

Web Storage 参考

Web Storage 包括 localStorage 和 sessionStorage,适合保存少量字符串数据,例如用户偏好、临时表单草稿、工具输入缓存。

语法

js
localStorage.setItem("key", "value");
const value = localStorage.getItem("key");

localStorage 与 sessionStorage

API 生命周期 常见用途
localStorage 手动删除前长期保留 主题偏好、工具配置、低敏缓存
sessionStorage 当前标签页会话内保留 临时步骤、一次性表单状态

常用方法

方法 说明
setItem(key, value) 写入字符串
getItem(key) 读取字符串,缺失时返回 null
removeItem(key) 删除某个键
clear() 清空当前源下的全部存储
key(index) 按索引读取键名

示例

js
const payload = {
  value: "dark",
  expiresAt: Date.now() + 7 * 24 * 60 * 60 * 1000,
};

localStorage.setItem("theme", JSON.stringify(payload));

const raw = localStorage.getItem("theme");
const item = raw ? JSON.parse(raw) : null;

if (item && item.expiresAt > Date.now()) {
  console.log(item.value);
}

可运行演示

在线代码演示
源码
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Web Storage 演示</title>
    <style>
      * { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #0f172a; background: #f8fafc; }
      .demo { max-width: 720px; margin: 0 auto; padding: 20px; border: 1px solid #dbeafe; border-radius: 12px; background: #ffffff; }
      label { display: grid; gap: 8px; font-weight: 600; }
      textarea { min-height: 120px; padding: 12px; border: 1px solid #cbd5e1; border-radius: 8px; font: inherit; resize: vertical; }
      .actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 14px; }
      button { padding: 10px 14px; border: 0; border-radius: 8px; color: #ffffff; background: #2563eb; cursor: pointer; }
      button.secondary { color: #1e3a8a; background: #dbeafe; }
      p { min-height: 24px; color: #475569; }
    </style>
  </head>
  <body>
    <main class="demo">
      <label>
        便签内容
        <textarea id="note">这段内容会保存到 localStorage。</textarea>
      </label>
      <div class="actions">
        <button id="save" type="button">保存</button>
        <button id="load" class="secondary" type="button">读取</button>
        <button id="clear" class="secondary" type="button">删除</button>
      </div>
      <p id="status">localStorage 只能保存字符串。</p>
    </main>
    <script>
      const key = "caijiao:web-storage-demo";
      const note = document.querySelector("#note");
      const status = document.querySelector("#status");
      document.querySelector("#save").addEventListener("click", () => {
        localStorage.setItem(key, JSON.stringify({ value: note.value, savedAt: Date.now() }));
        status.textContent = "已保存到 localStorage。";
      });
      document.querySelector("#load").addEventListener("click", () => {
        const raw = localStorage.getItem(key);
        if (!raw) {
          status.textContent = "还没有保存内容。";
          return;
        }
        const item = JSON.parse(raw);
        note.value = item.value;
        status.textContent = "已读取保存内容。";
      });
      document.querySelector("#clear").addEventListener("click", () => {
        localStorage.removeItem(key);
        status.textContent = "已删除保存内容。";
      });
    </script>
  </body>
</html>

常见错误

  • Web Storage 只能保存字符串;对象要先 JSON.stringify(),读取后再 JSON.parse()。
  • localStorage 没有内置过期时间,需要自己保存 expiresAt 并在读取时判断。
  • 不要保存 token、密码、身份证号等敏感信息。
  • SSR 环境没有 window 和 localStorage,要放到客户端代码中执行。

相关内容