Skip to content

HTML 本地存储

HTML Web Storage(LocalStorage 和 SessionStorage)

Section titled “HTML Web Storage(LocalStorage 和 SessionStorage)”

Web Storage 允许 Web 应用程序在用户浏览器中本地存储数据,与传统的 cookies 相比具有优势。

Web Storage 提供机制,允许 Web 应用程序在用户浏览器中本地存储键值对。

相较于 Cookies 的优势:

  • 更大容量: Web Storage 提供远大于 cookies 的存储空间(通常每个源 5-10MB),而 cookies 大约只有 4KB。
  • 不随 HTTP 请求发送: Web Storage 中存储的数据不会随每个 HTTP 请求自动发送到服务器,与 cookies 相比,这提高了性能和安全性。
  • 更简单的 API: 提供直接的方法(setItem、getItem、removeItem)进行数据操作。

Web Storage 是域特定的。由一个源(协议、主机名、端口)的页面存储的数据是隔离的,不能被另一个源的页面访问。

Web Storage(LocalStorage 和 SessionStorage)受到所有主要现代 Web 浏览器的支持。

Web Storage 提供两个主要对象,用于在客户端存储数据:

  • window.localStorage: 存储没有过期日期的数据。即使浏览器窗口关闭后重新打开,数据也会持久存在。
  • window.sessionStorage: 数据只在当前会话期间存储。当浏览器标签页或窗口关闭时,数据会被清除。

在使用 Web Storage 之前,您可以检查浏览器是否支持:

if (typeof(Storage) !== ‘undefined’) { // Web Storage is supported. You can use localStorage and sessionStorage. // 支持 Web Storage。您可以使用 localStorage 和 sessionStorage。 console.log(‘Web Storage supported!’); } else { // Sorry! No Web Storage support.. // 抱歉!不支持 Web Storage.. console.log(‘Web Storage is not supported by this browser.’); }

使用 localStorage 存储需要在浏览器会话之间持久存在的数据,例如用户偏好设置或离线应用程序数据。

示例:

// Get the element to display results
// 获取用于显示结果的元素
const resultElement = document.getElementById('result');
// Store data: Set a key/value pair
// 存储数据:设置一个键值对
localStorage.setItem('username', 'JohnDoe');
localStorage.setItem('theme', 'dark');
// Retrieve data: Get the value associated with a key
// 检索数据:获取与键关联的值
const username = localStorage.getItem('username');
resultElement.innerHTML = `Username retrieved: ${username}<br>`;
// You can also access items like object properties (less recommended if keys might clash with Object prototype properties)
// 您也可以像访问对象属性一样访问项目(如果键名可能与 Object 原型属性冲突,则不推荐这样做)
localStorage.userLevel = 'admin';
resultElement.innerHTML += `User level: ${localStorage.userLevel}<br>`;
// Remove data: Delete a specific key/value pair
// 移除数据:删除特定的键值对
localStorage.removeItem('theme');
// Check if an item exists
// 检查项目是否存在
if (localStorage.getItem('theme') === null) {
resultElement.innerHTML += 'Theme has been removed.<br>';
}
// Clear all data: Remove all items stored in localStorage for this origin
// 清除所有数据:移除此源在 localStorage 中存储的所有项目
// localStorage.clear();
// Iterate over stored items
// 遍历存储的项目
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(`Key: ${key}, Value: ${value}`);
}
重要提示: Web Storage 只存储字符串。如果您需要存储对象或数组,请在保存前使用 JSON.stringify(),在检索后使用 JSON.parse()。数字也将被存储为字符串,因此如果需要进行计算,请使用 Number() 或 parseInt()/parseFloat() 进行转换。

示例:存储和检索对象

const userSettings = { theme: ‘dark’, notifications: true, fontSize: 16 };

// Store the object (as a JSON string) // 存储对象(作为 JSON 字符串) localStorage.setItem(‘settings’, JSON.stringify(userSettings));

// Retrieve the object (parse the JSON string) // 检索对象(解析 JSON 字符串) const retrievedSettings = JSON.parse(localStorage.getItem(‘settings’));

if (retrievedSettings) { console.log(‘Retrieved theme:’, retrievedSettings.theme); // Output: dark // console.log(‘检索到的主题:’, retrievedSettings.theme); // 输出: dark }

使用 sessionStorage 存储与当前浏览器会话相关的临时数据,例如多步表单中的用户输入或单页应用程序的当前状态。

sessionStorage 的 API 与 localStorage 完全相同(setItem、getItem、removeItem、clear、key、length),但数据只持续到标签页/窗口关闭。

示例:跟踪会话活动

// Get the element to display results
// 获取用于显示结果的元素
const sessionResultElement = document.getElementById('sessionResult');
// Check if a session counter exists, initialize if not
// 检查会话计数器是否存在,如果不存在则初始化
let visitCount = sessionStorage.getItem('pageVisits');
if (visitCount) {
visitCount = Number(visitCount) + 1;
} else {
visitCount = 1;
}
// Store the updated count
// 存储更新后的计数
sessionStorage.setItem('pageVisits', visitCount);
// Display the count for this session
// 显示当前会话的计数
sessionResultElement.innerHTML = `You have visited this page ${visitCount} time(s) in this session.`;
// sessionResultElement.innerHTML = `您在本会话中访问此页面 ${visitCount} 次。`;
  • 同步性: localStorage 和 sessionStorage 的操作都是同步的,这意味着如果过度使用或处理大量数据,它们可能会阻塞主浏览器线程。避免在主线程上执行复杂操作。
  • 存储限制: 尽管比 cookies 大,但仍然存在限制(通常为 5-10MB)。不要存储大量数据。
  • 安全性: 数据存储在客户端,并且可以通过 JavaScript 访问,因此除非经过适当的安全处理,否则不要存储敏感信息(如密码或令牌)。
  • 替代方案: 对于更大、更复杂的数据存储需求,或对于异步操作,可以考虑使用功能更强大的客户端数据库 IndexedDB。