aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/conflicting/web/api/web_storage_api/index.html
blob: c5bde57455508b989f75b23954793004687f56c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
---
title: Storage
slug: conflicting/Web/API/Web_Storage_API
translation_of: Web/API/Web_Storage_API
translation_of_original: Web/Guide/API/DOM/Storage
original_slug: Web/Guide/API/DOM/Storage
---
<h3 id="概述">
	概述</h3>
<p>
	DOM存储是一套在<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/" title="http://www.whatwg.org/specs/web-apps/current-work/">Web Applications 1.0</a> 规范中首次引入的与<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#storage">存储相关的特性</a>的总称, 现在已经分离出来,单独发展成为独立的<a class="external" href="http://dev.w3.org/html5/webstorage/" title="http://dev.w3.org/html5/webstorage/">W3C Web存储</a>规范. DOM存储被设计为用来提供一个更大存储量,更安全,更便捷的存储方法,从而可以代替掉将一些不需要让服务器知道的信息存储到cookies里的这种传统方法.该特性在<a href="/zh-cn/Firefox_2_for_developers" title="zh-cn/Firefox_2_for_developers">Firefox 2</a><a class="external" href="http://developer.apple.com/safari/library/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Name-ValueStorage/Name-ValueStorage.html" title="http://developer.apple.com/safari/library/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Name-ValueStorage/Name-ValueStorage.html">Safari 4</a>中首次引入.</p>
<div class="note">
	<strong>注意:</strong> DOM存储有别于<a href="/zh-cn/Storage" title="zh-cn/Storage">mozStorage</a> (Mozilla的XPCOM接口,用来访问SQLite) 也有别于<a href="/zh-cn/Session_store_API" title="zh-cn/Session_store_API">Session store API</a> (一个<a href="/zh-cn/XPCOM" title="zh-cn/XPCOM">XPCOM</a> 存储工具,主要为扩展程序使用).</div>
<h3 id="描述">
	描述</h3>
<p>
	DOM存储的机制是通过存储字符串类型的键/值对,来提供一种安全的存取方式.这个附加功能的目标是提供一个全面的,可以用来创建交互式应用程序的方法(包括那些高级功能,例如可以离线工作一段时间).</p>
<p>
	基于Mozilla的浏览器, Internet Explorer 8+, Safari 4+ 以及 Chrome 都提供了自己的DOM存储规范的实现. (如果你想让自己的代码兼容多个浏览器,则你需要照顾一下老版本的IE浏览器,IE下有一个类似的特性,在IE8之前版本也可以使用,叫做"<a class="external" href="http://msdn.microsoft.com/zh-cn/library/ms531424%28VS.85%29.aspx">userData behavior</a>",它允许你在多重浏览器会话中永久地保存数据.)</p>
<p>
	DOM存储很有用,因为在浏览器端没有好的方法来持久保存大量数据。浏览器<a href="http://en.wikipedia.org/wiki/HTTP_cookie">cookie</a>的能力有限,而且不支持组织持久数据,其他方法(如<a href="http://www.macromedia.com/support/documentation/zh-cn/flashplayer/help/help02.html">flash本地存储</a>)需要外部插件支持。</p>
<p><a href="http://aaronboodman.com/">Aaron Boodman</a>编写的<a href="http://aaronboodman.com/halfnote/">halfnote</a>(笔记类应用程序)是第一批使用新的DOM存储功能(不包括internet explorer的userData behavior)开发的公开应用程序之一。在这个应用里,Aaron同时将笔记保存到服务器(当网络可用时)和本地,这允许使用者即使在不稳定的网络环境下也能安全的记录备注事项。</p>
<p>
	虽然halfnote的理念和实现比较简单,但是halfnote的创新展示了一种在线上和线下都可用的新型web应用的可能性。</p>
<h3 id="参考">
	参考</h3>
<p>
	以下所提到的对象都是全局对象,作为 <a href="/zh-cn/DOM/window" title="/zh-cn/DOM/window">window 对象</a> 的属性存在。这意味着可以以 <code>sessionStorage</code> 或者 <code>window.sessionStorage 的形式访问这些对象。</code>(这点很重要,因为可以使用iframe来存储、访问除了直接包含在页面的数据之外的附加数据。)</p>
<h4 id="Storage">
	<code>Storage</code></h4>
<p>
	它是所有Storage实例(<code>sessionStorage</code><code>globalStorage[location.hostname]</code>)的构造函数,设置<code>Storage.prototype.removeKey = function(key) { this.removeItem(this.key(key)) }</code>,可通过<code>localStorage.removeKey</code><code>sessionStorage.removeKey</code>访问到。</p>
<p>
	<code>globalStorage</code>对象不是<code>Storage</code>的实例,而是<code>StorageObsolete</code>的一个实例。</p>
<p>
	<code>Storage</code>被定义在WhatWG <a class="external" href="http://dev.w3.org/html5/webstorage/#storage-0" title="http://dev.w3.org/html5/webstorage/#storage-0">Storage Interface</a> 中,如下:</p>
<pre class="eval">interface <dfn>Storage</dfn> {
  readonly attribute unsigned long <a class="external" href="http://dev.w3.org/html5/webstorage/#dom-storage-length" title="dom-Storage-length">length</a>;
  [IndexGetter] DOMString <a class="external" href="http://dev.w3.org/html5/webstorage/#dom-storage-key" title="dom-Storage-key">key</a>(in unsigned long index);
  [NameGetter] DOMString <a class="external" href="http://dev.w3.org/html5/webstorage/#dom-storage-getitem" title="dom-Storage-getItem">getItem</a>(in DOMString key);
  [NameSetter] void <a class="external" href="http://dev.w3.org/html5/webstorage/#dom-storage-setitem" title="dom-Storage-setItem">setItem</a>(in DOMString key, in DOMString data);
  [NameDeleter] void <a class="external" href="http://dev.w3.org/html5/webstorage/#dom-storage-removeitem" title="dom-Storage-removeItem">removeItem</a>(in DOMString key);
  void <a class="external" href="http://dev.w3.org/html5/webstorage/#dom-storage-clear" title="dom-Storage-clear">clear</a>();
};
</pre>
<div class="note">
	<strong>注意:</strong>虽然可以直接通过标准的 JavaScript 属性访问方法来设置和读取值,但是推荐的做法是使用 getItem 和 setItem 方法。</div>
<div class="note">
	<strong>注意:</strong>需要时刻注意的一点是,所有数据在被保存到下面将要介绍的任何一个存储器之前,都将通过它的 <code>.toString</code> 方法被转换成字符串。所以一个普通对象将会被存储为 <code>"[object Object]"</code>,而不是对象本身或者它的 JSON 形式。使用浏览器自身提供的 JSON 解析和序列化方法来存取对象是比较好的,也是比较常见的方法。</div>
<h4 id="sessionStorage_2">
	<code>sessionStorage</code></h4>
<p>
	<code>sessionStorage</code> 是个全局对象,它维护着<span style="line-height: inherit;">在页面会话(page session)期间有效的</span><span style="line-height: inherit;">存储空间。只要浏览器开着,页面会话周期就会一直持续。当页面重新载入(reload)或者被恢复(restores)时,页面会话也是一直存在的。每在新标签或者新窗口中打开一个新页面,都会初始化一个新的会话。</span><span style="line-height: inherit;"> </span></p>
<pre class="brush: js">// 保存数据到当前会话的存储空间
sessionStorage.setItem("username", "John");

// 访问数据
alert( "username = " + sessionStorage.getItem("username"));
</pre>
<p>
	当浏览器被意外刷新的时候,一些临时数据应当被保存和恢复。<code>sessionStorage</code> 对象在处理这种情况的时候是最有用的。</p>
<p>
	{{ fx_minversion_note("3.5", "在Firefox 3.5之前的版本中,如果浏览器意外崩溃,则在重启后,sessionStorage中保存的数据不会被恢复.之后的版本中,会恢复上次崩溃前的sessionStorage数据.") }}</p>
<p>
	<strong>例子:</strong></p>
<p>
	自动保存一个文本域中的内容,如果浏览器被意外刷新,则恢复该文本域中的内容,所以不会丢失任何输入的数据。</p>
<pre class="brush: js"> // 获取到我们要循环保存的文本域
 var field = document.getElementById("field");

 // 查看是否有一个自动保存的值
 // (只在浏览器被意外刷新时)
 if ( sessionStorage.getItem("autosave")) {
    // 恢复文本域中的内容
    field.value = sessionStorage.getItem("autosave");
 }

 // 每隔一秒检查文本域中的内容
 setInterval(function(){
    // 并将文本域的值保存到session storage对象中
    sessionStorage.setItem("autosave", field.value);
 }, 1000);
</pre>
<p>
	<strong>更多信息:</strong></p>
<ul>
	<li>
		<a class="external" href="http://dev.w3.org/html5/webstorage/#the-sessionstorage-attribute" title="http://dev.w3.org/html5/webstorage/#the-sessionstorage-attribute">sessionStorage specification</a></li>
</ul>
<h4 id="localStorage">
	<code>localStorage</code></h4>
<p>
	<code>localStorage</code> is the same as sessionStorage with same same-origin rules applied but it is persistent. <code>localStorage</code> was introduced in Firefox 3.5.</p>
<div class="note">
	<strong>注意:</strong>当浏览器进入私人模式(private browsing mode,Google Chrome 上对应的应该是叫隐身模式)的时候,会创建一个新的、临时的、空的数据库,用以存储本地数据(local storage data)。当浏览器关闭时,里面的所有数据都将被丢弃。</div>
<h4 id="兼容性">
	兼容性</h4>
<p>
	这些<code> Storage</code> 对象最近刚被加入标准当中,所以并不是所有的浏览器都支持。如果你想在没有原生支持 <code>localStorage</code> 对象的浏览器中使用它,可以在你编写的 JavaScript 代码的首部插入下面两段代码中的任意一段。</p>
<p>
	This algorithm is an exact imitation of the <code>localStorage</code> object, but making use of cookies.</p>
<pre class="brush: js">if (!window.localStorage) {
  Object.defineProperty(window, "localStorage", new (function () {
    var aKeys = [], oStorage = {};
    Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "key", {
      value: function (nKeyId) { return aKeys[nKeyId]; },
      writable: false,
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "setItem", {
      value: function (sKey, sValue) {
        if(!sKey) { return; }
        document.cookie = escape(sKey) + "=" + escape(sValue) + "; path=/";
      },
      writable: false,
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "length", {
      get: function () { return aKeys.length; },
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "removeItem", {
      value: function (sKey) {
        if(!sKey) { return; }
        var sExpDate = new Date();
        sExpDate.setDate(sExpDate.getDate() - 1);
        document.cookie = escape(sKey) + "=; expires=" + sExpDate.toGMTString() + "; path=/";
      },
      writable: false,
      configurable: false,
      enumerable: false
    });
    this.get = function () {
      var iThisIndx;
      for (var sKey in oStorage) {
        iThisIndx = aKeys.indexOf(sKey);
        if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); }
        else { aKeys.splice(iThisIndx, 1); }
        delete oStorage[sKey];
      }
      for (aKeys; aKeys.length &gt; 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); }
      for (var iCouple, iKey, iCouplId = 0, aCouples = document.cookie.split(/\s*;\s*/); iCouplId &lt; aCouples.length; iCouplId++) {
        iCouple = aCouples[iCouplId].split(/\s*=\s*/);
        if (iCouple.length &gt; 1) {
          oStorage[iKey = unescape(iCouple[0])] = unescape(iCouple[1]);
          aKeys.push(iKey);
        }
      }
      return oStorage;
    };
    this.configurable = false;
    this.enumerable = true;
  })());
}
</pre>
<div class="note">
	<strong>Note:</strong> The maximum size of data that can be saved is severely restricted by the use of cookies. With this algorithm, use the functions <code>localStorage.setItem()</code> and <code>localStorage.removeItem()</code> to add, change or remove a key. The use of methods <code>localStorage.yourKey = yourValue;</code> and <code>delete localStorage.yourKey;</code> to set or delete a key <strong>is not a secure way with this code</strong>. You can also change its name and use it only to manage a document's cookies regardless of the localStorage object.</div>
<p>
	Here is another, less exact, imitation of the <code>localStorage</code> object. It is simpler than the previous one, but it is compatible with old browsers, like Internet Explorer &lt; 8. It also makes use of cookies.</p>
<pre class="brush: js">if (!window.localStorage) {
  window.localStorage = {
    getItem: function (sKey) {
      if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&amp;") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
    },
    key: function (nKeyId) { return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]); },
    setItem: function (sKey, sValue) {
      if(!sKey) { return; }
      document.cookie = escape(sKey) + "=" + escape(sValue) + "; path=/";
      this.length = document.cookie.match(/\=/g).length;
    },
    length: 0,
    removeItem: function (sKey) {
      if (!sKey || !this.hasOwnProperty(sKey)) { return; }
      var sExpDate = new Date();
      sExpDate.setDate(sExpDate.getDate() - 1);
      document.cookie = escape(sKey) + "=; expires=" + sExpDate.toGMTString() + "; path=/";
      this.length--;
    },
    hasOwnProperty: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&amp;") + "\\s*\\=")).test(document.cookie); }
  };
  window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
}
</pre>
<div class="note">
	<strong>Note:</strong> The maximum size of data that can be saved is severely restricted by the use of cookies. With this algorithm, use the functions <code>localStorage.getItem()</code>, <code>localStorage.setItem()</code> and <code>localStorage.removeItem()</code> to get, add, change or remove a key. The use of method <code>localStorage.yourKey</code> in order to get, set or delete a key <strong>is not permitted with this code</strong>. You can also change its name and use it only to manage a document's cookies regardless of the localStorage object.</div>
<h5 id="与_globalStorage_的关系的兼容性">
	与 globalStorage 的关系的兼容性</h5>
<p class="note">
	<code>localStorage</code> is also the same as <code>globalStorage[location.hostname]</code>, with the exception of being scoped to an HTML5 origin (scheme + hostname + non-standard port) and <code>localStorage</code> being an instance of <code>Storage</code> as opposed to <code>globalStorage[location.hostname]</code> being an instance of <code>StorageObsolete</code> which is covered below. 例如,在 <a class="external" href="http://example.com" rel="freelink">http://example.com</a> 中不能访问 <a class="link-https" href="https://example.com" rel="freelink">https://example.com</a> 中的 <code>localStorage</code> 对象,但是它们都可以访问同一个 <code>globalStorage。</code> <code>localStorage</code> 是个标准接口,但 <code>globalStorage</code> 是非标准的。所以你的代码最好不要依赖这些关系。</p>
<p>
	Please note that setting a property on <code>globalStorage[location.hostname]</code> does <strong>not</strong> set it on <code>localStorage</code> and extending <code>Storage.prototype</code> does not affect <code>globalStorage</code> items, only extending <code>StorageObsolete.prototype</code> does.</p>
<h4 id="globalStorage_2">
	<code>globalStorage</code></h4>
<p>
	{{ Non-standard_header() }}{{ obsolete_header("13.0") }}<code>globalStorage </code>is obsolete since Gecko 1.9.1 (Firefox 3.5) and unsupported since Gecko 13 (Firefox 13). Just use<code> {{ Anch("localStorage") }} </code>instead. This proposed addition to HTML 5 has been removed from the HTML 5 specification in favor of &lt;code&gt;localStorage&lt;/code&gt;, which is implemented in Firefox 3.5. This is a global object (<code>globalStorage</code>) that maintains multiple private storage areas that can be used to hold data over a long period of time (e.g. over multiple pages and browser sessions).</p>
<div class="warning">
	Note: <code>globalStorage</code> is not a <code>Storage</code> instance, but a <code>StorageList</code> instance containing <code>StorageObsolete</code> instances.</div>
<pre class="eval deki-transform">// Save data that only scripts on the mozilla.org domain can access
globalStorage['mozilla.org'].setItem("snippet", "&lt;b&gt;Hello&lt;/b&gt;, how are you?");
</pre>
<p>
	Specifically, the <code>globalStorage</code> object provides access to a number of different storage objects into which data can be stored. For example, if we were to build a web page that used <code>globalStorage</code> on this domain (developer.mozilla.org) we'd have the following storage object available to us:</p>
<ul>
	<li>
		<code>globalStorage{{ mediawiki.external('\'developer.mozilla.org\'') }}</code> - All web pages within the developer.mozilla.org sub-domain can both read and write data to this storage object.</li>
</ul>
<p>
	<strong>例子:</strong></p>
<p>
	All of these examples require that you have a script inserted (with each of the following code) in every page that you want to see the result on.</p>
<p>
	Remember a user's username for the particular sub-domain that is being visited:</p>
<pre class="eval deki-transform"> globalStorage['developer.mozilla.org'].setItem("username", "John");
</pre>
<p>
	Keep track of the number of times that a user visits all pages of your domain:</p>
<pre class="eval deki-transform"> // parseInt must be used since all data is stored as a string
 globalStorage['mozilla.org'].setItem("visits", parseInt(globalStorage['mozilla.org'].getItem("visits") || 0 ) + 1);
</pre>
<h3 id="存储位置以及清除数据">
	存储位置以及清除数据</h3>
<p>
	In Firefox the DOM storage data is stored in the <a class="external" href="http://kb.mozillazine.org/Webappsstore.sqlite" title="http://kb.mozillazine.org/Webappsstore.sqlite">webappsstore.sqlite file</a> in the profile folder (there's also chromeappsstore.sqlite file used to store browser's own data, <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=592990" title="https://bugzilla.mozilla.org/show_bug.cgi?id=592990">notably for the start page - about:home</a>, but potentially for other internal pages with "about:" URLs).</p>
<ul>
	<li>
		DOM Storage can be cleared via "Tools -&gt; Clear Recent History -&gt; Cookies" when Time range is "Everything" (via nsICookieManager::removeAll)
		<ul>
			<li>
				But not when another time range is specified: (<a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=527667" title="https://bugzilla.mozilla.org/show_bug.cgi?id=527667">bug 527667</a>)</li>
			<li>
				Does not show up in Tools -&gt; Options -&gt; Privacy -&gt; Remove individual cookies (<a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=506692" title="https://bugzilla.mozilla.org/show_bug.cgi?id=506692">bug 506692</a>)</li>
		</ul>
	</li>
	<li>
		DOM Storage is <strong>not</strong> cleared via Tools -&gt; Options -&gt; Advanced -&gt; Network -&gt; Offline data -&gt; Clear Now.</li>
	<li>
		Doesn't show up in the "Tools -&gt; Options -&gt; Advanced -&gt; Network -&gt; Offline data" list, unless the site also uses the offline cache. If the site does appear in that list, its DOM storage data is removed along with the <a href="/zh-cn/HTML/Using_the_application_cache" title="zh-cn/Offline resources in Firefox">offline cache</a> when clicking the Remove button.</li>
</ul>
<p>
	See also <a href="/zh-cn/HTML/Using_the_application_cache#Storage_location_and_clearing_the_offline_cache" title="zh-cn/Offline resources in Firefox#Storage location and clearing the offline cache">clearing offline resources cache</a>.</p>
<h3 id="更多信息">
	更多信息</h3>
<ul>
	<li>
		<a class="external" href="http://www.w3.org/TR/webstorage/" title="http://www.w3.org/TR/webstorage/">Web Storage</a> (W3C Web Apps Working Group)</li>
	<li>
		<a class="external" href="http://kb.mozillazine.org/Dom.storage.enabled">Enable/Disable DOM Storage in Firefox or SeaMonkey</a></li>
</ul>
<h3 id="例子">
	例子</h3>
<ul>
	<li>
		<a class="external" href="http://www.diveintojavascript.com/tutorials/web-storage-tutorial-creating-an-address-book-application" title="JavaScript Web Storage Tutorial: Creating an Address Book Application">JavaScript Web Storage Tutorial: Creating an Address Book Application</a> - hands-on tutorial describing how to use the Web Storage API by creating a simple address book application</li>
	<li>
		<a class="external" href="http://hacks.mozilla.org/2010/01/offline-web-applications/" title="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li>
	<li>
		<a class="external" href="http://noteboard.eligrey.com/" title="http://noteboard.eligrey.com/">Noteboard</a> - Note writing application that stores all data locally.</li>
	<li>
		<a class="external" href="http://github.com/eligrey/jData-host" title="http://github.com/eligrey/jData-host">jData</a> - A shared localStorage object interface that can be accessed by any website on the internet and works on Firefox 3+, Webkit 3.1.2+ nightlies, and IE8. Think of it as pseudo-globalStorage[""] but write access needs user confirmation.</li>
	<li>
		<a class="external" href="http://codebase.es/test/webstorage.html" title="http://codebase.es/test/webstorage.html">HTML 5 localStorage example</a>. Very simple and easy to understand example of localStorage. Saves and retrieves texts and shows a list of saved items. Tested in Firefox 3 or higher.</li>
	<li>
		<a class="external" href="http://upload.jonathanwilsson.com/html5/sessionstorage.php" title="http://upload.jonathanwilsson.com/html5/sessionstorage.php">HTML5 Session Storage</a>. A very simple example of session storage. Also includes a example on local storage. Tested in Firefox 3.6 or higher.</li>
	<li>
		<a class="external" href="http://channy.creation.net/work/firefox/domstorage/"><strike>Basic DOMStorage Examples</strike></a><strike> - Broken in Firefox 3 and up due to use of globalStorage on one domain level up from the current domain which is not allowed in Firefox 3.</strike></li>
	<li>
		<a class="external" href="http://aaronboodman.com/halfnote/"><strike>halfnote</strike></a><strike> - (displaying broken in Firefox 3) Note writing application that uses DOM Storage.</strike></li>
</ul>
<h3 id="浏览器兼容性">
	浏览器兼容性</h3>
<p>
	{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
	<table class="compat-table">
		<tbody>
			<tr>
				<th>
					Feature</th>
				<th>
					Chrome</th>
				<th>
					Firefox (Gecko)</th>
				<th>
					Internet Explorer</th>
				<th>
					Opera</th>
				<th>
					Safari (WebKit)</th>
			</tr>
			<tr>
				<td>
					localStorage</td>
				<td>
					4</td>
				<td>
					3.5</td>
				<td>
					8</td>
				<td>
					10.50</td>
				<td>
					4</td>
			</tr>
			<tr>
				<td>
					sessionStorage</td>
				<td>
					5</td>
				<td>
					2</td>
				<td>
					8</td>
				<td>
					10.50</td>
				<td>
					4</td>
			</tr>
			<tr>
				<td>
					globalStorage</td>
				<td>
					{{ CompatNo() }}</td>
				<td>
					2-13</td>
				<td>
					{{ CompatNo() }}</td>
				<td>
					{{ CompatNo() }}</td>
				<td>
					{{ CompatNo() }}</td>
			</tr>
		</tbody>
	</table>
</div>
<div id="compat-mobile">
	<table class="compat-table">
		<tbody>
			<tr>
				<th>
					Feature</th>
				<th>
					Android</th>
				<th>
					Firefox Mobile (Gecko)</th>
				<th>
					IE Phone</th>
				<th>
					Opera Mobile</th>
				<th>
					Safari Mobile</th>
			</tr>
			<tr>
				<td>
					Basic support</td>
				<td>
					{{ CompatUnknown() }}</td>
				<td>
					{{ CompatUnknown() }}</td>
				<td>
					{{ CompatUnknown() }}</td>
				<td>
					{{ CompatUnknown() }}</td>
				<td>
					{{ CompatUnknown() }}</td>
			</tr>
		</tbody>
	</table>
</div>
<p>
	All browsers have varying capacity levels for both local- and sessionStorage. Here is a <a class="external" href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">detailed rundown of all the storage capacities for various browsers</a>.</p>
<p>
	 </p>
<h3 id="相关链接">
	相关链接</h3>
<ul>
	<li>
		<a class="external" href="http://en.wikipedia.org/wiki/HTTP_cookie">HTTP cookies</a> (<code><a href="/zh-cn/DOM/document.cookie" title="zh-cn/DOM/document.cookie">document.cookie</a></code>)</li>
	<li>
		<a class="external" href="http://www.macromedia.com/support/documentation/zh-cn/flashplayer/help/help02.html">Flash Local Storage</a></li>
	<li>
		<a class="external" href="http://msdn2.microsoft.com/en-us/library/ms531424.aspx">Internet Explorer userData behavior</a></li>
	<li>
		<a href="/zh-cn/XPCOM_Interface_Reference/nsIDOMStorageEventObsolete" title="zh-cn/XPCOM Interface Reference/nsIDOMStorageEventObsolete">nsIDOMStorageEventObsolete</a></li>
	<li>
		<a href="/zh-cn/DOM/event/StorageEvent" title="zh-cn/DOM/Event/StorageEvent">StorageEvent</a></li>
</ul>
<p>
	{{ HTML5ArticleTOC() }}</p>
<p>
	{{ languages( { "es": "es/DOM/Almacenamiento", "fr": "fr/DOM/Storage", "ja": "ja/DOM/Storage", "pl": "pl/DOM/Storage", "en": "en/DOM/Storage" } ) }}</p>
<p>
	---------------------------------</p>
<p>
	 </p>
<h3 id=".E6.91.98.E8.A6.81" name=".E6.91.98.E8.A6.81">
	摘要</h3>
<p>
	DOM Storage,就是在<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/">Web Applications 1.0</a> specification中介绍的那些<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#storage">存储相关特性</a>集合的名称。相比较在cookies中存储信息来说,DOM Stroage更大、更安全、更易于使用的。目前支持的浏览器包括Mozilla Firefox 2+, Google Chrome, Apple Safari, Opera和Microsoft IE9+,在移动设备上也包括iPhone &amp; iPad Safari。</p>
<div class="note">
	<strong>Note:</strong> DOM Storage 与 <a href="/cn/Storage" title="cn/Storage">mozStorage</a> (Mozilla对于SQLite的XPCOM接口)和<a href="/cn/Session_store_API" title="cn/Session_store_API">Session store API</a>(扩展使用的一个<a href="/cn/XPCOM" title="cn/XPCOM">XPCOM</a>存储).不同</div>
<h3 id=".E6.8F.8F.E8.BF.B0" name=".E6.8F.8F.E8.BF.B0">
	描述</h3>
<p>
	DOM Storage机制是一种通过字符串形式的名/值对来安全地存储和使用的方法。这个附加功能的目标是提供一个更全面的、可以创建交互式应用程序的方法(包括那些高级功能,例如可以离线工作一段时间)。</p>
<p>
	目前,只有基于Mozilla的浏览器提供了DOM Storage的实现。不过,Internet Explorer也有一个类似的特性,叫做"<a class="external" href="http://msdn.microsoft.com/workshop/author/behaviors/reference/behaviors/userdata.asp">userData behavior</a>",他允许你在多重浏览器会话中永久地保存数据。</p>
<p>
	DOM Storage 是很有用的,因为在任何一段时期都没有一个很好的、只通过浏览器来永久存储合理大小的数据的方法。<a class="external" href="http://en.wikipedia.org/wiki/HTTP_cookie">浏览器cookies</a> 限制了存储容量,而且并没有为组织永久性的数据提供支持,并且其他的方法还需要外部插件来实现(例如<a class="external" href="http://www.macromedia.com/support/documentation/zh-cn/flashplayer/help/help02.html">Flash Local Storage</a>)。</p>
<p>
	第一个使用了新的DOM Storage功能(除了Internet Explorer 的 userData Behavior之外)的公共应用程序是由 <a class="external" href="http://aaronboodman.com/">Aaron Boodman</a> 写的 <a class="external" href="http://aaronboodman.com/halfnote/">halfnote</a>(一个便签应用程序) 。在他的程序中,Aaron同时把便签内容保存到服务器上(当Internet连接可用时)和一个本地数据存储中。这就允许用户即便是在不定式发生internet连接中断时,也可以安全的写一些有备份的便签。</p>
<p>
	不过,在halfnote中表现出来的概念和实现,都还是相对简单的。它的诞生揭示了一种新的、可以在线或离线使用的网络应用程序。</p>
<h3 id=".E5.8F.82.E8.80.83" name=".E5.8F.82.E8.80.83">
	参考</h3>
<p>
	下面的内容都是作为每个<a href="/cn/DOM/window" title="cn/DOM/window"><code>window</code> 对象</a>的属性存在的全局对象。这也就是说,可以通过<code>sessionStorage</code> 或者 <code>window.sessionStorage</code> 来访问它们。(这很重要,因为随后你可以使用iframe来存储、访问、添加那些并不是立刻就包含在你页面中的数据。)</p>
<h4 id="sessionStorage" name="sessionStorage">
	<code>sessionStorage</code></h4>
<p>
	这是一个全局对象(<code>sessionStorage</code>),它含有一个在页面会话有效期内可用的存储区域。只要页面没有关闭,一个页面会话就始终保持着,并且当页面被重新载入或恢复时“复活”。打开一个新的标签页或新窗口都会初始化新的会话。</p>
<pre class="eval">// 将数据存入当前会话的一个存储中
sessionStorage.username = "John";

// 访问某些已存储的数据
alert( "username = " + sessionStorage.username );
</pre>
<p>
	<code>sessionStorage</code> 对象是最有用的,它持有那些应该保存的临时数据,而且一旦浏览器突然被刷新时,要恢复的那些数据,</p>
<div class="bug">
	<strong>Note:</strong> <code>sessionStorage</code> 还应该有在浏览器崩溃后存储和恢复数据的功能,不过由于{{ Bug(339445) }}的原因,这个功能到现在还没有在Firefox中实现。这个功能实现之后,<code>sessionStorage</code>的防御功能就十分有用了。</div>
<p>
	<strong>举例:</strong></p>
<p>
	自动保存文本字段的内容,如果浏览器突然被刷新,就恢复字段内容,这样就不会丢失任何输入了。</p>
<pre class="eval"> // 获得我们要跟踪的那个文本字段
 var field = document.getElementById("field");

 // 看看我们是否有一个autosave的值
 // (这将只会在页面被突然刷新时发生)
 if ( sessionStorage.autosave ) {
     // 恢复文本字段中的内容
     field.value = sessionStorage.autosave;
 }

 // 每秒钟检查一次文本字段的内容
 setInterval(function(){
     // 并把结果保存到会话存储对象中
     sessionStorage.autosave = field.value;
 }, 1000);
</pre>
<p>
	<strong>更多信息:</strong></p>
<ul>
	<li>
		<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#sessionstorage">sessionStorage specification</a></li>
</ul>
<h4 id="globalStorage" name="globalStorage">
	<code>globalStorage</code></h4>
<p>
	这是一个全局对象(<code>globalStorage</code>),它维护着各种公共的或者私有的,可以用来长时期保存数据的存储空间(例如,在多重的页面和浏览器会话之间)。</p>
<pre class="eval">// 可以这样访问那些仅对mozilla.org域上的脚本保存的数据
globalStorage['mozilla.org'].snippet = "&lt;b&gt;Hello&lt;/b&gt;, how are you?";

// 可以这样访问为任何网页任何域存储的数据
globalStorage[<span class="nowiki">''</span>].favBrowser = "Firefox";
</pre>
<p>
	特别地,<code>globalStorage</code>对象,提供了访问一些不同的可以保存数据的存储对象的方法。例如,如果我们要建立一个可以在域(developer.mozilla.org)下面可以使用<code>globalStorage</code>的网页,我们有下面这些存储对象可以使用:</p>
<ul>
	<li>
		<code>globalStorage{{ mediawiki.external('\'developer.mozilla.org\'') }}</code> - 在developer.mozilla.org下面所有的子域都可以通过这个存储对象来进行读和写。</li>
	<li>
		<code>globalStorage{{ mediawiki.external('\'mozilla.org\'') }}</code> - 在mozilla.org域名下面的所有网页都可以通过这个存储对象来进行读和写。</li>
	<li>
		<code>globalStorage{{ mediawiki.external('\'org\'') }}</code> - 在.org域名下面的所有网页都可以通过这个存储对象来进行读和写。</li>
	<li>
		<code>globalStorage{{ mediawiki.external('') }}</code> - 在任何域名下的任何网页都可以通过这个存储对象来进行读和写。</li>
</ul>
<div class="bug">
	<strong>注意:</strong> firefox目前还没有实现<code>globalStorage{{ mediawiki.external('tld') }}</code><code>globalStorage{{ mediawiki.external('') }}</code> (会抛出一个安全错误),这是由于对于这些名字空间可以进行随意读写的话是有安全漏洞的 <a class="external" href="http://ejohn.org/blog/dom-storage-answers/">更多信息</a></div>
<p>
	<strong>示例:</strong></p>
<p>
	下面这些示例,需要你在所有想看到效果的页面中都插入脚本(包括如下所有的代码)。</p>
<p>
	记录某个指定子域名下面正在访问的用户的username:</p>
<pre class="eval"> globalStorage['developer.mozilla.org'].username = "John";
</pre>
<p>
	跟踪一个用户在你的域名下所访问的所有页面的次数:</p>
<pre class="eval"> // 由于所有数据都是被当作一个字符串来保存的,所以这里必须使用parseInt
 globalStorage['mozilla.org'].visits =
     parseInt( globalStorage['mozilla.org'].visits || 0 ) + 1;
</pre>
<p>
	记录所有你访问的网站:</p>
<pre class="eval"> globalStorage[<span class="nowiki">''</span>].sites += "," + location.hostname;
</pre>
<p>
	<strong>更多信息:</strong></p>
<ul>
	<li>
		<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#globalstorage">globalStorage specification</a></li>
</ul>
<h3 id="More_information" name="More_information">
	More information</h3>
<ul>
	<li>
		<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/">Web Applications 1.0 Specification</a></li>
	<li>
		<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#storage">Web Applications 1.0 Storage Specification</a></li>
	<li>
		<a class="external" href="http://kb.mozillazine.org/Dom.storage.enabled">Enable/Disable DOM Storage in Firefox or SeaMonkey</a></li>
</ul>
<h3 id="Examples" name="Examples">
	Examples</h3>
<ul>
	<li>
		<a class="external" href="http://channy.creation.net/work/firefox/domstorage/">Basic DOMStorage Examples</a></li>
	<li>
		<a class="external" href="http://aaronboodman.com/halfnote/">halfnote</a> - Note writing application that uses DOM Storage.</li>
</ul>
<h3 id="Related" name="Related">
	Related</h3>
<ul>
	<li>
		<a class="external" href="http://en.wikipedia.org/wiki/HTTP_cookie">HTTP cookies</a> (<code><a href="/cn/DOM/document.cookie" title="cn/DOM/document.cookie">document.cookie</a></code>)</li>
	<li>
		<a class="external" href="http://www.macromedia.com/support/documentation/zh-cn/flashplayer/help/help02.html">Flash Local Storage</a></li>
	<li>
		<a class="external" href="http://msdn.microsoft.com/workshop/author/behaviors/reference/behaviors/userdata.asp">Internet Explorer userData behavior</a></li>
</ul>