1. 11 Web storage
    1. 11.1 Introduction
    2. 11.2 The API
      1. 11.2.1 The Storage interface
      2. 11.2.2 The sessionStorage attribute
      3. 11.2.3 The localStorage attribute
      4. 11.2.4 The storage event
        1. The StorageEvent interface
    3. 11.3 Disk space
    4. 11.4 Privacy
      1. 11.4.1 User tracking
    5. 11.5 Security
      1. 11.5.1 DNS spoofing attacks
      2. 11.5.2 Cross-directory attacks

11 Web storage

11.1 Introduction

This specification introduces two related mechanisms, similar to HTTP session cookies, for storing name-value pairs on the client side. [COOKIES]

The first is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different windows at the same time.

Cookies don't really handle this case well. For example, a user could be buying plane tickets in two different windows, using the same site. If the site used cookies to keep track of which ticket the user was buying, then as the user clicked from page to page in both windows, the ticket currently being purchased would "leak" from one window to the other, potentially causing the user to buy two tickets for the same flight without really noticing.

To address this, this specification introduces the sessionStorage IDL attribute. Sites can add data to the session storage, and it will be accessible to any page from the same site opened in that window.

For example, a page could have a checkbox that the user ticks to indicate that they want insurance:

 <input type="checkbox" onchange="sessionStorage.insurance = checked ? 'true' : ''">
  I want insurance on this trip.

A later page could then check, from script, whether the user had checked the checkbox or not:

if (sessionStorage.insurance) { ... }

If the user had multiple windows opened on the site, each one would have its own individual copy of the session storage object.

The second storage mechanism is designed for storage that spans multiple windows, and lasts beyond the current session. In particular, Web applications might wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.

Again, cookies do not handle this case well, because they are transmitted with every request.

The localStorage IDL attribute is used to access a page's local storage area.

The site at example.com can display a count of how many times the user has loaded its page by putting the following at the bottom of its page:

  You have viewed this page
  <span id="count">an untold number of</span>
  if (!localStorage.pageLoadCount)
    localStorage.pageLoadCount = 0;
  localStorage.pageLoadCount = parseInt(localStorage.pageLoadCount) + 1;
  document.getElementById('count').textContent = localStorage.pageLoadCount;

Each site has its own separate storage area.

11.2 The API

Support: namevalue-storageChrome for Android 81+Chrome 4+iOS Safari 3.2+Safari 4+Firefox 3.5+Samsung Internet 4+Edge 12+UC Browser for Android 12.12+IE 8+Opera 10.5+Opera Mini NoneFirefox for Android 68+

Source: caniuse.com

11.2.1 The Storage interface

Each Storage object provides access to a list of key/value pairs, which are sometimes called items. Keys are strings. Any string (including the empty string) is a valid key. Values are similarly strings.

Each Storage object is associated with a list of key/value pairs when it is created, as defined in the sections on the sessionStorage and localStorage attributes. Multiple separate objects implementing the Storage interface can all be associated with the same list of key/value pairs simultaneously.

storage . length

Returns the number of key/value pairs currently present in the list associated with the object.

storage . key ( n )

Returns the name of the nth key in the list, or null if n is greater than or equal to the number of key/value pairs in the object.

value = storage . getItem ( key )
value = storage[key]

Returns the current value associated with the given key, or null if the given key does not exist in the list associated with the object.

storage . setItem ( key, value )
storage[key] = value

Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.

Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)

storage . removeItem ( key )
delete storage[key]

Removes the key/value pair with the given key from the list associated with the object, if a key/value pair with the given key exists.

storage . clear()

Empties the list associated with the object of all key/value pairs, if there are any.

When the setItem(), removeItem(), and clear() methods are invoked, events are fired on the relevant global objects of other Document objects that can access the newly stored or removed data, as defined in the sections on the sessionStorage and localStorage attributes.

This specification does not require that the above methods wait until the data has been physically written to disk. Only consistency in what different scripts accessing the same underlying list of key/value pairs see is required.

11.2.2 The sessionStorage attribute

The sessionStorage attribute represents the set of storage areas specific to the current top-level browsing context.

window . sessionStorage

Returns the Storage object associated with that origin's session storage area.

Each top-level browsing context has a unique set of session storage areas, one for each origin.

User agents should not expire data from a browsing context's session storage areas, but may do so when the user requests that such data be deleted, or when the UA detects that it has limited storage space, or for security reasons. User agents should always avoid deleting data while a script that could access that data is running. When a top-level browsing context is destroyed (and therefore permanently inaccessible to the user) the data stored in its session storage areas can be discarded with it, as the API described in this specification provides no way for that data to ever be subsequently retrieved.

When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a session storage area, if the methods did not throw an exception or "do nothing" as defined above, then for every Document object whose relevant global object's sessionStorage attribute's Storage object is associated with the same storage area, other than x, user agents send a storage notification.

11.2.3 The localStorage attribute

The localStorage object provides a Storage object for an origin.

window . localStorage

Returns the Storage object associated with that origin's local storage area.

Throws a "SecurityError" DOMException if the Document's origin is an opaque origin or if the request violates a policy decision (e.g. if the user agent is configured to not allow the page to persist data).

When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a local storage area, if the methods did not throw an exception or "do nothing" as defined above, then for every Document object whose relevant global object's localStorage attribute's Storage object is associated with the same storage area, other than x, user agents send a storage notification.

The localStorage attribute provides access to shared state. This specification does not define the interaction with other browsing contexts in a multiprocess user agent, and authors are encouraged to assume that there is no locking mechanism. A site could, for instance, try to read the value of a key, increment its value, then write it back out, using the new value as a unique identifier for the session; if the site does this twice in two different browser windows at the same time, it might end up using the same "unique" identifier for both sessions, with potentially disastrous effects.

11.2.4 The storage event

The storage event is fired on a Document object's relevant global object when a storage area changes, as described in the previous two sections (for session storage, for local storage). The StorageEvent interface
event . key

Returns the key of the storage item being changed.

event . oldValue

Returns the old value of the key of the storage item whose value is being changed.

event . newValue

Returns the new value of the key of the storage item whose value is being changed.

event . url

Returns the URL of the document whose storage item changed.

event . storageArea

Returns the Storage object that was affected.

11.3 Disk space

User agents should limit the total amount of space allowed for storage areas, because hostile authors could otherwise use this feature to exhaust the user's available disk space.

User agents should guard against sites storing data under their origin's other affiliated sites, e.g. storing up to the limit in a1.example.com, a2.example.com, a3.example.com, etc, circumventing the main example.com storage limit.

User agents may prompt the user when quotas are reached, allowing the user to grant a site more space. This enables sites to store many user-created documents on the user's computer, for instance.

User agents should allow users to see how much space each domain is using.

A mostly arbitrary limit of five megabytes per origin is suggested. Implementation feedback is welcome and will be used to update this suggestion in the future.

For predictability, quotas should be based on the uncompressed size of data stored.

11.4 Privacy

11.4.1 User tracking

A third-party advertiser (or any entity capable of getting content distributed to multiple sites) could use a unique identifier stored in its local storage area to track a user across multiple sessions, building a profile of the user's interests to allow for highly targeted advertising. In conjunction with a site that is aware of the user's real identity (for example an e-commerce site that requires authenticated credentials), this could allow oppressive groups to target individuals with greater accuracy than in a world with purely anonymous Web usage.

There are a number of techniques that can be used to mitigate the risk of user tracking:

Blocking third-party storage

User agents may restrict access to the localStorage objects to scripts originating at the domain of the active document of the top-level browsing context, for instance denying access to the API for pages from other domains running in iframes.

Expiring stored data

User agents may, possibly in a manner configured by the user, automatically delete stored data after a period of time.

For example, a user agent could be configured to treat third-party local storage areas as session-only storage, deleting the data once the user had closed all the browsing contexts that could access it.

This can restrict the ability of a site to track a user, as the site would then only be able to track the user across multiple sessions when they authenticate with the site itself (e.g. by making a purchase or logging in to a service).

However, this also reduces the usefulness of the API as a long-term storage mechanism. It can also put the user's data at risk, if the user does not fully understand the implications of data expiration.

Treating persistent storage as cookies

If users attempt to protect their privacy by clearing cookies without also clearing data stored in the local storage area, sites can defeat those attempts by using the two features as redundant backup for each other. User agents should present the interfaces for clearing these in a way that helps users to understand this possibility and enables them to delete data in all persistent storage features simultaneously. [COOKIES]

Site-specific safelisting of access to local storage areas

User agents may allow sites to access session storage areas in an unrestricted manner, but require the user to authorize access to local storage areas.

Origin-tracking of stored data

User agents may record the origins of sites that contained content from third-party origins that caused data to be stored.

If this information is then used to present the view of data currently in persistent storage, it would allow the user to make informed decisions about which parts of the persistent storage to prune. Combined with a blocklist ("delete this data and prevent this domain from ever storing data again"), the user can restrict the use of persistent storage to sites that they trust.

Shared blocklists

User agents may allow users to share their persistent storage domain blocklists.

This would allow communities to act together to protect their privacy.

While these suggestions prevent trivial use of this API for user tracking, they do not block it altogether. Within a single domain, a site can continue to track the user during a session, and can then pass all this information to the third party along with any identifying information (names, credit card numbers, addresses) obtained by the site. If a third party cooperates with multiple sites to obtain such information, a profile can still be created.

However, user tracking is to some extent possible even with no cooperation from the user agent whatsoever, for instance by using session identifiers in URLs, a technique already commonly used for innocuous purposes but easily repurposed for user tracking (even retroactively). This information can then be shared with other sites, using visitors' IP addresses and other user-specific data (e.g. user-agent headers and configuration settings) to combine separate sessions into coherent user profiles.

11.5 Security

11.5.1 DNS spoofing attacks

Because of the potential for DNS spoofing attacks, one cannot guarantee that a host claiming to be in a certain domain really is from that domain. To mitigate this, pages can use TLS. Pages using TLS can be sure that only the user, software working on behalf of the user, and other pages using TLS that have certificates identifying them as being from the same domain, can access their storage areas.

11.5.2 Cross-directory attacks

Different authors sharing one host name, for example users hosting content on the now defunct geocities.com, all share one local storage object. There is no feature to restrict the access by pathname. Authors on shared hosts are therefore urged to avoid using these features, as it would be trivial for other authors to read the data and overwrite it.

Even if a path-restriction feature was made available, the usual DOM scripting security model would make it trivial to bypass this protection and access the data from any path.