Skip to content

Web Storage

存储数据 in 浏览器使用 localStorage, sessionStorage, and IndexedDB.

你将学到

  • difference 之间 localStorage, sessionStorage, and IndexedDB
  • 如何 读取, 编写, and 移除项 使用 Storage API
  • 当到 use 每个 storage mechanism and 它们的大小限制
  • 为什么 sensitive 数据应该不 go in localStorage (XSS risk)

概念讲解

Web Storage

Browsers can store data on the user's device, so it persists across page reloads and sessions. There are three main options — localStorage, sessionStorage, and IndexedDB — each with different lifetimes, capacities, and use cases. Choosing the right one is a key decision in web app design.

localStorage

localStorage stores key-value pairs as strings. Data persists indefinitely — it survives page reloads, browser restarts, and even computer reboots — until explicitly cleared. The API is simple:

localStorage.setItem("主题", "dark");
const theme = localStorage.getItem("theme");  // "dark"
localStorage.removeItem("主题");

The capacity is typically 5–10 MB per origin. Because it is synchronous, large reads can block the main thread. localStorage is perfect for user preferences (theme, language), small cached data, and feature flags. It is never sent to the server — it is purely client-side.

sessionStorage

sessionStorage has the same API as localStorage, but data is cleared when the tab or window closes. It is useful for temporary state that should not persist: a multi-step form's progress, a scroll position to restore on back-button, or a temporary filter. If the user opens the same page in a new tab, each tab has its own sessionStorage — they do not share.

IndexedDB

IndexedDB is a full client-side database — it stores structured data, supports indexes and queries, and handles large amounts (hundreds of MB or more). It is asynchronous (does not block the UI) and can store objects, files, and blobs, not just strings. The API is more complex than localStorage, so many developers use a wrapper library like idb or localForage. Use IndexedDB for offline-first apps, large caches, and storing data that needs querying.

Security Warning

Never store sensitive data in localStorage. Any JavaScript running on the page — including injected XSS scripts — can read it. Passwords, session tokens, and personal data belong in httpOnly cookies (which JavaScript cannot access) or in server-side sessions. localStorage is for non-sensitive preferences and caches only. This is one of the most common web security mistakes.

示例代码

              // A theme manager using localStorage
const ThemeStore = {
  get() {
    return localStorage.getItem("theme") || "light";
  },
  set(theme) {
    localStorage.setItem("theme", theme);
    document.body.dataset.theme = theme;
  },
  toggle() {
    this.set(this.get() === "light" ? "dark" : "light");
  }
};

// A multi-step form using sessionStorage for temporary progress
const FormProgress = {
  save(step, data) {
    sessionStorage.setItem(`form-step-${step}`, JSON.stringify(data));
  },
  load(step) {
    const raw = sessionStorage.getItem(`form-step-${step}`);
    return raw ? JSON.parse(raw) : null;
  },
  clear() {
    sessionStorage.clear();
  }
};

// On page load, restore the theme
ThemeStore.set(ThemeStore.get());

// Listen for storage changes in other tabs
window.addEventListener("storage", (e) => {
  if (e.key === "theme") ThemeStore.set(e.newValue);
});
            

ThemeStore uses localStorage for persistent 主题那个 survives reloads. FormProgress uses sessionStorage for temporary 表单数据那个 clears 当 tab 关闭. storage 事件 fires in other tabs 当 localStorage 更改, 启用 cross-tab 主题 sync. 所有数据是 非-sensitive.

动手试一试

  • JWT Decoder

    Decode JWT 到 see 什么数据是 in 它 — 但从不存储 JWTs in localStorage.

  • JSON Formatter

    格式 JSON 数据之前存储它 in localStorage or IndexedDB.

常见错误

错误写法

存储 sensitive 数据如 密码 or 认证令牌 in localStorage.

正确做法

localStorage 是 readable 通过任何 JavaScript on page, 包含 XSS attacks. 存储 sensitive 会话数据 in httpOnly, Secure Cookie 那个 JavaScript cannot access. Reserve localStorage for 非-sensitive preferences 如主题 and language.

错误写法

存储对象 directly 不使用 JSON.stringify, 获取 [对象对象].

正确做法

localStorage 仅存储字符串. Use JSON.stringify(obj) 当编写 and JSON.parse(str) 当读取. Wrap parse in try/catch 因为 corrupted 数据将 throw.

相关速查表

练习 Web Storage

4 个练习

练习 Web Storage

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误