www.fgks.org   »   [go: up one dir, main page]

Click to Rate and Give Feedback
HTML and DHTML Overviews and Tutori...
 Introduction to DOM Storage
Introduction to DOM Storage
New for Windows Internet Explorer 8
Note: This documentation is preliminary and is subject to change.

The DOM Storage API includes two related mechanisms for persisting client-side data in a secure manner using the Document Object Model (DOM), sessionStorage and globalStorage. These objects were introduced in Internet Explorer 8.

Note  For prior versions of Internet Explorer, persistent data storage is implemented by the userData behavior.

This topic contains the following sections.

What is DOM Storage?

DOM Storage is often compared to HTTP cookies. Like cookies, Web developers can store per-session or domain-specific data as name/value pairs on the client using DOM Storage. However, unlike cookies, DOM Storage makes it easier to control how information stored by one window is visible to another.

For example, a user might open two browser windows to buy airline tickets for two different flights. However, if the airline's Web application uses cookies to store its session state, information could "leak" from one transaction into the other, potentially causing the user to buy two tickets for the same flight without noticing. As applications become more capable of offline behaviors, such as storing values locally for later return to the server, the potential for this soft of information "leak" becomes more prevalent.

DOM Storage also offers significantly more disk space than cookies. In Internet Explorer, cookies can store only 4 kilobyte (KB) of data. This byte total can be one name/value pair of 4 KB, or it can be up to 20 name/value pairs that have a total size of 4 KB. By comparison, DOM Storage provides roughly 10 megabytes (MB) for each storage area.

Functionally, client storage areas are quite different from cookies. DOM Storage doesn't transmit values to the server with every request as cookies do, nor does the data in a global storage area ever expire. And unlike cookies, it is easy to access individual pieces of data using a standard interface that has growing support among browser vendors.

DOM Storage Scripting Objects

window.sessionStorage

Session storage is designed for scenarios where the user is carrying out a single transaction. The sessionStorage attribute of the window object maintains key/value pairs for all pages loaded during the lifetime of a single tab (for the duration of the top-level browsing context). For example, a page might have a check box that the user selects to indicate that he wants insurance:

<label>
    <input type="checkbox" >
    I want insurance on this trip.
</label>

A later page could then check, from script, whether the user had selected the check box:

if (sessionStorage.insurance) { ... } 

The Storage object supports expando properties ('insurance' in the example above). If the property name does not exist, a key/value pair is automatically created to hold it. Note that key/value pairs are always stored as strings. Different data types such as numbers, Boolean values, and structured data must first be converted to strings before persisting to a storage area.

Once a value has been saved to sessionStorage, it can be retrieved by script running in another page in the same context. When another document is loaded, sessionStorage is initialized from memory for same-origin URLs. (See Security and Privacy section for more information.)

Note  Although it is allowed by the HTML 5 (Working Draft) World Wide Web link, Internet Explorer 8 does not resume sessionStorage after browser crash recovery.

window.globalStorage

The global storage mechanism spans multiple windows and persists beyond the current session. The globalStorage attribute provides persistent storage areas for domains. It allows Web applications to store nearly 10 MB of user data, such as entire documents or a user's mailbox, on the client for performance reasons.

For example, a Web site can display a count of how many times the user has visited a page with the following script.

<p>
  You have viewed this page
  <span id="count">an untold number of</span>
  time(s).
</p>
<script>
  var storage = globalStorage[location.hostname];
  if (!storage.pageLoadCount) storage.pageLoadCount = 0;
  storage.pageLoadCount = parseInt(storage.pageLoadCount, 10) + 1;
  document.getElementById('count').innerHTML = storage.pageLoadCount;
</script> 

Note  Before incrementing pageLoadCount it must first be converted to a number with the parseInt Method (JScript 5.6) World Wide Web link.

Each domain and subdomain has its own separate global storage area. Domains can access the storage areas of subdomains, and subdomains can access the storage areas of parent domains. For example, globalStorage['example.com'] is accessible to example.com and any of its subdomains. The subdomain globalStorage['www.example.com'] is accessible to example.com, but not to other subdomains, such as mail.example.com.

The Storage Object

The following properties and methods are supported by both session and global storage objects.

begin Method

Marks the beginning of a global storage transaction.

clear Method

Removes all key/value pairs from the DOM Storage area.

commit Method

Writes pending changes to persistent storage.

getItem Method

Retrieves the current value associated with the DOM Storage key.

key Method

Retrieves the key at the specified index in the collection.

length Property

Retrieves the length of the key/value list.

remainingSpace Property

Retrieves the remaining memory space, in bytes, for the storage object.

removeItem Method

Deletes a key/value pair from the DOM Storage collection.

setItem Method

Sets a key/value pair.

DOM Storage Events

Internet Explorer fires events when data in a storage area is updated, so that information can synchronized between multiple instances of the browser or tabs.

The following events are supported.

onstorage

The onstorage event is fired in an document when a storage area changes. All documents sharing the same session context, and those that are currently displaying a page from the same domain or subdomain where global storage is being committed, receive the event. The domain property of the event indicates which storage area was updated.

<script>
document.attachEvent('onstorage', function(e) {
    // Check domain attribute of event for top-level context.
    alert('Updated: ' + e.domain);
});
</script> 

If the target document object is not currently active, Internet Explorer does not fire any events.

onstoragecommit

Internet Explorer uses XML files to store global storage. The onstoragecommit event fires when a global storage is written to disk. Like onstorage, the domain property indicates which global storage area was updated.

Note  Disk writes occur asynchronously; however, to provide fine-grained control of data consistency, the begin and commit methods can be used to defer disk writes.

Security and Privacy

The data stored in global storage is much more public than that stored in cookies, which can be limited to a certain path within a domain. Even picking a hard-to-guess key won't provide any privacy because the Storage object provides a way to enumerate them.

Here are some things to consider:

Top-Level Browsing Context and Origin

Access to the session storage area is restricted by the top-level browsing context. In Internet Explorer, a new browsing context is created for every tab. Script running in one top-level browsing context has no access to storage created in another. Sites can add data to the session storage, and it will be accessible to any page from that origin opened in the same window.

Origin is determined by the protocol, hostname (or IP address), and port number of the document's URL. Script access to storage data is permitted only if the script origin matches that of the storage area.

HTTPS and Secure Values

If a key/value pair is created from a URL using the https:// protocol scheme, the value is automatically marked as secure. Attempts to read a secure value from an unsecured URL are not permitted, unless the item's secure property has been set to false. Script running in a secure context can set this value to enable data sharing between secure and unsecure domains.

Origin Determines Storage Limits

Disk quota limits are imposed against the domain of the page that sets the value, rather than the domain where the value is being set. This prevents malicious scripts from using up the storage quota of a related domain. It also prevents such scripts from using random subdomains to store unrestricted amounts of data.

Storage size is calculated as the total length of all key names and values, and a single storage area can contain up to 10 million bytes. The remainingSpace property is used to determine the available disk space.

Clearing the Storage Areas

Session state is released as soon as the last window to reference that data is closed. However, users can clear storage areas at any time by selecting Delete Browsing History from the Tools menu in Internet Explorer, selecting the Cookies check box, and clicking OK. This clears session and global storage areas for all domains that are not in the Favorites folder and resets the storage quotas in the registry. Clear the Preserve Favorite Site Data check box to delete all storage areas, regardless of source.

To delete key/value pairs from a storage list, iterate over the collection with removeItem or use clear. Keep in mind that changes to a global storage area are saved to disk asynchronously; if data consistency is an issue, use begin and commit to process several changes in one transaction.

Related Topics

Tags What's this?: Add a tag
Community Content
 
Add Community Content
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker
DCSIMG