MDN wants to learn about developers like you:

 Web Storage API 提供机制, 使浏览器能以一种比使用Cookie更直观的方式存储键/值对。

Web Storage 概念和用法

Web Storage 包含如下两种机制:

  • sessionStorage 为每一个给定的源(given origin)维持一个独立的存储区域,该存储区域在页面会话期间可用(即只要浏览器处于打开状态,包括页面重新加载和恢复)。
  • localStorage 同样的功能,但是在浏览器关闭,然后重新打开后数据仍然存在。

这两种机制是通过 Window.sessionStorageWindow.localStorage 属性使用(更确切的说,在支持的浏览器中 Window 对象实现了 WindowLocalStorage 和 WindowSessionStorage 对象并挂在其 localStoragesessionStorage 属性下)—— 调用其中任一对象会创建 Storage 对象,通过 Storage 对象,可以设置、获取和移除数据项。对于每个源(origin)sessionStoragelocalStorage 使用不同的 Storage 对象——独立运行和控制。

注意:从Firefox 45开始,当浏览器奔溃或重启时,每个源的存储大小将限制在10M,以避免因过度使用web storage引起的内存问题。

注意:若用户禁用第三方cookie,那么将不允许来自第三方IFrames对Web Storage的访问。(从Firefox 43版本开始实行)

注意:本地存储不同于mozStorage(Mozilla's XPCOM interfaces to SQLite)或Session store API(an XPCOM storage utility for use by extensions)。

Web Storage 接口

允许你在一个特定域中设置,检索和删除数据和储存类型(session or local.)
Web Storage API 继承于Window 对象,并提供两个新属性  — Window.sessionStorageWindow.localStorage — 它们分别地提供对当前域的会话和本地Storage 对象的访问。
 当一个存储区更改时,存储事件从文档的 Window 对象上被发布。


为了阐述一些 典型的web storage的用法, 我们创了一个简单的例子,  Web Storage Demo. landing page 提供控制器可以用来自定义颜色,字体和装饰图片。 当你选择不同的选项, 页面会被立即更新;此外,你的选择被储存到 localStorage 中,  以便当你离开该页面,然后过些时候在重新加载它时,你的选择会被记住。

另外, 我们提供了一个 event output page — 如果你在另一个标签页加载这个页面, 然后在landing page改变你的选择,当StorageEvent被发布时,你将会看到被更新的储存信息输出。


Specification Status Comment
Web Storage (Second edition) Recommendation  


Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
localStorage 4 3.5 8 10.50 4
sessionStorage 5 2 8 10.50 4
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support 2.1 ? 8 11 iOS 3.2


注意:手机Safari从IOS 5.1版本开始,将localStorage数据到存放到缓存文件夹中,当空间不足时,系统将会时不时地自动清理缓存。

隐私浏览/ 隐身模式

Most modern browsers support a privacy option called 'Incognito', 'Private Browsing' or something similar that doesn't store data like history and cookies. This is fundamentally incompatible with Web Storage for obvious reasons. As such, browser vendors are experimenting with different scenarios for how to deal with this incompatibility.

Most browsers have opted for a strategy where storage APIs are still available and seemingly fully functional, with the one big difference that all stored data is wiped after the browser is closed. For these browsers there are still different interpretations of what should be done with existing stored data (from a regular browsing session). Should it be available to read when in Private mode? Then there are some browsers, most notably Safari, that have opted for a solution where storage is available, but is empty and has a quota of 0 bytes assigned, effectively making it impossible to write data to it.

Developers should be aware of these different implementations and take them into account when developing websites depending on Web Storage APIs. For more information please have a look at this WHATWG blog post that specifically deals with this topic.


Web Storage API的使用


 最后编辑者: Dafrok,