html5 storage 基础

本文详细介绍了HTML5提供的sessionStorage和localStorage两种客户端存储技术。这两种技术允许网站在用户的浏览器上存储键值对数据,sessionStorage适用于临时数据存储,而localStorage则用于持久化的数据存储。文章还提供了使用这些API的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录下基础知识。转自:https://developer.mozilla.org/en-US/docs/DOM/Storage

 

 

Reference

The following are global objects that exist as properties of every window object. This means that they can be accessed as sessionStorage or window.sessionStorage. (This is important because you can then use IFrames to store, or access, additional data, beyond what is immediately included in your page.)

Storage

This is a constructor (Storage) for all Storage instances (sessionStorage and globalStorage[location.hostname]).  Setting Storage.prototype.removeKey = function(key){ this.removeItem(this.key(key)) } would be accessed as localStorage.removeKey and sessionStorage.removeKey.

globalStorage items are not an instance of Storage, but instead are an instance of StorageObsolete.

Storage is defined by the WhatWG Storage Interface as this:


interface Storage {
  readonly attribute unsigned long length;
  [IndexGetter] DOMString key(in unsigned long index);
  [NameGetter] DOMString getItem(in DOMString key);
  [NameSetter] void setItem(in DOMString key, in DOMString data);
  [NameDeleter] void removeItem(in DOMString key);
  void clear();
};
 

Note: Although the values can be set and read using the standard JavaScript property access method, using the getItem and setItem methods is recommended.
Note: Keep in mind that everything you store in any of the storages described in this page is converted to string using its .toString method before being stored. So trying to store a common object will result in string "[object Object]" to be stored instead of the object or its JSON representation. Using native JSON parsing and serialization methods provided by the browser is a good and common way for storing objects in string format.
sessionStorage

This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

// Save data to a the current session's store
sessionStorage.setItem("username", "John");
  
// Access some stored data
alert( "username = " + sessionStorage.getItem("username"));
 

The sessionStorage object is most useful for hanging on to temporary data that should be saved and restored if the browser is accidentally refreshed.

 

 

Examples:

Autosave the contents of a text field, and if the browser is accidentally refreshed, restore the text field contents, so that no writing is lost.

// Get the text field that we're going to track
var field = document.getElementById("field");
  
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if ( sessionStorage.getItem("autosave")) {
   // Restore the contents of the text field
   field.value = sessionStorage.getItem("autosave");
}
  
// Check the contents of the text field every second
setInterval(function(){
   // And save the results into the session storage object
   sessionStorage.setItem("autosave", field.value);
}, 1000);
 

htm5 cookbook

 

 

some data for only the current browser instance (i.e., so it goes away when
the user closes the browser), use sessionStorage:
var user_id = "A1B2C3D4";
var user_data = {
name: "Tom Hanks",
occupation: "Actor",
favorite_color: "Blue"
// ...
};
sessionStorage.setItem(user_id, JSON.stringify(user_data));
To store some data for a longer period of time, use localStorage:
var user_id = "A1B2C3D4";
var user_prefs = {
keep_me_logged_in: true,
start_page: "daily news"
// ...
};
localStorage.setItem(user_id, JSON.stringify(user_prefs));
These code snippets look almost identical because the APIs are identical.
220 | Chapter 10: Advanced HTML5 JavaScript
To pull data (if available) from the storage container, use code like this:
var user_id = "A1B2C3D4";
var user_data = { /* defaults */ };
var user_prefs = { /* defaults */ };
if (sessionStorage.getItem(user_id)) {
user_data = JSON.parse(sessionStorage.getItem(user_id));
}
if (localStorage.getItem(user_id)) {
user_prefs = JSON.parse(localStorage.getItem(user_id));
}
These storage APIs allow you to very simply set and retrieve key/value data, where the
value is a string but can represent anything you want, including the string serialization
of a complex data object.
The localStorage and sessionStorage APIs are synchronous in design,
which makes them easier to use but can result in slower performance.
Be careful using these APIs in performance-sensitive code.
Discussion
The solution for storing data client-side that most likely first popped into your head is
cookies. However, cookies have a number of problems that make them less than ideal
for storing user data. In this chapter we explore a new alternative: the HTML5 storage
(also known as “DOM storage”) APIs.
sessionStorage and localStorage share the same API; the difference, as belied by their
names, is in how long they persist the data. For data that you only need to persist for
the lifetime of a browser session—things such as user login data, shopping cart contents,
etc.—the sessionStorage API is probably your best option. For more long-lived
data—things such as application preferences—localStorage may be a better option.
Many browsers even persist sessionStorage data across browser crashes.
This makes it a great container to temporarily mirror data being
entered into form fields: if the browser crashes, you can restore what
the user was typing.
The APIs for sessionStorage and localStorage are as follows:
getItem(key)
Returns an item of data from the storage container, referenced by its key
setItem(key, item)
Adds an item of data to the storage container, referenced by its key
10.1 Local Storage | 221
key(index)
Returns the key for an item of data at the numerical index specified
removeItem(key)
Removes an item from the storage container, referenced by its key
clear()
Clears out all data in the current storage container
length
Identifies how many items of data are in the storage container
Most browsers give up to 5 MB of space for these storage containers. For most practical
applications, this is more than enough. Be prepared to detect and handle errors, though,
if you are writing more data than the browser allows.
Unlike cookies (which have explicit expirations) and sessionStorage (which has implicit
expiration at the end of the browser instance/session), the localStorage API has
no expiration at all. This has both good and bad consequences.
The benefit is that data stays around as long as you need it to unless the user explicitly
clears it herself, but the downside is that the 5 MB limit may be reached more quickly
than anticipated, especially if old data is abandoned and left forever to sit idle in the
storage container.
One common solution is to implement a custom expiration mechanism, by storing a
timestamp with each piece of data and then checking manually on each page load to
see if any old data needs to be removed.
For instance, your ecommerce site might keep a record of all items the user has viewed
across various visits, so it can display that in a “Previously Viewed” area. However, you
don’t want the application to remember those items forever, so you might manually
expire entries that are older than, say, 21 days:
// first, store the currently viewed item in the history
var current_item = {
id: "ABCD0123",
data: "Mens' Running Shoes",
ts: new Date() // current timestamp, used for expiration check later
};
localStorage.setItem(current_item.id, JSON.stringify(current_item));
// then manually "expire" all old entries
var key, data;
for (var i=0; i<localStorage.length; i++) {
key = localStorage.key(i);
data = localStorage.getItem(key);
if (data.ts < ((new Date()) - 60*60*24*21)) { // more than 21 days old
localStorage.removeItem(key);
}
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值