Some interfaces and behaviours used in browsers such as History or Location.

This specification is an experimental breakup of the HTML specification. You can see the full list on the index page and take part in the discussion in the repository.

Documents

Every XML and HTML document in an HTML UA is represented by a Document object. [[!DOM]]

The document's address is the URL associated with a Document (as defined in the DOM standard). It is initially set when the Document is created, but that can change during the lifetime of the Document; for example, it changes when the user navigates to a fragment identifier on the page and when the pushState() method is called with a new URL. [[!DOM]]

Interactive user agents typically expose the document's address in their user interface. This is the primary mechanism by which a user can tell if a site is attempting to impersonate another.

When a Document is created by a script using the createDocument() or createHTMLDocument() APIs, the document's address is the same as the document's address of the responsible document specified by the script's settings object, and the Document is both ready for post-load tasks and completely loaded immediately.

The document's referrer is an absolute URL that can be set when the Document is created. If it is not explicitly set, then its value is the empty string.

Each Document object has a reload override flag that is originally unset. The flag is set by the document.open() and document.write() methods in certain situations. When the flag is set, the Document also has a reload override buffer which is a Unicode string that is used as the source of the document when it is reloaded.

When the user agent is to perform an overridden reload, given a source browsing context, it must act as follows:

  1. Let source be the value of the browsing context's active document's reload override buffer.

  2. Let address be the browsing context's active document's address.

  3. Navigate the browsing context to a resource whose source is source, with replacement enabled and exceptions enabled. The source browsing context is that given to the overridden reload algorithm. When the navigate algorithm creates a Document object for this purpose, set that Document's reload override flag and set its reload override buffer to source.

    When it comes time to set the document's address in the navigation algorithm, use address as the override URL.

The Document object

The DOM specification defines a Document interface, which this specification extends significantly:

enum DocumentReadyState { "loading", "interactive", "complete" };

[OverrideBuiltins]
partial /*sealed*/ interface Document {
  // resource metadata management
  [PutForwards=href, Unforgeable] readonly attribute Location? location;
  attribute DOMString domain;
  readonly attribute DOMString referrer;
  attribute DOMString cookie;
  readonly attribute DOMString lastModified;
  readonly attribute DocumentReadyState readyState;

  // DOM tree accessors
  getter object (DOMString name);
  attribute DOMString title;
  attribute DOMString dir;
  attribute HTMLElement? body;
  readonly attribute HTMLHeadElement? head;
  [SameObject] readonly attribute HTMLCollection images;
  [SameObject] readonly attribute HTMLCollection embeds;
  [SameObject] readonly attribute HTMLCollection plugins;
  [SameObject] readonly attribute HTMLCollection links;
  [SameObject] readonly attribute HTMLCollection forms;
  [SameObject] readonly attribute HTMLCollection scripts;
  NodeList getElementsByName(DOMString elementName);
  NodeList getItems(optional DOMString typeNames = ""); // microdata
  [SameObject] readonly attribute DOMElementMap cssElementMap;
  readonly attribute HTMLScriptElement? currentScript;

  // dynamic markup insertion
  Document open(optional DOMString type = "text/html", optional DOMString replace = "");
  WindowProxy open(DOMString url, DOMString name, DOMString features, optional boolean replace = false);
  void close();
  void write(DOMString... text);
  void writeln(DOMString... text);

  // user interaction
  readonly attribute WindowProxy? defaultView;
  readonly attribute Element? activeElement;
  boolean hasFocus();
  attribute DOMString designMode;
  boolean execCommand(DOMString commandId, optional boolean showUI = false, optional DOMString value = "");
  boolean queryCommandEnabled(DOMString commandId);
  boolean queryCommandIndeterm(DOMString commandId);
  boolean queryCommandState(DOMString commandId);
  boolean queryCommandSupported(DOMString commandId);
  DOMString queryCommandValue(DOMString commandId);
  readonly attribute HTMLCollection commands;

  // special event handler IDL attributes that only apply to Document objects
  [LenientThis] attribute EventHandler onreadystatechange;

  // also has obsolete members
};
Document implements GlobalEventHandlers;

Resource metadata management

document . referrer

Returns the address of the Document from which the user navigated to this one, unless it was blocked or there was no such document, in which case it returns the empty string.

The noreferrer link type can be used to block the referrer.

The referrer attribute must return the document's referrer.

In the case of HTTP, the referrer IDL attribute will match the Referer (sic) header that was sent when fetching the current page.

Typically user agents are configured to not report referrers in the case where the referrer uses an encrypted protocol and the current page does not (e.g. when navigating from an https: page to an http: page).


document . cookie [ = value ]

Returns the HTTP cookies that apply to the Document. If there are no cookies or cookies can't be applied to this resource, the empty string will be returned.

Can be set, to add a new cookie to the element's set of HTTP cookies.

If the contents are sandboxed into a unique origin (e.g. in an iframe with the sandbox attribute), a SecurityError exception will be thrown on getting and setting.

The cookie attribute represents the cookies of the resource identified by the document's address.

A Document object that falls into one of the following conditions is a cookie-averse Document object:

On getting, if the document is a cookie-averse Document object, then the user agent must return the empty string. Otherwise, if the Document's origin is not a scheme/host/port tuple, the user agent must throw a SecurityError exception. Otherwise, the user agent must first obtain the storage mutex and then return the cookie-string for the document's address for a "non-HTTP" API, decoded using the UTF-8 decoder. [[!COOKIES]] (This is a fingerprinting vector.)

On setting, if the document is a cookie-averse Document object, then the user agent must do nothing. Otherwise, if the Document's origin is not a scheme/host/port tuple, the user agent must throw a SecurityError exception. Otherwise, the user agent must obtain the storage mutex and then act as it would when receiving a set-cookie-string for the document's address via a "non-HTTP" API, consisting of the new value encoded as UTF-8. [[!COOKIES]] [[!ENCODING]]

Since the cookie attribute is accessible across frames, the path restrictions on cookies are only a tool to help manage which cookies are sent to which parts of the site, and are not in any way a security feature.


document . lastModified

Returns the date of the last modification to the document, as reported by the server, in the form "MM/DD/YYYY hh:mm:ss", in the user's local time zone.

If the last modification date is not known, the current time is returned instead.

The lastModified attribute, on getting, must return the date and time of the Document's source file's last modification, in the user's local time zone, in the following format:

  1. The month component of the date.
  2. A U+002F SOLIDUS character (/).
  3. The day component of the date.
  4. A U+002F SOLIDUS character (/).
  5. The year component of the date.
  6. A U+0020 SPACE character.
  7. The hours component of the time.
  8. A U+003A COLON character (:).
  9. The minutes component of the time.
  10. A U+003A COLON character (:).
  11. The seconds component of the time.

All the numeric components above, other than the year, must be given as two ASCII digits representing the number in base ten, zero-padded if necessary. The year must be given as the shortest possible string of four or more ASCII digits representing the number in base ten, zero-padded if necessary.

The Document's source file's last modification date and time must be derived from relevant features of the networking protocols used, e.g. from the value of the HTTP Last-Modified header of the document, or from metadata in the file system for local files. If the last modification date and time are not known, the attribute must return the current date and time in the above format.


document . readyState

Returns "loading" while the Document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.

The readystatechange event fires on the Document object when this value changes.

Each document has a current document readiness. When a Document object is created, it must have its current document readiness set to the string "loading" if the document is associated with an HTML parser, an XML parser, or an XSLT processor, and to the string "complete" otherwise. Various algorithms during page loading affect this value. When the value is set, the user agent must fire a simple event named readystatechange at the Document object.

A Document is said to have an active parser if it is associated with an HTML parser or an XML parser that has not yet been stopped or aborted.

The readyState IDL attribute must, on getting, return the current document readiness.

DOM tree accessors

The html element of a document is the document's root element, if there is one and it's an html element, or null otherwise.


document . head

Returns the head element.

The head element of a document is the first head element that is a child of the html element, if there is one, or null otherwise.

The head attribute, on getting, must return the head element of the document (a head element or null).


document . title [ = value ]

Returns the document's title, as given by the title element for HTML and as given by the SVG title element for SVG.

Can be set, to update the document's title. If there is no appropriate element to update, the new value is ignored.

The title element of a document is the first title element in the document (in tree order), if there is one, or null otherwise.

The title attribute must, on getting, run the following algorithm:

  1. If the root element is an svg element in the SVG namespace, then let value be a concatenation of the data of all the child Text nodes of the first title element in the SVG namespace that is a child of the root element. [[!SVG]]

  2. Otherwise, let value be a concatenation of the data of all the child Text nodes of the title element, in tree order, or the empty string if the title element is null.

  3. Strip and collapse whitespace in value.

  4. Return value.

On setting, the steps corresponding to the first matching condition in the following list must be run:

If the root element is an svg element in the SVG namespace [[!SVG]]
  1. Let element be the first title element in the SVG namespace that is a child of the root element, if any. If there isn't one, create a title element in the SVG namespace, append it to the root element, and let element be that element. [[!SVG]]

  2. Act as if the textContent IDL attribute of element was set to the new value being assigned.

If the root element is in the HTML namespace
  1. If the title element is null and the head element is null, then abort these steps.

  2. If the title element is null, then create a new title element and append it to the head element, and let element be the newly created element; otherwise, let element be the title element.

  3. Act as if the textContent IDL attribute of element was set to the new value being assigned.

Otherwise

Do nothing.


document . body [ = value ]

Returns the body element.

Can be set, to replace the body element.

If the new value is not a body or frameset element, this will throw a HierarchyRequestError exception.

The body element of a document is the first child of the html element that is either a body element or a frameset element. If there is no such element, it is null.

The body attribute, on getting, must return the body element of the document (either a body element, a frameset element, or null). On setting, the following algorithm must be run:

  1. If the new value is not a body or frameset element, then throw a HierarchyRequestError exception and abort these steps.
  2. Otherwise, if the new value is the same as the body element, do nothing. Abort these steps.
  3. Otherwise, if the body element is not null, then replace that element with the new value in the DOM, as if the root element's replaceChild() method had been called with the new value and the incumbent body element as its two arguments respectively, then abort these steps.
  4. Otherwise, if there is no root element, throw a HierarchyRequestError exception and abort these steps.
  5. Otherwise, the body element is null, but there's a root element. Append the new value to the root element.

document . images

Returns an HTMLCollection of the img elements in the Document.

document . embeds
document . plugins

Return an HTMLCollection of the embed elements in the Document.

document . links

Returns an HTMLCollection of the a and area elements in the Document that have href attributes.

document . forms

Return an HTMLCollection of the form elements in the Document.

document . scripts

Return an HTMLCollection of the script elements in the Document.

The images attribute must return an HTMLCollection rooted at the Document node, whose filter matches only img elements.

The embeds attribute must return an HTMLCollection rooted at the Document node, whose filter matches only embed elements.

The plugins attribute must return the same object as that returned by the embeds attribute.

The links attribute must return an HTMLCollection rooted at the Document node, whose filter matches only a elements with href attributes and area elements with href attributes.

The forms attribute must return an HTMLCollection rooted at the Document node, whose filter matches only form elements.

The scripts attribute must return an HTMLCollection rooted at the Document node, whose filter matches only script elements.


collection = document . getElementsByName(name)

Returns a NodeList of elements in the Document that have a name attribute with the value name.

The getElementsByName(name) method takes a string name, and must return a live NodeList containing all the HTML elements in that document that have a name attribute whose value is equal to the name argument (in a case-sensitive manner), in tree order. When the method is invoked on a Document object again with the same argument, the user agent may return the same as the object returned by the earlier call. In other cases, a new NodeList object must be returned.


element . cssElementMap

Returns a DOMElementMap object for the Document representing the current CSS element reference identifiers.

The cssElementMap IDL attribute allows authors to define CSS element reference identifiers, which are used in certain CSS features to override the normal ID-based mapping. [[!CSSIMAGES]]

When a Document is created, it must be associated with an initially-empty CSS ID overrides list, which consists of a list of mappings each of which consists of a string name mapped to an Element node.

Each entry in the CSS ID overrides list, while it is in the list and is either in the Document or is an img, video, or canvas element, defines a CSS element reference identifier mapping the given name to the given Element. [[!CSSIMAGES]]

On getting, the cssElementMap IDL attribute must return a DOMElementMap object, associated with the following algorithms, which expose the current mappings:

The algorithm for getting the list of name-element mappings

Return the Document's CSS ID overrides list, maintaining the order in which the entries were originally added to the list.

The algorithm for mapping a name to a certain element

Let name be the name passed to the algorithm and element be the Element passed to the algorithm.

If element is null, run the algorithm for deleting mappings by name, passing it name.

Otherwise, if there is an entry in the Document's CSS ID overrides list whose name is name, replace its current value with element.

Otherwise, add a mapping to the Document's CSS ID overrides list whose name is name and whose element is element.

The algorithm for deleting mappings by name

If there is an entry in the Document's CSS ID overrides list whose name is the name passed to this algorithm, remove it. This also undefines the CSS element reference identifier for that name. [[!CSSIMAGES]]


document . currentScript

Returns the script element that is currently executing. In the case of reentrant script execution, returns the one that most recently started executing amongst those that have not yet finished executing.

Returns null if the Document is not currently executing a script element (e.g. because the running script is an event handler, or a timeout).

The currentScript attribute, on getting, must return the value to which it was most recently initialised. When the Document is created, the currentScript must be initialised to null.


The Document interface supports named properties. The supported property names at any moment consist of the values of the name content attributes of all the applet, exposed embed, form, iframe, img, and exposed object elements in the Document that have non-empty name content attributes, and the values of the id content attributes of all the applet and exposed object elements in the Document that have non-empty id content attributes, and the values of the id content attributes of all the img elements in the Document that have both non-empty name content attributes and non-empty id content attributes. The supported property names must be in tree order, ignoring later duplicates, with values from id attributes coming before values from name attributes when the same element contributes both.

To determine the value of a named property name when the Document object is indexed for property retrieval, the user agent must return the value obtained using the following steps:

  1. Let elements be the list of named elements with the name name in the Document.

    There will be at least one such element, by definition.

  2. If elements has only one element, and that element is an iframe element, then return the WindowProxy object of the nested browsing context represented by that iframe element, and abort these steps.

  3. Otherwise, if elements has only one element, return that element and abort these steps.

  4. Otherwise return an HTMLCollection rooted at the Document node, whose filter matches only named elements with the name name.

Named elements with the name name, for the purposes of the above algorithm, are those that are either:

An embed or object element is said to be exposed if it has no exposed object ancestor, and, for object elements, is additionally either not showing its fallback content or has no object or embed descendants.


The dir attribute on the Document interface is defined along with the dir content attribute.

Loading XML documents

partial interface XMLDocument {
  boolean load(DOMString url);
};

The load(url) method must run the following steps:

  1. Let document be the XMLDocument object on which the method was invoked.

  2. Resolve the method's first argument, relative to the API base URL specified by the entry settings object. If this is not successful, throw a SyntaxError exception and abort these steps. Otherwise, let url be the resulting absolute URL.

  3. If the origin of url is not the same as the origin of document, throw a SecurityError exception and abort these steps.

  4. Remove all child nodes of document, without firing any mutation events.

  5. Set the current document readiness of document to "loading".

  6. Run the remainder of these steps in parallel, and return true from the method.

  7. Let result be a Document object.

  8. Let success be false.

  9. Fetch url from the origin of document, using the referrer source specified by the entry settings object, with the blocking flag set and the force same-origin flag set.

  10. If the fetch attempt was successful, and the resource's Content-Type metadata is an XML MIME type, then run these substeps:

    1. Create a new XML parser associated with the result document.

    2. Pass this parser the fetched document.

    3. If there is an XML well-formedness or XML namespace well-formedness error, then remove all child nodes from result. Otherwise let success be true.

  11. Queue a task to run the following steps.

    1. Set the current document readiness of document to "complete".

    2. Replace all the children of document by the children of result (even if it has no children), firing mutation events as if a DocumentFragment containing the new children had been inserted.

    3. Fire a simple event named load at document.

Browsing contexts

A browsing context is an environment in which Document objects are presented to the user.

A tab or window in a Web browser typically contains a browsing context, as does an iframe or frames in a frameset.

Each browsing context has a corresponding WindowProxy object.

A browsing context has a session history, which lists the Document objects that that browsing context has presented, is presenting, or will present. At any time, one Document in each browsing context is designated the active document. A Document's browsing context is that browsing context whose session history contains the Document, if any. (A Document created using an API such as createDocument() has no browsing context.)

Each Document in a browsing context is associated with a Window object. A browsing context's WindowProxy object forwards everything to the browsing context's active document's Window object.

In general, there is a 1-to-1 mapping from the Window object to the Document object. There are two exceptions. First, a Window can be reused for the presentation of a second Document in the same browsing context, such that the mapping is then 1-to-2. This occurs when a browsing context is navigated from the initial about:blank Document to another, with replacement enabled. Second, a Document can end up being reused for several Window objects when the document.open() method is used, such that the mapping is then many-to-1.

A Document does not necessarily have a browsing context associated with it. In particular, data mining tools are likely to never instantiate browsing contexts.


A browsing context can have a creator browsing context, the browsing context that was responsible for its creation. If a browsing context has a parent browsing context, then that is its creator browsing context. Otherwise, if the browsing context has an opener browsing context, then that is its creator browsing context. Otherwise, the browsing context has no creator browsing context.

If a browsing context A has a creator browsing context, then the Document that was the active document of that creator browsing context at the time A was created is the creator Document.

Creating a browsing context: When a browsing context is first created, it must be created with a single Document in its session history, whose address is about:blank, which is marked as being an HTML document, whose character encoding is UTF-8, and which is both ready for post-load tasks and completely loaded immediately, along with a new Window object that the Document is associated with. The Document must have a single child html node, which itself has two empty child nodes: a head element, and a body element. As soon as this Document is created, the user agent must implement the sandboxing for it. If the browsing context has a creator Document, then the browsing context's Document's referrer must be set to the address of that creator Document at the time of the browsing context's creation.

If the browsing context is created specifically to be immediately navigated, then that initial navigation will have replacement enabled.

The origin and effective script origin of the about:blank Document are set when the Document is created. If the new browsing context has a creator browsing context, then the origin of the about:blank Document is an alias to the origin of the creator Document and the effective script origin of the about:blank Document is initially an alias to the effective script origin of the creator Document. Otherwise, the origin of the about:blank Document is a globally unique identifier assigned when the new browsing context is created and the effective script origin of the about:blank Document is initially an alias to its origin.

Nested browsing contexts

Certain elements (for example, iframe elements) can instantiate further browsing contexts. These are called nested browsing contexts. If a browsing context P has a Document D with an element E that nests another browsing context C inside it, then C is said to be nested through D, and E is said to be the browsing context container of C. If the browsing context container element E is in the Document D, then P is said to be the parent browsing context of C and C is said to be a child browsing context of P. Otherwise, the nested browsing context C has no parent browsing context.

A browsing context A is said to be an ancestor of a browsing context B if there exists a browsing context A' that is a child browsing context of A and that is itself an ancestor of B, or if the browsing context A is the parent browsing context of B.

A browsing context that is not a nested browsing context has no parent browsing context, and is the top-level browsing context of all the browsing contexts for which it is an ancestor browsing context.

The transitive closure of parent browsing contexts for a nested browsing context gives the list of ancestor browsing contexts.

The list of the descendant browsing contexts of a Document d is the (ordered) list returned by the following algorithm:

  1. Let list be an empty list.

  2. For each child browsing context of d that is nested through an element that is in the Document d, in the tree order of the elements nesting those browsing contexts, run these substeps:

    1. Append that child browsing context to the list list.

    2. Append the list of the descendant browsing contexts of the active document of that child browsing context to the list list.

  3. Return the constructed list.

A Document is said to be fully active when it is the active document of its browsing context, and either its browsing context is a top-level browsing context, or it has a parent browsing context and the Document through which it is nested is itself fully active.

Because they are nested through an element, child browsing contexts are always tied to a specific Document in their parent browsing context. User agents must not allow the user to interact with child browsing contexts of elements that are in Documents that are not themselves fully active.

A nested browsing context can have a seamless browsing context flag set, if it is embedded through an iframe element with a seamless attribute.

A nested browsing context can be put into a delaying load events mode. This is used when it is navigated, to delay the load event of the browsing context container before the new Document is created.

The document family of a browsing context consists of the union of all the Document objects in that browsing context's session history and the document families of all those Document objects. The document family of a Document object consists of the union of all the document families of the browsing contexts that are nested through the Document object.

Navigating nested browsing contexts in the DOM

window . top

Returns the WindowProxy for the top-level browsing context.

window . parent

Returns the WindowProxy for the parent browsing context.

window . frameElement

Returns the Element for the browsing context container.

Returns null if there isn't one.

Throws a SecurityError exception in cross-origin situations.

The top IDL attribute on the Window object of a Document in a browsing context b must return the WindowProxy object of its top-level browsing context (which would be its own WindowProxy object if it was a top-level browsing context itself), if it has one, or its own WindowProxy object otherwise (e.g. if it was a detached nested browsing context).

The parent IDL attribute on the Window object of a Document in a browsing context b must return the WindowProxy object of the parent browsing context, if there is one (i.e. if b is a child browsing context), or the WindowProxy object of the browsing context b itself, otherwise (i.e. if it is a top-level browsing context or a detached nested browsing context).

The frameElement IDL attribute on the Window object of a Document d, on getting, must run the following algorithm:

  1. If d is not a Document in a nested browsing context, return null and abort these steps.

  2. If the browsing context container's node document does not have the same effective script origin as the effective script origin specified by the entry settings object, then throw a SecurityError exception and abort these steps.

  3. Return the browsing context container for b.

Auxiliary browsing contexts

It is possible to create new browsing contexts that are related to a top-level browsing context without being nested through an element. Such browsing contexts are called auxiliary browsing contexts. Auxiliary browsing contexts are always top-level browsing contexts.

An auxiliary browsing context has an opener browsing context, which is the browsing context from which the auxiliary browsing context was created.

Navigating auxiliary browsing contexts in the DOM

The opener IDL attribute on the Window object, on getting, must return the WindowProxy object of the browsing context from which the current browsing context was created (its opener browsing context), if there is one, if it is still available, and if the current browsing context has not disowned its opener; otherwise, it must return null. On setting, if the new value is null then the current browsing context must disown its opener; if the new value is anything else then the user agent must call the [[\DefineOwnProperty]] internal method of the Window object, passing the property name "opener" as the property key, and the Property Descriptor { [[\Value]]: value, [[\Writable]]: true, [[\Enumerable]]: true, [[\Configurable]]: true } as the property descriptor, where value is the new value.

Secondary browsing contexts

User agents may support secondary browsing contexts, which are browsing contexts that form part of the user agent's interface, apart from the main content area.

Security

A browsing context A is familiar with a second browsing context B if one of the following conditions is true:


A browsing context A is allowed to navigate a second browsing context B if the following algorithm terminates positively:

  1. If A is not the same browsing context as B, and A is not one of the ancestor browsing contexts of B, and B is not a top-level browsing context, and A's active document's active sandboxing flag set has its sandboxed navigation browsing context flag set, then abort these steps negatively.

  2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, and A's node document's active sandboxing flag set has its sandboxed top-level navigation browsing context flag set, then abort these steps negatively.

  3. Otherwise, if B is a top-level browsing context, and is neither A nor one of the ancestor browsing contexts of A, and A's Document's active sandboxing flag set has its sandboxed navigation browsing context flag set, and A is not the one permitted sandboxed navigator of B, then abort these steps negatively.

  4. Otherwise, terminate positively!


An element has a browsing context scope origin if its Document's browsing context is a top-level browsing context or if all of its Document's ancestor browsing contexts all have active documents whose origin are the same origin as the element's node document's origin. If an element has a browsing context scope origin, then its value is the origin of the element's node document.

Groupings of browsing contexts

Each browsing context is defined as having a list of one or more directly reachable browsing contexts. These are:

The transitive closure of all the browsing contexts that are directly reachable browsing contexts forms a unit of related browsing contexts.

Each unit of related browsing contexts is then further divided into the smallest number of groups such that every member of each group has an active document with an effective script origin that, through appropriate manipulation of the document.domain attribute, could be made to be the same as other members of the group, but could not be made the same as members of any other group. Each such group is a unit of related similar-origin browsing contexts.

There is also at most one event loop per unit of related similar-origin browsing contexts (though several units of related similar-origin browsing contexts can have a shared event loop).

Browsing context names

Browsing contexts can have a browsing context name. By default, a browsing context has no name (its name is not set).

A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)

A valid browsing context name or keyword is any string that is either a valid browsing context name or that is an ASCII case-insensitive match for one of: _blank, _self, _parent, or _top.

These values have different meanings based on whether the page is sandboxed or not, as summarised in the following (non-normative) table. In this table, "current" means the browsing context that the link or script is in, "parent" means the parent browsing context of the one the link or script is in, "master" means the nearest ancestor browsing context of the one the link or script is in that is not itself in a seamless iframe, "top" means the top-level browsing context of the one the link or script is in, "new" means a new top-level browsing context or auxiliary browsing context is to be created, subject to various user preferences and user agent policies, "none" means that nothing will happen, and "maybe new" means the same as "new" if the "allow-popups" keyword is also specified on the sandbox attribute (or if the user overrode the sandboxing), and the same as "none" otherwise.

Keyword Ordinary effect Effect in an iframe with...
seamless="" sandbox="" sandbox="" seamless="" sandbox="allow-top-navigation" sandbox="allow-top-navigation" seamless=""
none specified, for links and form submissions current master current master current master
empty string current master current master current master
_blank new new maybe new maybe new maybe new maybe new
_self current current current current current current
_parent if there isn't a parent current current current current current current
_parent if parent is also top parent/top parent/top none none parent/top parent/top
_parent if there is one and it's not top parent parent none none none none
_top if top is current current current current current current current
_top if top is not current top top none none top top
name that doesn't exist new new maybe new maybe new maybe new maybe new
name that exists and is a descendant specified descendant specified descendant specified descendant specified descendant specified descendant specified descendant
name that exists and is current current current current current current current
name that exists and is an ancestor that is top specified ancestor specified ancestor none none specified ancestor/top specified ancestor/top
name that exists and is an ancestor that is not top specified ancestor specified ancestor none none none none
other name that exists with common top specified specified none none none none
name that exists with different top, if familiar and one permitted sandboxed navigator specified specified specified specified specified specified
name that exists with different top, if familiar but not one permitted sandboxed navigator specified specified none none none none
name that exists with different top, not familiar new new maybe new maybe new maybe new maybe new

Most of the restrictions on sandboxed browsing contexts are applied by other algorithms, e.g. the navigation algorithm, not the rules for choosing a browsing context given a browsing context name given below.


An algorithm is allowed to show a popup if any of the following conditions is true:


The rules for choosing a browsing context given a browsing context name are as follows. The rules assume that they are being applied in the context of a browsing context, as part of the execution of a task.

  1. If the given browsing context name is the empty string or _self, then the chosen browsing context must be the current one.

    If the given browsing context name is _self, then this is an explicit self-navigation override, which overrides the behaviour of the seamless browsing context flag set by the seamless attribute on iframe elements.

  2. If the given browsing context name is _parent, then the chosen browsing context must be the parent browsing context of the current one, unless there isn't one, in which case the chosen browsing context must be the current browsing context.

  3. If the given browsing context name is _top, then the chosen browsing context must be the top-level browsing context of the current one, if there is one, or else the current browsing context.

  4. If the given browsing context name is not _blank and there exists a browsing context whose name is the same as the given browsing context name, and the current browsing context is familiar with that browsing context, and the user agent determines that the two browsing contexts are related enough that it is ok if they reach each other, then that browsing context must be the chosen one. If there are multiple matching browsing contexts, the user agent should select one in some arbitrary consistent manner, such as the most recently opened, most recently focused, or more closely related.

    If the browsing context is chosen by this step to be the current browsing context, then this is also an explicit self-navigation override.

  5. Otherwise, a new browsing context is being requested, and what happens depends on the user agent's configuration and abilities — it is determined by the rules given for the first applicable option from the following list:

    There is no chosen browsing context. The user agent may inform the user that a popup has been blocked.

    If the current browsing context's active document's active sandboxing flag set has the sandboxed auxiliary navigation browsing context flag set.

    Typically, there is no chosen browsing context.

    The user agent may offer to create a new top-level browsing context or reuse an existing top-level browsing context. If the user picks one of those options, then the designated browsing context must be the chosen one (the browsing context's name isn't set to the given browsing context name). The default behaviour (if the user agent doesn't offer the option to the user, or if the user declines to allow a browsing context to be used) must be that there must not be a chosen browsing context.

    If this case occurs, it means that an author has explicitly sandboxed the document that is trying to open a link.

    If the user agent has been configured such that in this instance it will create a new browsing context, and the browsing context is being requested as part of following a hyperlink whose link types include the noreferrer keyword

    A new top-level browsing context must be created. If the given browsing context name is not _blank, then the new top-level browsing context's name must be the given browsing context name (otherwise, it has no name). The chosen browsing context must be this new browsing context. The creation of such a browsing context is a new start for session storage.

    If it is immediately navigated, then the navigation will be done with replacement enabled.

    If the user agent has been configured such that in this instance it will create a new browsing context, and the noreferrer keyword doesn't apply

    A new auxiliary browsing context must be created, with the opener browsing context being the current one. If the given browsing context name is not _blank, then the new auxiliary browsing context's name must be the given browsing context name (otherwise, it has no name). The chosen browsing context must be this new browsing context.

    If it is immediately navigated, then the navigation will be done with replacement enabled.

    If the user agent has been configured such that in this instance it will reuse the current browsing context

    The chosen browsing context is the current browsing context.

    If the user agent has been configured such that in this instance it will not find a browsing context

    There must not be a chosen browsing context.

    User agent implementors are encouraged to provide a way for users to configure the user agent to always reuse the current browsing context.

    If the current browsing context's active document's active sandboxing flag set has the sandboxed navigation browsing context flag set and the chosen browsing context picked above, if any, is a new browsing context (whether top-level or auxiliary), then all the flags that are set in the current browsing context's active document's active sandboxing flag set when the new browsing context is created must be set in the new browsing context's popup sandboxing flag set, and the current browsing context must be set as the new browsing context's one permitted sandboxed navigator.

The Window object

[PrimaryGlobal] 
/*sealed*/ interface Window : EventTarget {
  // the current browsing context
  [Unforgeable] readonly attribute WindowProxy window;
  [Replaceable] readonly attribute WindowProxy self;
  [Unforgeable] readonly attribute Document document;
  attribute DOMString name; 
  [PutForwards=href, Unforgeable] readonly attribute Location location;
  readonly attribute History history;
  [Replaceable] readonly attribute BarProp locationbar;
  [Replaceable] readonly attribute BarProp menubar;
  [Replaceable] readonly attribute BarProp personalbar;
  [Replaceable] readonly attribute BarProp scrollbars;
  [Replaceable] readonly attribute BarProp statusbar;
  [Replaceable] readonly attribute BarProp toolbar;
  attribute DOMString status;
  void close();
  readonly attribute boolean closed;
  void stop();
  void focus();
  void blur();

  // other browsing contexts
  [Replaceable] readonly attribute WindowProxy frames;
  [Replaceable] readonly attribute unsigned long length;
  [Unforgeable] readonly attribute WindowProxy top;
  attribute any opener;
  [Replaceable] readonly attribute WindowProxy parent;
  readonly attribute Element? frameElement;
  WindowProxy open(optional DOMString url = "about:blank", optional DOMString target = "_blank", [TreatNullAs=EmptyString] optional DOMString features = "", optional boolean replace = false);
  getter WindowProxy (unsigned long index);
  getter object (DOMString name);

  // the user agent
  readonly attribute Navigator navigator; 
  [Replaceable, SameObject] readonly attribute External external;
  readonly attribute ApplicationCache applicationCache;

  // user prompts
  void alert();
  void alert(DOMString message);
  boolean confirm(optional DOMString message = "");
  DOMString? prompt(optional DOMString message = "", optional DOMString default = "");
  void print();
  any showModalDialog(DOMString url, optional any argument); // deprecated

  long requestAnimationFrame(FrameRequestCallback callback);
  void cancelAnimationFrame(long handle);

  void postMessage(any message, DOMString targetOrigin, optional sequence<Transferable> transfer);

  // also has obsolete members
};
Window implements GlobalEventHandlers;
Window implements WindowEventHandlers;
window . window
window . frames
window . self

These attributes all return window.

window . document

Returns the Document associated with window.

document . defaultView

Returns the Window object of the active document.

The window, frames, and self IDL attributes must all return the Window object's browsing context's WindowProxy object.

The document IDL attribute must return the Window object's newest Document object.

The Document object associated with a Window object can change in exactly one case: when the navigate algorithm initialises a new Document object for the first page loaded in a browsing context. In that specific case, the Window object of the original about:blank page is reused and gets a new Document object.

The defaultView IDL attribute of the Document interface must return the Document's browsing context's WindowProxy object, if there is one, or null otherwise.


For historical reasons, Window objects must also have a writable, configurable, non-enumerable property named HTMLDocument whose value is the Document interface object.

Security

This section describes a security model that is underdefined, imperfect, and does not match implementations. Work is ongoing to attempt to resolve this, but in the meantime, please do not rely on this section for precision. Implementors are urged to send their feedback on how cross-origin cross-global access to Window and Location objects should work. See bug 20701.

User agents must throw a SecurityError exception whenever any properties of a Window object are accessed when the incumbent settings object specifies an effective script origin that is not the same as the Window object's Document's effective script origin, with the following exceptions:

When the incumbent settings object specifies an effective script origin that is different than a Window object's Document's effective script origin, the user agent must act as if any changes to that Window object's properties, getters, setters, etc, were not present, and as if all the properties of that Window object had their [[\Enumerable]] attribute set to false.

For members that return objects (including function objects), each distinct effective script origin that is not the same as the Window object's Document's effective script origin must be provided with a separate set of objects. These objects must have the prototype chain appropriate for the script for which the objects are created (not those that would be appropriate for scripts whose global object, as specified by their settings object, is the Window object in question).

For instance, if two frames containing Documents from different origins access the same Window object's postMessage() method, they will get distinct objects that are not equal.

APIs for creating and navigating browsing contexts by name

window = window . open( [ url [, target [, features [, replace ] ] ] ] )

Opens a window to show url (defaults to about:blank), and returns it. The target argument gives the name of the new window. If a window exists with that name already, it is reused. The replace attribute, if true, means that whatever page is currently open in that window will be removed from the window's session history. The features argument can be used to influence the rendering of the new window.

window . name [ = value ]

Returns the name of the window.

Can be set, to change the name.

window . close()

Closes the window.

window . closed

Returns true if the window has been closed, false otherwise.

window . stop()

Cancels the document load.

The open() method on Window objects provides a mechanism for navigating an existing browsing context or opening and navigating an auxiliary browsing context.

When the method is invoked, the user agent must run the following steps:

  1. Let entry settings be the entry settings object when the method was invoked.

  2. Let url be the first argument.

  3. Let target be the second argument.

  4. Let features be the third argument.

  5. Let replace be the fourth argument.

  6. Let source browsing context be the responsible browsing context specified by entry settings.

  7. If target is the empty string, let it be the string "_blank" instead.

  8. If the user has indicated a preference for which browsing context to navigate, follow these substeps:

    1. Let target browsing context be the browsing context indicated by the user.

    2. If target browsing context is a new top-level browsing context, let the source browsing context be set as target browsing context's one permitted sandboxed navigator.

    For example, suppose there is a user agent that supports control-clicking a link to open it in a new tab. If a user clicks in that user agent on an element whose onclick handler uses the window.open() API to open a page in an iframe, but, while doing so, holds the control key down, the user agent could override the selection of the target browsing context to instead target a new tab.

    Otherwise, apply the rules for choosing a browsing context given a browsing context name using target as the name and source browsing context as the context in which the algorithm is executed. If this results in there not being a chosen browsing context, then throw an InvalidAccessError exception and abort these steps. Otherwise, let target browsing context be the browsing context so obtained.

  9. If target browsing context was just created, either as part of the rules for choosing a browsing context given a browsing context name or due to the user indicating a preference for navigating a new top-level browsing context, then let new be true. Otherwise, let it be false.

  10. Interpret features as defined in the CSSOM View specification. [[!CSSOMVIEW]]

  11. If url is the empty string, run the appropriate steps from the following list:

    If new is false

    Jump to the step labeled end.

    If new is true

    Let resource be the URL "about:blank".

    Otherwise, resolve url relative to the API base URL specified by entry settings, and let resource be the resulting absolute URL, if any. If the resolve a URL algorithm failed, then run one of the following two steps instead:

    • Let resource be a resource representing an inline error page.

    • If new is false, jump to the step labeled end, otherwise, let resource be the URL "about:blank".

  12. If resource is "about:blank" and new is true, queue a task to fire a simple event named load at target browsing context's Window object, with target override set to target browsing context's Window object's Document object.

    Otherwise, navigate target browsing context to resource, with exceptions enabled. If new is true, then replacement must be enabled also. The source browsing context is source browsing context.

  13. End: Return the WindowProxy object of target browsing context.


The name attribute of the Window object must, on getting, return the current name of the browsing context, if one is set, or the empty string otherwise; and, on setting, set the name of the browsing context to the new value.

The name gets reset when the browsing context is navigated to another domain.


The close() method on Window objects should, if all the following conditions are met, close the browsing context A:

A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a top-level browsing context whose session history contains only one Document.

The closed attribute on Window objects must return true if the Window object's browsing context has been discarded, and false otherwise.

The stop() method on Window objects should, if there is an existing attempt to navigate the browsing context and that attempt is not currently running the unload a document algorithm, cancel that navigation; then, it must abort the active document of the browsing context of the Window object on which it was invoked.

Accessing other browsing contexts

window . length

Returns the number of child browsing contexts.

window[index]

Returns the indicated child browsing context.

The length IDL attribute on the Window interface must return the number of child browsing contexts that are nested through elements that are in the Document that is the active document of that Window object, if that Window's browsing context shares the same event loop as the responsible document specified by the entry settings object accessing the IDL attribute; otherwise, it must return zero.

The supported property indices on the Window object at any instant are the numbers in the range 0 .. n-1, where n is the number returned by the length IDL attribute. If n is zero then there are no supported property indices.

To determine the value of an indexed property index of a Window object, the user agent must return the WindowProxy object of the indexth child browsing context of the Document that is nested through an element that is in the Document, sorted in the order that the elements nesting those browsing contexts were most recently inserted into the Document, the WindowProxy object of the most recently inserted browsing context container's nested browsing context being last.

These properties are the dynamic nested browsing context properties.

Named access on the Window object

window[name]

Returns the indicated element or collection of elements.

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:

To determine the value of a named property name when the Window object is indexed for property retrieval, the user agent must return the value obtained using the following steps:

  1. Let objects be the list of named objects with the name name in the active document.

    There will be at least one such object, by definition.

  2. If objects contains a nested browsing context, then return the WindowProxy object of the nested browsing context corresponding to the first browsing context container in tree order whose browsing context is in objects, and abort these steps.

  3. Otherwise, if objects has only one element, return that element and abort these steps.

  4. Otherwise return an HTMLCollection rooted at the Document node, whose filter matches only named objects with the name name. (By definition, these will all be elements.)

Named objects with the name name, for the purposes of the above algorithm, are those that are either:

Garbage collection and browsing contexts

A browsing context has a strong reference to each of its Documents and its WindowProxy object, and the user agent itself has a strong reference to its top-level browsing contexts.

A Document has a strong reference to its Window object.

A Window object has a strong reference to its Document object through its document attribute. Thus, references from other scripts to either of those objects will keep both alive. Similarly, both Document and Window objects have implied strong references to the WindowProxy object.

Each script has a strong reference to its settings object, and each environment settings object has strong references to its global object, responsible browsing context, and responsible document (if any).

When a browsing context is to discard a Document, the user agent must run the following steps:

  1. Set the Document's salvageable state to false.

  2. Run any unloading document cleanup steps for the Document that are defined by this specification and other applicable specifications.

  3. Abort the Document.

  4. Remove any tasks associated with the Document in any task source, without running those tasks.

  5. Discard all the child browsing contexts of the Document.

  6. Lose the strong reference from the Document's browsing context to the Document.

Whenever a Document object is discarded, it is also removed from the list of the worker's Documents of each worker whose list contains that Document.

When a browsing context is discarded, the strong reference from the user agent itself to the browsing context must be severed, and all the Document objects for all the entries in the browsing context's session history must be discarded as well.

User agents may discard top-level browsing contexts at any time (typically, in response to user requests, e.g. when a user force-closes a window containing one or more top-level browsing contexts). Other browsing contexts must be discarded once their WindowProxy object is eligible for garbage collection.

Closing browsing contexts

When the user agent is required to close a browsing context, it must run the following steps:

  1. Let specified browsing context be the browsing context being closed.

  2. Prompt to unload the active document of the specified browsing context. If the user refused to allow the document to be unloaded, then abort these steps.

  3. Unload the active document of the specified browsing context with the recycle parameter set to false.

  4. Remove the specified browsing context from the user interface (e.g. close or hide its tab in a tabbed browser).

  5. Discard the specified browsing context.

User agents should offer users the ability to arbitrarily close any top-level browsing context.

Browser interface elements

To allow Web pages to integrate with Web browsers, certain Web browser interface elements are exposed in a limited way to scripts in Web pages.

Each interface element is represented by a BarProp object:

interface BarProp {
  attribute boolean visible;
};
window . locationbar . visible

Returns true if the location bar is visible; otherwise, returns false.

window . menubar . visible

Returns true if the menu bar is visible; otherwise, returns false.

window . personalbar . visible

Returns true if the personal bar is visible; otherwise, returns false.

window . scrollbars . visible

Returns true if the scroll bars are visible; otherwise, returns false.

window . statusbar . visible

Returns true if the status bar is visible; otherwise, returns false.

window . toolbar . visible

Returns true if the toolbar is visible; otherwise, returns false.

The visible attribute, on getting, must return either true or a value determined by the user agent to most accurately represent the visibility state of the user interface element that the object represents, as described below. On setting, the new value must be discarded.

The following BarProp objects exist for each Document object in a browsing context. Some of the user interface elements represented by these objects might have no equivalent in some user agents; for those user agents, except when otherwise specified, the object must act as if it was present and visible (i.e. its visible attribute must return true).

The location bar BarProp object
Represents the user interface element that contains a control that displays the URL of the active document, or some similar interface concept.
The menu bar BarProp object
Represents the user interface element that contains a list of commands in menu form, or some similar interface concept.
The personal bar BarProp object
Represents the user interface element that contains links to the user's favorite pages, or some similar interface concept.
The scrollbar BarProp object
Represents the user interface element that contains a scrolling mechanism, or some similar interface concept.
The status bar BarProp object
Represents a user interface element found immediately below or after the document, as appropriate for the user's media, which typically provides information about ongoing network activity or information about elements that the user's pointing device is current indicating. If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e. its visible attribute may return false).
The toolbar BarProp object
Represents the user interface element found immediately above or before the document, as appropriate for the user's media, which typically provides session history traversal controls (back and forward buttons, reload buttons, etc). If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e. its visible attribute may return false).

The locationbar attribute must return the location bar BarProp object.

The menubar attribute must return the menu bar BarProp object.

The personalbar attribute must return the personal bar BarProp object.

The scrollbars attribute must return the scrollbar BarProp object.

The statusbar attribute must return the status bar BarProp object.

The toolbar attribute must return the toolbar BarProp object.


For historical reasons, the status attribute on the Window object must, on getting, return the last string it was set to, and on setting, must set itself to the new value. When the Window object is created, the attribute must be set to the empty string. It does not do anything else.

The WindowProxy object

As mentioned earlier, each browsing context has a WindowProxy object. This object is unusual in that all operations that would be performed on it must be performed on the Window object of the browsing context's active document instead. It is thus indistinguishable from that Window object in every way until the browsing context is navigated.

There is no WindowProxy interface object.

The WindowProxy object allows scripts to act as if each browsing context had a single Window object, while still keeping separate Window objects for each Document.

In the following example, the variable x is set to the WindowProxy object returned by the window accessor on the global object. All of the expressions following the assignment return true, because in every respect, the WindowProxy object acts like the underlying Window object.

var x = window;
x instanceof Window; // true
x === this; // true

Origin

Origins are the fundamental currency of the Web's security model. Two actors in the Web platform that share an origin are assumed to trust each other and to have the same authority. Actors with differing origins are considered potentially hostile versus each other, and are isolated from each other to varying degrees.

For example, if Example Bank's Web site, hosted at bank.example.com, tries to examine the DOM of Example Charity's Web site, hosted at charity.example.org, a SecurityError exception will be raised.


The origin of a resource and the effective script origin of a resource are each one of the following:

Opaque identifiers

Internal values, with no serialisation, for which the only meaningful operation is testing for equality.

Tuples

Tuples consisting of a scheme component, a host component, a port component, and optionally extra data.

The extra data could include the certificate of the site when using encrypted connections, to ensure that if the site's secure certificate changes, the origin is considered to change as well.

Aliases

A reference to another origin or effective script origin.

An origin or effective script origin can be defined as an alias to another origin or effective script origin. The value of the origin or effective script origin is then the value of the origin or effective script origin to which it is an alias.

These characteristics are defined as follows:

For URLs

The origin and effective script origin of the URL are the URL origin defined in the WHATWG URL standard. [[!URL]]

For Document objects
If a Document's active sandboxing flag set has its sandboxed origin browsing context flag set

The origin is a globally unique identifier assigned when the Document is created.

The effective script origin is initially an alias to the origin of the Document.

If a Document was served over the network and has an address that uses a URL scheme with a server-based naming authority

The origin is an alias to the origin of the Document's address.

The effective script origin is initially an alias to the origin of the Document.

If a Document was generated from a data: URL found in another Document or in a script

The origin is an alias to the origin specified by the incumbent settings object when the navigate algorithm was invoked, or, if no script was involved, of the node document of the element that initiated the navigation to that URL.

The effective script origin is initially an alias to the effective script origin of that same environment settings object or Document.

If a Document is the initial "about:blank" document

The origin and effective script origin of the Document are those it was assigned when its browsing context was created.

If a Document was created as part of the processing for javascript: URLs

The origin is an alias to the origin of the active document of the browsing context being navigated when the navigate algorithm was invoked.

The effective script origin is initially an alias to the effective script origin of that same Document.

If a Document is an iframe srcdoc document

The origin of the Document is an alias to the origin of the Document's browsing context's browsing context container's node document.

The effective script origin is initially an alias to the effective script origin of the Document's browsing context's browsing context container's node document.

If a Document was obtained in some other manner (e.g. a data: URL typed in by the user or that was returned as the location of an HTTP redirect (or equivalent in other protocols), a Document created using the createDocument() API, etc)

The default behaviour as defined in the DOM standard applies. [[!DOM]].

The origin is a globally unique identifier assigned when the Document is created, and the effective script origin is initially an alias to the origin of the Document.

The effective script origin of a Document can be manipulated using the document.domain IDL attribute.

For images of img elements
If the image data is CORS-cross-origin
The origin is a globally unique identifier assigned when the image is created.
If the image data is CORS-same-origin
The origin is an alias to the origin of the img element's node document.

Images do not have an effective script origin.

For audio and video elements
If the media data is CORS-cross-origin
The origin is a globally unique identifier assigned when the media data is fetched.
If the media data is CORS-same-origin
The origin is an alias to the origin of the media element's node document.

Media elements do not have an effective script origin.

For fonts

The origin of a downloadable Web font is an alias to the origin of the absolute URL used to obtain the font (after any redirects). [[!CSSFONTS]] [[!CSSFONTLOAD]]

The origin of a locally installed system font is an alias to the origin of the Document in which that font is being used.

Fonts do not have an effective script origin.

Other specifications can override the above definitions by themselves specifying the origin of a particular URL, Document, image, media element, or font.


The Unicode serialisation of an origin is the string obtained by applying the following algorithm to the given origin:

  1. If the origin in question is not a scheme/host/port tuple, then return the literal string "null" and abort these steps.

  2. Otherwise, let result be the scheme part of the origin tuple.

  3. Append the string "://" to result.

  4. Apply the domain to Unicode algorithm to each component of the host part of the origin tuple, and append the results — each component, in the same order, separated by U+002E FULL STOP characters (.) — to result. [[!URL]]

  5. If the port part of the origin tuple gives a port that is different from the default port for the protocol given by the scheme part of the origin tuple, then append a U+003A COLON character (:) and the given port, in base ten, to result.

  6. Return result.

The ASCII serialisation of an origin is the string obtained by applying the following algorithm to the given origin:

  1. If the origin in question is not a scheme/host/port tuple, then return the literal string "null" and abort these steps.

  2. Otherwise, let result be the scheme part of the origin tuple.

  3. Append the string "://" to result.

  4. Apply the domain to ASCII algorithm to each component of the host part of the origin tuple, and append the results — each component, in the same order, separated by U+002E FULL STOP characters (.) — to result. [[!URL]]

    If the domain to ASCII algorithm returns failure, e.g. because a component is too long or because it contains invalid characters, then throw a SecurityError exception and abort these steps.

  5. If the port part of the origin tuple gives a port that is different from the default port for the protocol given by the scheme part of the origin tuple, then append a U+003A COLON character (:) and the given port, in base ten, to result.

  6. Return result.

Two origins are said to be the same origin if the following algorithm returns true:

  1. Let A be the first origin being compared, and B be the second origin being compared.

  2. If A and B are both opaque identifiers, and their value is equal, then return true.

  3. Otherwise, if either A or B or both are opaque identifiers, return false.

  4. If A and B have scheme components that are not identical, return false.

  5. If A and B have host components that are not identical, return false.

  6. If A and B have port components that are not identical, return false.

  7. If either A or B have additional data, but that data is not identical for both, return false.

  8. Return true.

Relaxing the same-origin restriction

document . domain [ = domain ]

Returns the current domain used for security checks.

Can be set to a value that removes subdomains, to change the effective script origin to allow pages on other subdomains of the same domain (if they do the same thing) to access each other. (Can't be set in sandboxed iframes.)

The domain attribute on Document objects must be initialised to the document's domain, if it has one, and the empty string otherwise. If the document's domain starts with a U+005B LEFT SQUARE BRACKET character ([) and ends with a U+005D RIGHT SQUARE BRACKET character (]), it is an IPv6 address; these square brackets must be omitted when initialising the attribute's value.

On getting, the attribute must return its current value, unless the Document has no browsing context, in which case it must return the empty string.

On setting, the user agent must run the following algorithm:

  1. If the Document has no browsing context, throw a SecurityError exception and abort these steps.

  2. If the Document's active sandboxing flag set has its sandboxed document.domain browsing context flag set, throw a SecurityError exception and abort these steps.

  3. If the new value is an IPv4 or IPv6 address, let new value be the new value.

    Otherwise, strictly split the new value on U+002E FULL STOP characters (.), apply the domain to ASCII algorithm to each returned token, and let new value be the result of concatenating the results of applying that algorithm to each token, in the same order, separated by U+002E FULL STOP characters (.). [[!URL]]

    If the domain to ASCII algorithm returns failure, e.g. because a component is too long or because it contains invalid characters, then throw a SecurityError exception and abort these steps.

  4. If new value is not exactly equal to the current value of the document.domain attribute, then run these substeps:

    1. If the current value is an IPv4 or IPv6 address, throw a SecurityError exception and abort these steps.

    2. If new value, prefixed by a U+002E FULL STOP (.), does not exactly match the end of the current value, throw a SecurityError exception and abort these steps.

      If the new value is an IPv4 or IPv6 address, it cannot match the new value in this way and thus an exception will be thrown here.

    3. If new value matches a suffix in the Public Suffix List, or, if new value, prefixed by a U+002E FULL STOP (.), matches the end of a suffix in the Public Suffix List, then throw a SecurityError exception and abort these steps. [[!PSL]]

      Suffixes must be compared in an ASCII case-insensitive manner, after applying the domain to ASCII algorithm to their individual components, . [[!URL]]

  5. Release the storage mutex.

  6. Set the attribute's value to new value.

  7. If the effective script origin of the Document is an alias, set it to the value of the effective script origin (essentially de-aliasing the effective script origin).

  8. If new value is not the empty string, then run these substeps:

    1. Set the host part of the effective script origin tuple of the Document to new value.

    2. Set the port part of the effective script origin tuple of the Document to "manual override" (a value that, for the purposes of comparing origins, is identical to "manual override" but not identical to any other value).

The domain of a Document is the host part of the document's origin, if the value of that origin is a scheme/host/port tuple. If it isn't, then the document does not have a domain.

The domain attribute is used to enable pages on different hosts of a domain to access each others' DOMs.

Do not use the document.domain attribute when using shared hosting. If an untrusted third party is able to host an HTTP server at the same IP address but on a different port, then the same-origin protection that normally protects two different sites on the same host will fail, as the ports are ignored when comparing origins after the document.domain attribute has been used.

Sandboxing

A sandboxing flag set is a set of zero or more of the following flags, which are used to restrict the abilities that potentially untrusted resources have:

The sandboxed navigation browsing context flag

This flag prevents content from navigating browsing contexts other than the sandboxed browsing context itself (or browsing contexts further nested inside it), auxiliary browsing contexts (which are protected by the sandboxed auxiliary navigation browsing context flag defined next), and the top-level browsing context (which is protected by the sandboxed top-level navigation browsing context flag defined below).

If the sandboxed auxiliary navigation browsing context flag is not set, then in certain cases the restrictions nonetheless allow popups (new top-level browsing contexts) to be opened. These browsing contexts always have one permitted sandboxed navigator, set when the browsing context is created, which allows the browsing context that created them to actually navigate them. (Otherwise, the sandboxed navigation browsing context flag would prevent them from being navigated even if they were opened.)

The sandboxed auxiliary navigation browsing context flag

This flag prevents content from creating new auxiliary browsing contexts, e.g. using the target attribute, the window.open() method, or the showModalDialog() method.

The sandboxed top-level navigation browsing context flag

This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context.

When the sandboxed top-level navigation browsing context flag is not set, content can navigate its top-level browsing context, but other browsing contexts are still protected by the sandboxed navigation browsing context flag and possibly the sandboxed auxiliary navigation browsing context flag.

The sandboxed plugins browsing context flag

This flag prevents content from instantiating plugins, whether using the embed element, the object element, the applet element, or through navigation of a nested browsing context, unless those plugins can be secured.

The sandboxed seamless iframes flag

This flag prevents content from using the seamless attribute on descendant iframe elements.

This prevents a page inserted using the allow-same-origin keyword from using a CSS-selector-based method of probing the DOM of other pages on the same site (in particular, pages that contain user-sensitive information).

The sandboxed origin browsing context flag

This flag forces content into a unique origin, thus preventing it from accessing other content from the same origin.

This flag also prevents script from reading from or writing to the document.cookie IDL attribute, and blocks access to localStorage.

The sandboxed forms browsing context flag

This flag blocks form submission.

The sandboxed pointer lock browsing context flag

This flag disables the Pointer Lock API. [[!POINTERLOCK]]

The sandboxed scripts browsing context flag

This flag blocks script execution.

The sandboxed automatic features browsing context flag

This flag blocks features that trigger automatically, such as automatically playing a video or automatically focusing a form control.

The sandboxed storage area URLs flag

This flag prevents URL schemes that use storage areas from being able to access the origin's data.

The sandboxed fullscreen browsing context flag

This flag prevents content from using the requestFullscreen() method.

The sandboxed document.domain browsing context flag

This flag prevents content from using the document.domain feature to change the effective script origin.

When the user agent is to parse a sandboxing directive, given a string input, a sandboxing flag set output, and optionally an allow fullscreen flag, it must run the following steps:

  1. Split input on spaces, to obtain tokens.

  2. Let output be empty.

  3. Add the following flags to output:


Every top-level browsing context has a popup sandboxing flag set, which is a sandboxing flag set. When a browsing context is created, its popup sandboxing flag set must be empty. It is populated by the rules for choosing a browsing context given a browsing context name.

Every nested browsing context has an iframe sandboxing flag set, which is a sandboxing flag set. Which flags in a nested browsing context's iframe sandboxing flag set are set at any particular time is determined by the iframe element's sandbox attribute.

Every Document has an active sandboxing flag set, which is a sandboxing flag set. When the Document is created, its active sandboxing flag set must be empty. It is populated by the navigation algorithm.

Every resource that is obtained by the navigation algorithm has a forced sandboxing flag set, which is a sandboxing flag set. A resource by default has no flags set in its forced sandboxing flag set, but other specifications can define that certain flags are set.

In particular, the forced sandboxing flag set is used by the Content Security Policy specification. [[CSP]]


When a user agent is to implement the sandboxing for a Document, it must populate Document's active sandboxing flag set with the union of the flags that are present in the following sandboxing flag sets at the time the Document object is created:

Session history and navigation

The session history of browsing contexts

The sequence of Documents in a browsing context is its session history. Each browsing context, including nested browsing contexts, has a distinct session history. A browsing context's session history consists of a flat list of session history entries. Each session history entry consists, at a minimum, of a URL, and each entry may in addition have a state object, a title, a Document object, form data, a scroll position, and other information associated with it.

Each entry, when first created, has a Document. However, when a Document is not active, it's possible for it to be discarded to free resources. The URL and other data in a session history entry is then used to bring a new Document into being to take the place of the original, should the user agent find itself having to reactivate that Document.

Titles associated with session history entries need not have any relation with the current title of the Document. The title of a session history entry is intended to explain the state of the document at that point, so that the user can navigate the document's history.

URLs without associated state objects are added to the session history as the user (or script) navigates from page to page.


Each Document object in a browsing context's session history is associated with a unique History object which must all model the same underlying session history.

The history attribute of the Window interface must return the object implementing the History interface for that Window object's newest Document.


A state object is an object representing a user interface state.

Pages can add state objects to the session history. These are then returned to the script when the user (or script) goes back in the history, thus enabling authors to use the "navigation" metaphor even in one-page applications.

State objects are intended to be used for two main purposes: first, storing a preparsed description of the state in the URL so that in the simple case an author doesn't have to do the parsing (though one would still need the parsing for handling URLs passed around by users, so it's only a minor optimization), and second, so that the author can store state that one wouldn't store in the URL because it only applies to the current Document instance and it would have to be reconstructed if a new Document were opened.

An example of the latter would be something like keeping track of the precise coordinate from which a pop-up div was made to animate, so that if the user goes back, it can be made to animate to the same location. Or alternatively, it could be used to keep a pointer into a cache of data that would be fetched from the server based on the information in the URL, so that when going back and forward, the information doesn't have to be fetched again.


At any point, one of the entries in the session history is the current entry. This is the entry representing the active document of the browsing context. Which entry is the current entry is changed by the algorithms defined in this specification, e.g. during session history traversal.

The current entry is usually an entry for the address of the Document. However, it can also be one of the entries for state objects added to the history by that document.

An entry with persisted user state is one that also has user-agent defined state. This specification does not specify what kind of state can be stored.

For example, some user agents might want to persist the scroll position, or the values of form controls.

User agents that persist the value of form controls are encouraged to also persist their directionality (the value of the element's dir attribute). This prevents values from being displayed incorrectly after a history traversal when the user had originally entered the values with an explicit, non-default directionality.

Entries that consist of state objects share the same Document as the entry for the page that was active when they were added.

Contiguous entries that differ just by fragment identifier also share the same Document.

All entries that share the same Document (and that are therefore merely different states of one particular document) are contiguous by definition.

Each Document in a browsing context can also have a latest entry. This is the entry for that Document to which the browsing context's session history was most recently traversed. When a Document is created, it initially has no latest entry.

User agents may discard the Document objects of entries other than the current entry that are not referenced from any script, reloading the pages afresh when the user or script navigates back to such pages. This specification does not specify when user agents should discard Document objects and when they should cache them.

Entries that have had their Document objects discarded must, for the purposes of the algorithms given below, act as if they had not. When the user or script navigates back or forwards to a page which has no in-memory DOM objects, any other entries that shared the same Document object with it must share the new object as well.

The History interface

interface History {
  readonly attribute long length;
  readonly attribute any state;
  void go(optional long delta);
  void back();
  void forward();
  void pushState(any data, DOMString title, optional DOMString? url = null);
  void replaceState(any data, DOMString title, optional DOMString? url = null);
};
window . history . length

Returns the number of entries in the joint session history.

window . history . state

Returns the current state object.

window . history . go( [ delta ] )

Goes back or forward the specified number of steps in the joint session history.

A zero delta will reload the current page.

If the delta is out of range, does nothing.

window . history . back()

Goes back one step in the joint session history.

If there is no previous page, does nothing.

window . history . forward()

Goes forward one step in the joint session history.

If there is no next page, does nothing.

window . history . pushState(data, title [, url ] )

Pushes the given data onto the session history, with the given title, and, if provided and not null, the given URL.

window . history . replaceState(data, title [, url ] )

Updates the current entry in the session history to have the given data, title, and, if provided and not null, URL.

The joint session history of a top-level browsing context is the union of all the session histories of all browsing contexts of all the fully active Document objects that share that top-level browsing context, with all the entries that are current entries in their respective session histories removed except for the current entry of the joint session history.

The current entry of the joint session history is the entry that most recently became a current entry in its session history.

Entries in the joint session history are ordered chronologically by the time they were added to their respective session histories. Each entry has an index; the earliest entry has index 0, and the subsequent entries are numbered with consecutively increasing integers (1, 2, 3, etc).

Since each Document in a browsing context might have a different event loop, the actual state of the joint session history can be somewhat nebulous. For example, two sibling iframe elements could both traverse from one unique origin to another at the same time, so their precise order might not be well-defined; similarly, since they might only find out about each other later, they might disagree about the length of the joint session history.

All the getters and setters for attributes, and all the methods, defined on the History interface, when invoked on a History object associated with a Document that is not fully active, must throw a SecurityError exception instead of operating as described below.

The length attribute of the History interface must return the number of entries in the top-level browsing context's joint session history.

The actual entries are not accessible from script.

The state attribute of the History interface must return the last value it was set to by the user agent. Initially, its value must be null.

When the go(delta) method is invoked, if the argument to the method was omitted or has the value zero, the user agent must act as if the location.reload() method was called instead. Otherwise, the user agent must traverse the history by a delta whose value is the value of the method's argument.

When the back() method is invoked, the user agent must traverse the history by a delta −1.

When the forward()method is invoked, the user agent must traverse the history by a delta +1.


Each top-level browsing context has a session history traversal queue, initially empty, to which tasks can be added.

Each top-level browsing context, when created, must begin running the following algorithm, known as the session history event loop for that top-level browsing context, in parallel:

  1. Wait until this top-level browsing context's session history traversal queue is not empty.

  2. Pull the first task from this top-level browsing context's session history traversal queue, and execute it.

  3. Return to the first step of this algorithm.

The session history event loop helps coordinate cross-browsing-context transitions of the joint session history: since each browsing context might, at any particular time, have a different event loop (this can happen if the user agent has more than one event loop per unit of related browsing contexts), transitions would otherwise have to involve cross-event-loop synchronisation.


To traverse the history by a delta delta, the user agent must append a task to this top-level browsing context's session history traversal queue, the task consisting of running the following steps:

  1. Let delta be the argument to the method.

  2. If the index of the current entry of the joint session history plus delta is less than zero or greater than or equal to the number of items in the joint session history, then abort these steps.

  3. Let specified entry be the entry in the joint session history whose index is the sum of delta and the index of the current entry of the joint session history.

  4. Let specified browsing context be the browsing context of the specified entry.

  5. If the specified browsing context's active document's unload a document algorithm is currently running, abort these steps.

  6. Queue a task that consists of running the following substeps. The relevant event loop is that of the specified browsing context's active document. The task source for the queued task is the history traversal task source.

    1. If there is an ongoing attempt to navigate specified browsing context that has not yet matured (i.e. it has not passed the point of making its Document the active document), then cancel that attempt to navigate the browsing context.

    2. If the specified browsing context's active document is not the same Document as the Document of the specified entry, then run these substeps:

      1. Fully exit fullscreen.

      2. Prompt to unload the active document of the specified browsing context. If the user refused to allow the document to be unloaded, then abort these steps.

      3. Unload the active document of the specified browsing context with the recycle parameter set to false.

    3. Traverse the history of the specified browsing context to the specified entry.

When the user navigates through a browsing context, e.g. using a browser's back and forward buttons, the user agent must traverse the history by a delta equivalent to the action specified by the user.


The pushState(data, title, url) method adds a state object entry to the history.

The replaceState(data, title, url) method updates the state object, title, and optionally the URL of the current entry in the history.

When either of these methods is invoked, the user agent must run the following steps:

  1. Let cloned data be a structured clone of the specified data. If this throws an exception, then rethrow that exception and abort these steps.

  2. If the third argument is not null, run these substeps:

    1. Resolve the value of the third argument, relative to the API base URL specified by the entry settings object.
    2. If that fails, throw a SecurityError exception and abort these steps.
    3. Compare the resulting parsed URL to the result of applying the URL parser algorithm to the document's address. If any component of these two URLs differ other than the path, query, and fragment components, then throw a SecurityError exception and abort these steps.
    4. If the origin of the resulting absolute URL is not the same as the origin of the responsible document specified by the entry settings object, and either the path or query components of the two parsed URLs compared in the previous step differ, throw a SecurityError exception and abort these steps. (This prevents sandboxed content from spoofing other pages on the same origin.)
    5. Let new URL be the resulting absolute URL.

    For the purposes of the comparisons in the above substeps, the path and query components can only be the same if the scheme component of both parsed URLs are relative schemes.

  3. If the third argument is null, then let new URL be the URL of the current entry.

  4. If the method invoked was the pushState() method:

    1. Remove all the entries in the browsing context's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

      This doesn't necessarily have to affect the user agent's user interface.

    2. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context's document family.

    3. If appropriate, update the current entry to reflect any state that the user agent wishes to persist. The entry is then said to be an entry with persisted user state.

    4. Add a state object entry to the session history, after the current entry, with cloned data as the state object, the given title as the title, and new URL as the URL of the entry.

    5. Update the current entry to be this newly added entry.

    Otherwise, if the method invoked was the replaceState() method:

    1. Update the current entry in the session history so that cloned data is the entry's new state object, the given title is the new title, and new URL is the entry's new URL.

  5. If the current entry in the session history represents a non-GET request (e.g. it was the result of a POST submission) then update it to instead represent a GET request (or equivalent).

  6. Set the document's address to new URL.

    Since this is neither a navigation of the browsing context nor a history traversal, it does not cause a hashchange event to be fired.

  7. Set history.state to a structured clone of cloned data.

  8. Let the latest entry of the Document of the current entry be the current entry.

The title is purely advisory. User agents might use the title in the user interface.

User agents may limit the number of state objects added to the session history per page. If a page hits the UA-defined limit, user agents must remove the entry immediately after the first entry for that Document object in the session history after having added the new entry. (Thus the state history acts as a FIFO buffer for eviction, but as a LIFO buffer for navigation.)

Consider a game where the user can navigate along a line, such that the user is always at some coordinate, and such that the user can bookmark the page corresponding to a particular coordinate, to return to it later.

A static page implementing the x=5 position in such a game could look like the following:

<!DOCTYPE HTML>
<!-- this is http://example.com/line?x=5 -->
<title>Line Game - 5</title>
<p>You are at coordinate 5 on the line.</p>
<p>
 <a href="?x=6">Advance to 6</a> or
 <a href="?x=4">retreat to 4</a>?
</p>

The problem with such a system is that each time the user clicks, the whole page has to be reloaded. Here instead is another way of doing it, using script:

<!DOCTYPE HTML>
<!-- this starts off as http://example.com/line?x=5 -->
<title>Line Game - 5</title>
<p>You are at coordinate <span id="coord">5</span> on the line.</p>
<p>
 <a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or
 <a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>?
</p>
<script>
 var currentPage = 5; // prefilled by server
 function go(d) {
   setupPage(currentPage + d);
   history.pushState(currentPage, document.title, '?x=' + currentPage);
 }
 onpopstate = function(event) {
   setupPage(event.state);
 }
 function setupPage(page) {
   currentPage = page;
   document.title = 'Line Game - ' + currentPage;
   document.getElementById('coord').textContent = currentPage;
   document.links[0].href = '?x=' + (currentPage+1);
   document.links[0].textContent = 'Advance to ' + (currentPage+1);
   document.links[1].href = '?x=' + (currentPage-1);
   document.links[1].textContent = 'retreat to ' + (currentPage-1);
 }
</script>

In systems without script, this still works like the previous example. However, users that do have script support can now navigate much faster, since there is no network access for the same experience. Furthermore, contrary to the experience the user would have with just a naïve script-based approach, bookmarking and navigating the session history still work.

In the example above, the data argument to the pushState() method is the same information as would be sent to the server, but in a more convenient form, so that the script doesn't have to parse the URL each time the user navigates.

Applications might not use the same title for a session history entry as the value of the document's title element at that time. For example, here is a simple page that shows a block in the title element. Clearly, when navigating backwards to a previous state the user does not go back in time, and therefore it would be inappropriate to put the time in the session history title.

<!DOCTYPE HTML>
<TITLE>Line</TITLE>
<SCRIPT>
 setInterval(function () { document.title = 'Line - ' + new Date(); }, 1000);
 var i = 1;
 function inc() {
   set(i+1);
   history.pushState(i, 'Line - ' + i);
 }
 function set(newI) {
   i = newI;
   document.forms.F.I.value = newI;
 }
</SCRIPT>
<BODY ONPOPSTATE="set(event.state)">
<FORM NAME=F>
State: <OUTPUT NAME=I>1</OUTPUT> <INPUT VALUE="Increment" TYPE=BUTTON ONCLICK="inc()">
</FORM>

The Location interface

Each Document object in a browsing context's session history is associated with a unique instance of a Location object.

document . location [ = value ]
window . location [ = value ]

Returns a Location object with the current page's location.

Can be set, to navigate to another page.

The location attribute of the Document interface must return the Location object for that Document object, if it is in a browsing context, and null otherwise.

The location attribute of the Window interface must return the Location object for that Window object's Document.

Location objects provide a representation of the address of the active document of their Document's browsing context, and allow the current entry of the browsing context's session history to be changed, by adding or replacing entries in the history object.

[Unforgeable] interface Location {
  void assign(DOMString url);
  void replace(DOMString url);
  void reload();

  [SameObject] readonly attribute DOMString[] ancestorOrigins;
};
Location implements URLUtils;
location . assign(url)

Navigates to the given page.

location . replace(url)

Removes the current page from the session history and navigates to the given page.

location . reload()

Reloads the current page.

location . ancestorOrigins

Returns an array values are the origins of the ancestor browsing contexts, from the parent browsing context to the top-level browsing context.

The relevant Document is the Location object's associated Document object's browsing context's active document.

When the assign(url) method is invoked, the UA must resolve the argument, relative to the API base URL specified by the entry settings object, and if that is successful, must navigate the browsing context to the specified url, with exceptions enabled. If the browsing context's session history contains only one Document, and that was the about:blank Document created when the browsing context was created, then the navigation must be done with replacement enabled.

When the replace(url) method is invoked, the UA must resolve the argument, relative to the API base URL specified by the entry settings object, and if that is successful, navigate the browsing context to the specified url with replacement enabled and exceptions enabled.

Navigation for the assign() and replace() methods must be done with the responsible browsing context specified by the incumbent settings object as the source browsing context.

If the resolving step of the assign() and replace() methods is not successful, then the user agent must instead throw a SyntaxError exception.

When the reload() method is invoked, the user agent must run the appropriate steps from the following list:

If the currently executing task is the dispatch of a resize event in response to the user resizing the browsing context

Repaint the browsing context and abort these steps.

If the browsing context's active document is an iframe srcdoc document

Reprocess the iframe attributes of the browsing context's browsing context container.

If the browsing context's active document has its reload override flag set

Perform an overridden reload, with the browsing context being navigated as the responsible browsing context.

Otherwise

Navigate the browsing context to the document's address with replacement enabled and exceptions enabled. The source browsing context must be the browsing context being navigated. This is a reload-triggered navigation.

When a user requests that the active document of a browsing context be reloaded through a user interface element, the user agent should navigate the browsing context to the same resource as that Document, with replacement enabled. In the case of non-idempotent methods (e.g. HTTP POST), the user agent should prompt the user to confirm the operation first, since otherwise transactions (e.g. purchases or database modifications) could be repeated. User agents may allow the user to explicitly override any caches when reloading. If browsing context's active document's reload override flag is set, then the user agent may instead perform an overridden reload rather than the navigation described in this paragraph (with the browsing context being reloaded as the source browsing context).


The Location interface also supports the URLUtils interface. [[!URL]]

When the object is created, and whenever the the address of the relevant Document changes, the user agent must invoke the object's URLUtils interface's set the input algorithm with the address of the relevant Document as the given value.

The object's URLUtils interface's get the base algorithm must return the API base URL specified by the entry settings object, if there is one, or null otherwise.

The object's URLUtils interface's query encoding is the document's character encoding.

When the object's URLUtils interface invokes its update steps with the string value, the user agent must run the following steps:

  1. If any of the following conditions are met, let mode be normal navigation; otherwise, let it be replace navigation:

  2. If mode is normal navigation, then act as if the assign() method had been called with value as its argument. Otherwise, act as if the replace() method had been called with value as its argument.


The ancestorOrigins attribute, on getting, must return a read only array whose values are determined as follows. The same object must be returned each time the attribute's value is obtained for any particular Location object.

  1. Let output be an empty ordered list of strings.

  2. Let current be the browsing context of the Document with which the Location object is associated.

  3. Loop: If current has no parent browsing context, jump to the step labeled end.

  4. Let current be current's parent browsing context.

  5. Append the Unicode serialisation of current's active document's origin to output as a new value.

  6. Return to the step labeled loop.

  7. End: Let output be the values of the array, in the same order.

Security

This section describes a security model that is underdefined, imperfect, and does not match implementations. Work is ongoing to attempt to resolve this, but in the meantime, please do not rely on this section for precision. Implementors are urged to send their feedback on how cross-origin cross-global access to Window and Location objects should work. See bug 20701.

User agents must throw a SecurityError exception whenever any properties of a Location object are accessed when the entry settings object specifies an effective script origin that is not the same as the Location object's associated Document's browsing context's active document's effective script origin, with the following exceptions:

When the effective script origin specified by the entry settings object is different than a Location object's associated Document's effective script origin, the user agent must act as if any changes to that Location object's properties, getters, setters, etc, were not present, and as if all the properties of that Location object had their [[\Enumerable]] attribute set to false.

For members that return objects (including function objects), each distinct effective script origin that is not the same origin as the Location object's Document's effective script origin must be provided with a separate set of objects. These objects must have the prototype chain appropriate for the script for which the objects are created (not those that would be appropriate for scripts whose settings object specifies a global object that is the Location object's Document's Window object).

Implementation notes for session history

This section is non-normative.

The History interface is not meant to place restrictions on how implementations represent the session history to the user.

For example, session history could be implemented in a tree-like manner, with each page having multiple "forward" pages. This specification doesn't define how the linear list of pages in the history object are derived from the actual session history as seen from the user's perspective.

Similarly, a page containing two iframes has a history object distinct from the iframes' history objects, despite the fact that typical Web browsers present the user with just one "Back" button, with a session history that interleaves the navigation of the two inner frames and the outer page.

Security: It is suggested that to avoid letting a page "hijack" the history navigation facilities of a UA by abusing pushState(), the UA provide the user with a way to jump back to the previous page (rather than just going back to the previous state). For example, the back button could have a drop down showing just the pages in the session history, and not showing any of the states. Similarly, an aural browser could have two "back" commands, one that goes back to the previous state, and one that jumps straight back to the previous page.

In addition, a user agent could ignore calls to pushState() that are invoked on a timer, or from event listeners that are not triggered in response to a clear user action, or that are invoked in rapid succession.

Base64 utility methods

The atob() and btoa() methods allow authors to transform content to and from the base64 encoding.

[NoInterfaceObject, Exposed=(Window,Worker)]
interface WindowBase64 {
  DOMString btoa(DOMString btoa);
  DOMString atob(DOMString atob);
};
Window implements WindowBase64;

In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.

result = window . btoa( data )

Takes the input data, in the form of a Unicode string containing only characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and converts it to its base64 representation, which it returns.

Throws an InvalidCharacterError exception if the input string contains any out-of-range characters.

result = window . atob( data )

Takes the input data, in the form of a Unicode string containing base64-encoded binary data, decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary data.

Throws an InvalidCharacterError exception if the input string is not valid base64 data.

The WindowBase64 interface adds to the Window interface and the WorkerGlobalScope interface (part of Web workers).

The btoa() method must throw an InvalidCharacterError exception if the method's first argument contains any character whose code point is greater than U+00FF. Otherwise, the user agent must convert that argument to a sequence of octets whose nth octet is the eight-bit representation of the code point of the nth character of the argument, and then must apply the base64 algorithm to that sequence of octets, and return the result. [[!RFC4648]]

The atob() method must run the following steps to parse the string passed in the method's first argument:

  1. Let input be the string being parsed.

  2. Let position be a pointer into input, initially pointing at the start of the string.

  3. Remove all space characters from input.

  4. If the length of input divides by 4 leaving no remainder, then: if input ends with one or two U+003D EQUALS SIGN (=) characters, remove them from input.

  5. If the length of input divides by 4 leaving a remainder of 1, throw an InvalidCharacterError exception and abort these steps.

  6. If input contains a character that is not in the following list of characters and character ranges, throw an InvalidCharacterError exception and abort these steps:

  7. Let output be a string, initially empty.

  8. Let buffer be a buffer that can have bits appended to it, initially empty.

  9. While position does not point past the end of input, run these substeps:

    1. Find the character pointed to by position in the first column of the following table. Let n be the number given in the second cell of the same row.

      Character Number
      A0
      B1
      C2
      D3
      E4
      F5
      G6
      H7
      I8
      J9
      K10
      L11
      M12
      N13
      O14
      P15
      Q16
      R17
      S18
      T19
      U20
      V21
      W22
      X23
      Y24
      Z25
      a26
      b27
      c28
      d29
      e30
      f31
      g32
      h33
      i34
      j35
      k36
      l37
      m38
      n39
      o40
      p41
      q42
      r43
      s44
      t45
      u46
      v47
      w48
      x49
      y50
      z51
      052
      153
      254
      355
      456
      557
      658
      759
      860
      961
      +62
      /63
    2. Append to buffer the six bits corresponding to number, most significant bit first.

    3. If buffer has accumulated 24 bits, interpret them as three 8-bit big-endian numbers. Append the three characters with code points equal to those numbers to output, in the same order, and then empty buffer.

    4. Advance position by one character.

  10. If buffer is not empty, it contains either 12 or 18 bits. If it contains 12 bits, discard the last four and interpret the remaining eight as an 8-bit big-endian number. If it contains 18 bits, discard the last two and interpret the remaining 16 as two 8-bit big-endian numbers. Append the one or two characters with code points equal to those one or two numbers to output, in the same order.

    The discarded bits mean that, for instance, atob("YQ") and atob("YR") both return "a".

  11. Return output.

Dynamic markup insertion

APIs for dynamically inserting markup into the document interact with the parser, and thus their behaviour varies depending on whether they are used with HTML documents (and the HTML parser) or XHTML in XML documents (and the XML parser).

Opening the input stream

The open() method comes in several variants with different numbers of arguments.

document = document . open( [ type [, replace ] ] )

Causes the Document to be replaced in-place, as if it was a new Document object, but reusing the previous object, which is then returned.

If the type argument is omitted or has the value "text/html", then the resulting Document has an HTML parser associated with it, which can be given data to parse using document.write(). Otherwise, all content passed to document.write() will be parsed as plain text.

If the replace argument is present and has the value "replace", the existing entries in the session history for the Document object are removed.

The method has no effect if the Document is still being parsed.

Throws an InvalidStateError exception if the Document is an XML document.

window = document . open( url, name, features [, replace ] )

Works like the window.open() method.

Document objects have an ignore-opens-during-unload counter, which is used to prevent scripts from invoking the document.open() method (directly or indirectly) while the document is being unloaded. Initially, the counter must be set to zero.

When called with two arguments (or fewer), the document.open() method must act as follows:

  1. If the Document object is not flagged as an HTML document, throw an InvalidStateError exception and abort these steps.

  2. If the Document object is not an active document, then abort these steps.

  3. Let type be the value of the first argument.

  4. If the second argument is an ASCII case-insensitive match for the value "replace", then let replace be true.

    Otherwise, if the browsing context's session history contains only one Document, and that was the about:blank Document created when the browsing context was created, and that Document has never had the unload a document algorithm invoked on it (e.g. by a previous call to document.open()), then let replace be true.

    Otherwise, let replace be false.

  5. If the Document has an active parser whose script nesting level is greater than zero, then the method does nothing. Abort these steps and return the Document object on which the method was invoked.

    This basically causes document.open() to be ignored when it's called in an inline script found during parsing, while still letting it have an effect when called from a non-parser task such as a timer callback or event handler.

  6. Similarly, if the Document's ignore-opens-during-unload counter is greater than zero, then the method does nothing. Abort these steps and return the Document object on which the method was invoked.

    This basically causes document.open() to be ignored when it's called from a beforeunload pagehide, or unload event handler while the Document is being unloaded.

  7. Release the storage mutex.

  8. Set the Document's salvageable state to false.

  9. Prompt to unload the Document object. If the user refused to allow the document to be unloaded, then abort these steps and return the Document object on which the method was invoked.

  10. Unload the Document object, with the recycle parameter set to true.

  11. Abort the Document.

  12. Unregister all event listeners registered on the Document node and its descendants.

  13. Remove any tasks associated with the Document in any task source.

  14. Remove all child nodes of the document, without firing any mutation events.

  15. Replace the Document's singleton objects with new instances of those objects. (This includes in particular the Window, Location, History, ApplicationCache, and Navigator, objects, the various BarProp objects, the two Storage objects, the various HTMLCollection objects, and objects defined by other specifications, like Selection. It also includes all the Web IDL prototypes in the JavaScript binding, including the Document object's prototype.)

    The new Window object has a new environment settings object.

  16. Change the document's character encoding to UTF-8.

  17. If the Document is ready for post-load tasks, then set the Document object's reload override flag and set the Document's reload override buffer to the empty string.

  18. Set the Document's salvageable state back to true.

  19. Change the document's address to the address of the responsible document specified by the entry settings object.

  20. If the Document's iframe load in progress flag is set, set the Document's mute iframe load flag.

  21. Create a new HTML parser and associate it with the document. This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for an explicit call to document.close() before emitting an end-of-file token). The encoding confidence is irrelevant.

  22. Set the current document readiness of the document to "loading".

  23. If type is an ASCII case-insensitive match for the string "replace", then, for historical reasons, set it to the string "text/html".

    Otherwise:

    If the type string contains a U+003B SEMICOLON character (;), remove the first such character and all characters from it up to the end of the string.

    Strip leading and trailing whitespace from type.

  24. If type is not now an ASCII case-insensitive match for the string "text/html", then act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, then switch the HTML parser's tokenizer to the PLAINTEXT state.

  25. Remove all the entries in the browsing context's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

    This doesn't necessarily have to affect the user agent's user interface.

  26. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context's document family.

  27. Remove any earlier entries that share the same Document.
  28. If replace is false, then add a new entry, just before the last entry, and associate with the new entry the text that was parsed by the previous parser associated with the Document object, as well as the state of the document at the start of these steps. This allows the user to step backwards in the session history to see the page before it was blown away by the document.open() call. This new entry does not have a Document object, so a new one will be created if the session history is traversed to that entry.

  29. Finally, set the insertion point to point at just before the end of the input stream (which at this point will be empty).

  30. Return the Document on which the method was invoked.

The document.open() method does not affect whether a Document is ready for post-load tasks or completely loaded.

When called with four arguments, the open() method on the Document object must call the open() method on the Window object of the Document object, with the same arguments as the original call to the open() method, and return whatever that method returned. If the Document object has no Window object, then the method must throw an InvalidAccessError exception.

Closing the input stream

document . close()

Closes the input stream that was opened by the document.open() method.

Throws an InvalidStateError exception if the Document is an XML document.

The close() method must run the following steps:

  1. If the Document object is not flagged as an HTML document, throw an InvalidStateError exception and abort these steps.

  2. If there is no script-created parser associated with the document, then abort these steps.

  3. Insert an explicit "EOF" character at the end of the parser's input stream.

  4. If there is a pending parsing-blocking script, then abort these steps.

  5. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop.

document.write()

document . write(text...)

In general, adds the given string(s) to the Document's input stream.

This method has very idiosyncratic behaviour. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g. if the string written is the string "<plaintext>" or "<!--"). In other cases, the call can clear the current page first, as if document.open() had been called. In yet more cases, the method is simply ignored, or throws an exception. To make matters worse, the exact behaviour of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.

This method throws an InvalidStateError exception when invoked on XML documents.

Document objects have an ignore-destructive-writes counter, which is used in conjunction with the processing of script elements to prevent external scripts from being able to use document.write() to blow away the document by implicitly calling document.open(). Initially, the counter must be set to zero.

The document.write(...) method must act as follows:

  1. If the method was invoked on an XML document, throw an InvalidStateError exception and abort these steps.

  2. If the Document object is not an active document, then abort these steps.

  3. If the insertion point is undefined and either the Document's ignore-opens-during-unload counter is greater than zero or the Document's ignore-destructive-writes counter is greater than zero, abort these steps.

  4. If the insertion point is undefined, call the open() method on the document object (with no arguments). If the user refused to allow the document to be unloaded, then abort these steps. Otherwise, the insertion point will point at just before the end of the (empty) input stream.

  5. Insert the string consisting of the concatenation of all the arguments to the method into the input stream just before the insertion point.

  6. If the Document object's reload override flag is set, then append the string consisting of the concatenation of all the arguments to the method to the Document's reload override buffer.

  7. If there is no pending parsing-blocking script, have the HTML parser process the characters that were inserted, one at a time, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the insertion point or when the processing of the tokenizer is aborted by the tree construction stage (this can happen if a script end tag token is emitted by the tokenizer).

    If the document.write() method was called from script executing inline (i.e. executing because the parser parsed a set of script tags), then this is a reentrant invocation of the parser.

  8. Finally, return from the method.

document.writeln()

document . writeln(text...)

Adds the given string(s) to the Document's input stream, followed by a newline character. If necessary, calls the open() method implicitly first.

This method throws an InvalidStateError exception when invoked on XML documents.

The document.writeln(...) method, when invoked, must act as if the document.write() method had been invoked with the same argument(s), plus an extra argument consisting of a string containing a single line feed character (U+000A).

Timers

The setTimeout() and setInterval() methods allow authors to schedule timer-based callbacks.

[NoInterfaceObject, Exposed=(Window,Worker)]
interface WindowTimers {
  long setTimeout(Function handler, optional long timeout = 0, any... arguments);
  long setTimeout(DOMString handler, optional long timeout = 0, any... arguments);
  void clearTimeout(optional long handle = 0);
  long setInterval(Function handler, optional long timeout = 0, any... arguments);
  long setInterval(DOMString handler, optional long timeout = 0, any... arguments);
  void clearInterval(optional long handle = 0);
};
Window implements WindowTimers;
handle = window . setTimeout( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

handle = window . setTimeout( code [, timeout ] )

Schedules a timeout to compile and run code after timeout milliseconds.

window . clearTimeout( handle )

Cancels the timeout set with setTimeout() identified by handle.

handle = window . setInterval( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

handle = window . setInterval( code [, timeout ] )

Schedules a timeout to compile and run code every timeout milliseconds.

window . clearInterval( handle )

Cancels the timeout set with setInterval() identified by handle.

Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

The WindowTimers interface adds to the Window interface and the WorkerGlobalScope interface (part of Web workers).

Each object that implements the WindowTimers interface has a list of active timers. Each entry in this lists is identified by a number, which must be unique within the list for the lifetime of the object that implements the WindowTimers interface.


The setTimeout() method must return the value returned by the timer initialisation steps, passing them the method's arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to false.

The setInterval() method must return the value returned by the timer initialisation steps, passing them the method's arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to true.

The clearTimeout() and clearInterval() methods must clear the entry identified as handle from the list of active timers of the WindowTimers object on which the method was invoked, if any, where handle is the argument passed to the method. (If handle does not identify an entry in the list of active timers of the WindowTimers object on which the method was invoked, the method does nothing.)


The timer initialisation steps, which are invoked with some method arguments, a method context, a repeat flag which can be true or false, and optionally (and only if the repeat flag is true) a previous handle, are as follows:

  1. Let method context proxy be method context if that is a WorkerGlobalScope object, or else the WindowProxy that corresponds to method context.

  2. If previous handle was provided, let handle be previous handle; otherwise, let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call in the list of active timers.

  3. If previous handle was not provided, add an entry to the list of active timers for handle.

  4. Let task be a task that runs the following substeps:

    1. If the entry for handle in the list of active timers has been cleared, then abort this task's substeps.

    2. Run the appropriate set of steps from the following list:

      If the first method argument is a Function

      Invoke the Function. Use the third and subsequent method arguments (if any) as the arguments for invoking the Function. Use method context proxy as the thisArg for invoking the Function. [[!ECMA262]]

      Otherwise
      1. Let script source be the first method argument.

      2. Let script language be JavaScript.

      3. Let settings object be method context's environment settings object.

      4. Create a script using script source as the script source, the URL where script source can be found, scripting language as the scripting language, and settings object as the environment settings object.

    3. If the repeat flag is true, then call timer initialisation steps again, passing them the same method arguments, the same method context, with the repeat flag still set to true, and with the previous handle set to handler.

  5. Let timeout be the second method argument.

  6. If the currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.

  7. If nesting level is greater than 5, and timeout is less than 4, then increase timeout to 4.

  8. Increment nesting level by one.

  9. Let task's timer nesting level be nesting level.

  10. Return handle, and then continue running this algorithm in parallel.

  11. If method context is a Window object, wait until the Document associated with method context has been fully active for a further timeout milliseconds (not necessarily consecutively).

    Otherwise, method context is a WorkerGlobalScope object; wait until timeout milliseconds have passed with the worker not suspended (not necessarily consecutively).

  12. Wait until any invocations of this algorithm that had the same method context, that started before this one, and whose timeout is equal to or less than this one's, have completed.

    Argument conversion as defined by Web IDL (for example, invoking toString() methods on objects passed as the first argument) happens in the algorithms defined in Web IDL, before this algorithm is invoked.

    So for example, the following rather silly code will result in the log containing "ONE TWO ":

    var log = '';
    function logger(s) { log += s + ' '; }
    
    setTimeout({ toString: function () {
      setTimeout("logger('ONE')", 100);
      return "logger('TWO')";
    } }, 100);
  13. Optionally, wait a further user-agent defined length of time.

    This is intended to allow user agents to pad timeouts as needed to optimise the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

  14. Queue the task task.

    Once the task has been processed, if the repeat flag is false, it is safe to remove the entry for handle from the list of active timers (there is no way for the entry's existence to be detected past this point, so it does not technically matter one way or the other).

The task source for these tasks is the timer task source.

To run tasks of several milliseconds back to back without any delay, while still yielding back to the browser to avoid starving the user interface (and to avoid the browser killing the script for hogging the CPU), simply queue the next timer before performing work:

function doExpensiveWork() {
  var done = false;
  // ...
  // this part of the function takes up to five milliseconds
  // set done to true if we're done
  // ...
  return done;
}

function rescheduleWork() {
  var handle = setTimeout(rescheduleWork, 0); // preschedule next iteration
  if (doExpensiveWork())
    clearTimeout(handle); // clear the timeout if we don't need it
}

function scheduleWork() {
  setTimeout(rescheduleWork, 0);
}

scheduleWork(); // queues a task to do lots of work

User prompts

Simple dialogs

window . alert(message)

Displays a modal alert with the given message, and waits for the user to dismiss it.

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

result = window . confirm(message)

Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it, and returns true if the user clicks OK and false if the user clicks Cancel.

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

result = window . prompt(message [, default] )

Displays a modal text field prompt with the given message, waits for the user to dismiss it, and returns the value that the user entered. If the user cancels the prompt, then returns null instead. If the second argument is present, then the given value is used as a default.

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

Logic that depends on tasks or microtasks, such as media elements loading their media data, are stalled when these methods are invoked.

The alert(message) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is non-zero, optionally abort these steps.

  2. Release the storage mutex.

  3. Optionally, abort these steps. (For example, the user agent might give the user the option to ignore all alerts, and would thus abort at this step whenever the method was invoked.)

  4. If the method was invoked with no arguments, then let message be the empty string; otherwise, let message be the method's first argument.

  5. Show the given message to the user.

  6. Optionally, pause while waiting for the user to acknowledge the message.

The confirm(message) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is non-zero, optionally abort these steps, returning false.

  2. Release the storage mutex.

  3. Optionally, return false and abort these steps. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)

  4. Show the given message to the user, and ask the user to respond with a positive or negative response.

  5. Pause until the user responds either positively or negatively.

  6. If the user responded positively, return true; otherwise, the user responded negatively: return false.

The prompt(message, default) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is non-zero, optionally abort these steps, returning null.

  2. Release the storage mutex.

  3. Optionally, return null and abort these steps. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)

  4. Show the given message to the user, and ask the user to either respond with a string value or abort. The response must be defaulted to the value given by default.

  5. Pause while waiting for the user's response.

  6. If the user aborts, then return null; otherwise, return the string that the user responded with.

Printing

window . print()

Prompts the user to print the page.

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

When the print() method is invoked, if the Document is ready for post-load tasks, then the user agent must run the printing steps in parallel. Otherwise, the user agent must only set the print when loaded flag on the Document.

User agents should also run the printing steps whenever the user asks for the opportunity to obtain a physical form (e.g. printed copy), or the representation of a physical form (e.g. PDF copy), of a document.

The printing steps are as follows:

  1. The user agent may display a message to the user or abort these steps (or both).

    For instance, a kiosk browser could silently ignore any invocations of the print() method.

    For instance, a browser on a mobile device could detect that there are no printers in the vicinity and display a message saying so before continuing to offer a "save to PDF" option.

  2. The user agent must fire a simple event named beforeprint at the Window object of the Document that is being printed, as well as any nested browsing contexts in it.

    The beforeprint event can be used to annotate the printed copy, for instance adding the time at which the document was printed.

  3. The user agent must release the storage mutex.

  4. The user agent should offer the user the opportunity to obtain a physical form (or the representation of a physical form) of the document. The user agent may wait for the user to either accept or decline before returning; if so, the user agent must pause while the method is waiting. Even if the user agent doesn't wait at this point, the user agent must use the state of the relevant documents as they are at this point in the algorithm if and when it eventually creates the alternate form.

  5. The user agent must fire a simple event named afterprint at the Window object of the Document that is being printed, as well as any nested browsing contexts in it.

    The afterprint event can be used to revert annotations added in the earlier event, as well as showing post-printing UI. For instance, if a page is walking the user through the steps of applying for a home loan, the script could automatically advance to the next step after having printed a form or other.

Dialogs implemented using separate documents with showModalDialog()

This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using the showModalDialog() API at this time is highly discouraged.

The showModalDialog(url, argument) method, when invoked, must cause the user agent to run the following steps:

  1. Resolve url relative to the API base URL specified by the entry settings object.

    If this fails, then throw a SyntaxError exception and abort these steps.

  2. If the event loop's termination nesting level is non-zero, optionally abort these steps, returning the empty string.

  3. Release the storage mutex.

  4. If the user agent is configured such that this invocation of showModalDialog() is somehow disabled, then return the empty string and abort these steps.

    User agents are expected to disable this method in certain cases to avoid user annoyance (e.g. as part of their popup blocker feature). For instance, a user agent could require that a site be white-listed before enabling this method, or the user agent could be configured to only allow one modal dialog at a time.

  5. If the active sandboxing flag set of the active document of the responsible browsing context specified by the incumbent settings object has its sandboxed auxiliary navigation browsing context flag set, then return the empty string and abort these steps.

  6. Let incumbent origin be the effective script origin specified by the incumbent settings object at the time the showModalDialog() method was called.

  7. Let the list of background browsing contexts be a list of all the browsing contexts that:

    ...as well as any browsing contexts that are nested inside any of the browsing contexts matching those conditions.

  8. Disable the user interface for all the browsing contexts in the list of background browsing contexts. This should prevent the user from navigating those browsing contexts, causing events to be sent to those browsing context, or editing any content in those browsing contexts. However, it does not prevent those browsing contexts from receiving events from sources other than the user, from running scripts, from running animations, and so forth.

  9. Create a new auxiliary browsing context, with the opener browsing context being the browsing context of the Window object on which the showModalDialog() method was called. The new auxiliary browsing context has no name.

    This browsing context's Documents' Window objects all implement the WindowModal interface.

  10. Set all the flags in the new browsing context's popup sandboxing flag set that are set in the active sandboxing flag set of the active document of the responsible browsing context specified by the incumbent settings object. The responsible browsing context specified by the incumbent settings object must be set as the new browsing context's one permitted sandboxed navigator.

  11. Let the dialog arguments of the new browsing context be set to the value of argument, or the undefined value if the argument was omitted.

  12. Let the dialog arguments' origin be incumbent origin.

  13. Let the return value of the new browsing context be the undefined value.

  14. Let the return value origin be incumbent origin.

  15. Navigate the new browsing context to the absolute URL that resulted from resolving url earlier, with replacement enabled, and with the responsible browsing context specified by the incumbent settings object as the source browsing context.

  16. Spin the event loop until the new browsing context is closed. The user agent must allow the user to indicate that the browsing context is to be closed.

  17. Reenable the user interface for all the browsing contexts in the list of background browsing contexts.

  18. If the auxiliary browsing context's return value origin at the time the browsing context was closed was the same as incumbent origin, then let return value be the auxiliary browsing context's return value as it stood when the browsing context was closed.

    Otherwise, let return value be undefined.

  19. Return return value.

The Window objects of Documents hosted by browsing contexts created by the above algorithm must also implement the WindowModal interface.

When this happens, the members of the WindowModal interface, in JavaScript environments, appear to actually be part of the Window interface (e.g. they are on the same prototype chain as the window.alert() method).

[NoInterfaceObject]
interface WindowModal {
  readonly attribute any dialogArguments;
  attribute any returnValue;
};
window . dialogArguments

Returns the argument argument that was passed to the showModalDialog() method.

window . returnValue [ = value ]

Returns the current return value for the window.

Can be set, to change the value that will be returned by the showModalDialog() method.

Such browsing contexts have associated dialog arguments, which are stored along with the dialog arguments' origin. These values are set by the showModalDialog() method in the algorithm above, when the browsing context is created, based on the arguments provided to the method.

The dialogArguments IDL attribute, on getting, must check whether its browsing context's active document's effective script origin is the same as the dialog arguments' origin. If it is, then the browsing context's dialog arguments must be returned unchanged. Otherwise, the IDL attribute must return undefined.

These browsing contexts also have an associated return value and return value origin. As with the previous two values, these values are set by the showModalDialog() method in the algorithm above, when the browsing context is created.

The returnValue IDL attribute, on getting, must check whether its browsing context's active document's effective script origin is the same as the current return value origin. If it is, then the browsing context's return value must be returned unchanged. Otherwise, the IDL attribute must return undefined. On setting, the attribute must set the return value to the given new value, and the return value origin to the browsing context's active document's effective script origin.

The window.close() method can be used to close the browsing context.

System state and capabilities

The Navigator object

The navigator attribute of the Window interface must return an instance of the Navigator interface, which represents the identity and state of the user agent (the client), and allows Web pages to register themselves as potential protocol and content handlers:

interface Navigator {
  // objects implementing this interface also implement the interfaces given below
};
Navigator implements NavigatorID;
Navigator implements NavigatorLanguage;
Navigator implements NavigatorOnLine;
Navigator implements NavigatorContentUtils;
Navigator implements NavigatorStorageUtils;
Navigator implements NavigatorPlugins;

These interfaces are defined separately so that other specifications can re-use parts of the Navigator interface.

Client identification

[NoInterfaceObject, Exposed=(Window,Worker)]
interface NavigatorID {
  readonly attribute DOMString appCodeName; // constant "Mozilla"
  readonly attribute DOMString appName;
  readonly attribute DOMString appVersion;
  readonly attribute DOMString platform;
  readonly attribute DOMString product; // constant "Gecko"
  boolean taintEnabled(); // constant false
  readonly attribute DOMString userAgent;
  readonly attribute DOMString vendorSub;
};

In certain cases, despite the best efforts of the entire industry, Web browsers have bugs and limitations that Web authors are forced to work around.

This section defines a collection of attributes that can be used to determine, from script, the kind of user agent in use, in order to work around these issues.

Client detection should always be limited to detecting known current versions; future versions and unknown versions should always be assumed to be fully compliant.

window . navigator . appCodeName

Returns the string "Mozilla".

window . navigator . appName

Returns the name of the browser.

window . navigator . appVersion

Returns the version of the browser.

window . navigator . platform

Returns the name of the platform.

window . navigator . product

Returns the string "Gecko".

window . navigator . taintEnabled()

Returns false.

window . navigator . userAgent

Returns the complete User-Agent header.

appCodeName

Must return the string "Mozilla".

appName

Must return either the string "Netscape" or the full name of the browser, e.g. "Mellblom Browsernator".

appVersion

Must return either the string "4.0" or a string representing the version of the browser in detail, e.g. "1.0 (VMS; en-US) Mellblomenator/9000".

platform

Must return either the empty string or a string representing the platform on which the browser is executing, e.g. "MacIntel", "Win32", "FreeBSD i386", "WebTV OS".

product

Must return the string "Gecko".

taintEnabled()

Must return false.

userAgent

Must return the string used for the value of the "User-Agent" header in HTTP requests, or the empty string if no such header is ever sent.

vendorSub

Must return the empty string.

Any information in this API that varies from user to user can be used to profile the user. In fact, if enough such information is available, a user can actually be uniquely identified. For this reason, user agent implementors are strongly urged to include as little information in this API as possible. (This is a fingerprinting vector.)

Language preferences

[NoInterfaceObject, Exposed=(Window,Worker)]
interface NavigatorLanguage {
  readonly attribute DOMString? language;
  readonly attribute DOMString[] languages;
};
window . navigator . language

Returns a language tag representing the user's preferred language.

window . navigator . languages

Returns an array of language tags representing the user's preferred languages, with the most preferred language first.

The most preferred language is the one returned by navigator.language.

A languagechange event is fired at the Window or WorkerGlobalScope object when the user agent's understanding of what the user's preferred languages are changes.

language

Must return a valid BCP 47 language tag representing either a plausible language or the user's most preferred language. [[!BCP47]]

languages

Must return a read only array of valid BCP 47 language tags representing either one or more plausible languages, or the user's preferred languages, ordered by preference with the most preferred language first. The same object must be returned until the user agent needs to return different values, or values in a different order. [[!BCP47]]

Whenever the user agent needs to make the navigator.languages attribute of a Window or WorkerGlobalScope object return a new set of language tags, the user agent must queue a task to fire a simple event named languagechange at the Window or WorkerGlobalScope object and wait until that task begins to be executed before actually returning a new value.

The task source for this task is the DOM manipulation task source.

To determine a plausible language, the user agent should bear in mind the following:

  • Any information in this API that varies from user to user can be used to profile or identify the user. (This is a fingerprinting vector.)
  • If the user is not using a service that obfuscates the user's point of origin (e.g. the Tor anonymity network), then the value that is least likely to distinguish the user from other users with similar origins (e.g. from the same IP address block) is the language used by the majority of such users. [[TOR]]
  • If the user is using an anonymizing service, then the value "en-US" is suggested; if all users of the service use that same value, that reduces the possibility of distinguishing the users from each other.

To avoid introducing any more fingerprinting vectors, user agents should use the same list for the APIs defined in this function as for the HTTP Accept-Language header. (This is a fingerprinting vector.)

Custom scheme and content handlers: the registerProtocolHandler() and registerContentHandler() methods

[NoInterfaceObject]
interface NavigatorContentUtils {
  // content handler registration
  void registerProtocolHandler(DOMString scheme, DOMString url, DOMString title);
  void registerContentHandler(DOMString mimeType, DOMString url, DOMString title);
  DOMString isProtocolHandlerRegistered(DOMString scheme, DOMString url);
  DOMString isContentHandlerRegistered(DOMString mimeType, DOMString url);
  void unregisterProtocolHandler(DOMString scheme, DOMString url);
  void unregisterContentHandler(DOMString mimeType, DOMString url);
};

The registerProtocolHandler() method allows Web sites to register themselves as possible handlers for particular schemes. For example, an online telephone messaging service could register itself as a handler of the sms: scheme, so that if the user clicks on such a link, he is given the opportunity to use that Web site. Analogously, the registerContentHandler() method allows Web sites to register themselves as possible handlers for content in a particular MIME type. For example, the same online telephone messaging service could register itself as a handler for text/vcard files, so that if the user has no native application capable of handling vCards, his Web browser can instead suggest he use that site to view contact information stored on vCards that he opens. [[SMS]] [[!RFC6350]]

window . navigator . registerProtocolHandler(scheme, url, title)
window . navigator . registerContentHandler(mimeType, url, title)

Registers a handler for the given scheme or content type, at the given URL, with the given title.

The string "%s" in the URL is used as a placeholder for where to put the URL of the content to be handled.

Throws a SecurityError exception if the user agent blocks the registration (this might happen if trying to register as a handler for "http", for instance).

Throws a SyntaxError exception if the "%s" string is missing in the URL.

User agents may, within the constraints described in this section, do whatever they like when the methods are called. A UA could, for instance, prompt the user and offer the user the opportunity to add the site to a shortlist of handlers, or make the handlers his default, or cancel the request. UAs could provide such a UI through modal UI or through a non-modal transient notification interface. UAs could also simply silently collect the information, providing it only when relevant to the user.

User agents should keep track of which sites have registered handlers (even if the user has declined such registrations) so that the user is not repeatedly prompted with the same request.

The arguments to the methods have the following meanings and corresponding implementation requirements. The requirements that involve throwing exceptions must be processed in the order given below, stopping at the first exception thrown. (So the exceptions for the first argument take precedence over the exceptions for the second argument.)

scheme (registerProtocolHandler() only)

A scheme, such as "mailto" or "web+auth". The scheme must be compared in an ASCII case-insensitive manner by user agents for the purposes of comparing with the scheme part of URLs that they consider against the list of registered handlers.

The scheme value, if it contains a colon (as in "mailto:"), will never match anything, since schemes don't contain colons.

If the registerProtocolHandler() method is invoked with a scheme that is neither a whitelisted scheme nor a scheme whose value starts with the substring "web+" and otherwise contains only lowercase ASCII letters, and whose length is at least five characters (including the "web+" prefix), the user agent must throw a SecurityError exception.

The following schemes are the whitelisted schemes:

  • bitcoin
  • geo
  • im
  • irc
  • ircs
  • magnet
  • mailto
  • mms
  • news
  • nntp
  • openpgp4fpr
  • sip
  • sms
  • smsto
  • ssh
  • tel
  • urn
  • webcal
  • wtai
  • xmpp

This list can be changed. If there are schemes that should be added, please send feedback.

This list excludes any schemes that could reasonably be expected to be supported inline, e.g. in an iframe, such as http or (more theoretically) gopher. If those were supported, they could potentially be used in man-in-the-middle attacks, by replacing pages that have frames with such content with content under the control of the protocol handler. If the user agent has native support for the schemes, this could further be used for cookie-theft attacks.

mimeType (registerContentHandler() only)

A MIME type, such as model/vnd.flatland.3dml or application/vnd.google-earth.kml+xml. The MIME type must be compared in an ASCII case-insensitive manner by user agents for the purposes of comparing with MIME types of documents that they consider against the list of registered handlers.

User agents must compare the given values only to the MIME type/subtype parts of content types, not to the complete type including parameters. Thus, if mimeType values passed to this method include characters such as commas or whitespace, or include MIME parameters, then the handler being registered will never be used.

The type is compared to the MIME type used by the user agent after the sniffing algorithms have been applied.

If the registerContentHandler() method is invoked with a MIME type that is in the type blacklist or that the user agent has deemed a privileged type, the user agent must throw a SecurityError exception.

The following MIME types are in the type blacklist:

This list can be changed. If there are MIME types that should be added, please send feedback.

url

A string used to build the URL of the page that will handle the requests.

User agents must throw a SyntaxError exception if the url argument passed to one of these methods does not contain the exact literal string "%s".

User agents must throw a SyntaxError exception if resolving the url argument relative to the API base URL specified by the entry settings object is not successful.

The resulting absolute URL would by definition not be a valid URL as it would include the string "%s" which is not a valid component in a URL.

User agents must throw a SecurityError exception if the resulting absolute URL has an origin that differs from the origin specified by the entry settings object.

This is forcibly the case if the %s placeholder is in the scheme, host, or port parts of the URL.

The resulting absolute URL is the proto-URL. It identifies the handler for the purposes of the methods described below.

When the user agent uses this handler, it must replace the first occurrence of the exact literal string "%s" in the url argument with an escaped version of the absolute URL of the content in question (as defined below), then resolve the resulting URL, relative to the API base URL specified by the entry settings object at the time the registerContentHandler() or registerProtocolHandler() methods were invoked, and then navigate an appropriate browsing context to the resulting URL using the GET method (or equivalent for non-HTTP URLs).

To get the escaped version of the absolute URL of the content in question, the user agent must replace every character in that absolute URL that is not a character in the URL default encode set with the result of UTF-8 percent encoding that character.

If the user had visited a site at http://example.com/ that made the following call:

navigator.registerContentHandler('application/x-soup', 'soup?url=%s', 'SoupWeb™')

...and then, much later, while visiting http://www.example.net/, clicked on a link such as:

<a href="chickenkïwi.soup">Download our Chicken Kïwi soup!</a>

...then, assuming this chickenkïwi.soup file was served with the MIME type application/x-soup, the UA might navigate to the following URL:

http://example.com/soup?url=http://www.example.net/chickenk%C3%AFwi.soup

This site could then fetch the chickenkïwi.soup file and do whatever it is that it does with soup (synthesise it and ship it to the user, or whatever).

title

A descriptive title of the handler, which the UA might use to remind the user what the site in question is.

This section does not define how the pages registered by these methods are used, beyond the requirements on how to process the url value (see above). To some extent, the processing model for navigating across documents defines some cases where these methods are relevant, but in general UAs may use this information wherever they would otherwise consider handing content to native plugins or helper applications.

UAs must not use registered content handlers to handle content that was returned as part of a non-GET transaction (or rather, as part of any non-idempotent transaction), as the remote site would not be able to fetch the same data.


In addition to the registration methods, there are also methods for determining if particular handlers have been registered, and for unregistering handlers.

state = window . navigator . isProtocolHandlerRegistered(scheme, url)
state = window . navigator . isContentHandlerRegistered(mimeType, url)

Returns one of the following strings describing the state of the handler given by the arguments:

new
Indicates that no attempt has been made to register the given handler (or that the handler has been unregistered). It would be appropriate to promote the availability of the handler or to just automatically register the handler.
registered
Indicates that the given handler has been registered or that the site is blocked from registering the handler. Trying to register the handler again would have no effect.
declined
Indicates that the given handler has been offered but was rejected. Trying to register the handler again may prompt the user again.
window . navigator . unregisterProtocolHandler(scheme, url)
window . navigator . unregisterContentHandler(mimeType, url)

Unregisters the handler given by the arguments.

The isProtocolHandlerRegistered() method must return the handler state string that most closely describes the current state of the handler described by the two arguments to the method, where the first argument gives the scheme and the second gives the string used to build the URL of the page that will handle the requests. (This is a fingerprinting vector.)

The first argument must be compared to the schemes for which custom protocol handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The isContentHandlerRegistered() method must return the handler state string that most closely describes the current state of the handler described by the two arguments to the method, where the first argument gives the MIME type and the second gives the string used to build the URL of the page that will handle the requests. (This is a fingerprinting vector.)

The first argument must be compared to the MIME types for which custom content handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The handler state strings are the following strings. Each string describes several situations, as given by the following list.

new
The described handler has never been registered for the given scheme or type.
The described handler was once registered for the given scheme or type, but the site has since unregistered it. If the handler were to be reregistered, the user would be notified accordingly.
The described handler was once registered for the given scheme or type, but the site has since unregistered it, but the user has indicated that the site is to be blocked from registering the type again, so the user agent would ignore further registration attempts.
registered
An attempt was made to register the described handler for the given scheme or type, but the user has not yet been notified, and the user agent would ignore further registration attempts. (Maybe the user agent batches registration requests to display them when the user requests to be notified about them, and the user has not yet requested that the user agent notify it of the previous registration attempt.)
The described handler is registered for the given scheme or type (maybe, or maybe not, as the default handler).
The described handler is permanently blocked from being (re)registered. (Maybe the user marked the registration attempt as spam, or blocked the site for other reasons.)
declined
An attempt was made to register the described handler for the given scheme or type, but the user has not yet been notified; however, the user might be notified if another registration attempt were to be made. (Maybe the last registration attempt was made while the page was in the background and the user closed the page without looking at it, and the user agent requires confirmation for this registration attempt.)
An attempt was made to register the described handler for the given scheme or type, but the user has not yet responded.
An attempt was made to register the described handler for the given scheme or type, but the user declined the offer. The user has not indicated that the handler is to be permanently blocked, however, so another attempt to register the described handler might result in the user being prompted again.
The described handler was once registered for the given scheme or type, but the user has since removed it. The user has not indicated that the handler is to be permanently blocked, however, so another attempt to register the described handler might result in the user being prompted again.

The unregisterProtocolHandler() method must unregister the handler described by the two arguments to the method, where the first argument gives the scheme and the second gives the string used to build the URL of the page that will handle the requests.

The first argument must be compared to the schemes for which custom protocol handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The unregisterContentHandler() method must unregister the handler described by the two arguments to the method, where the first argument gives the MIME type and the second gives the string used to build the URL of the page that will handle the requests.

The first argument must be compared to the MIME types for which custom content handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The second argument of the four methods described above must be preprocessed as follows:

  1. If the string does not contain the substring "%s", abort these steps. There's no matching handler.

  2. Resolve the string relative to the API base URL specified by the entry settings object.

  3. If this fails, then throw a SyntaxError exception, aborting the method.

  4. If the resulting absolute URL's origin is not the same origin as the origin specified by the entry settings object, throw a SecurityError exception, aborting the method.

  5. Return the resulting absolute URL as the result of preprocessing the argument.

Security and privacy

These mechanisms can introduce a number of concerns, in particular privacy concerns.

Hijacking all Web usage. User agents should not allow schemes that are key to its normal operation, such as http or https, to be rerouted through third-party sites. This would allow a user's activities to be trivially tracked, and would allow user information, even in secure connections, to be collected.

Hijacking defaults. User agents are strongly urged to not automatically change any defaults, as this could lead the user to send data to remote hosts that the user is not expecting. New handlers registering themselves should never automatically cause those sites to be used.

Registration spamming. User agents should consider the possibility that a site will attempt to register a large number of handlers, possibly from multiple domains (e.g. by redirecting through a series of pages each on a different domain, and each registering a handler for video/mpeg — analogous practices abusing other Web browser features have been used by pornography Web sites for many years). User agents should gracefully handle such hostile attempts, protecting the user.

Misleading titles. User agents should not rely wholly on the title argument to the methods when presenting the registered handlers to the user, since sites could easily lie. For example, a site hostile.example.net could claim that it was registering the "Cuddly Bear Happy Content Handler". User agents should therefore use the handler's domain in any UI along with any title.

Hostile handler metadata. User agents should protect against typical attacks against strings embedded in their interface, for example ensuring that markup or escape characters in such strings are not executed, that null bytes are properly handled, that over-long strings do not cause crashes or buffer overruns, and so forth.

Leaking Intranet URLs. The mechanism described in this section can result in secret Intranet URLs being leaked, in the following manner:

  1. The user registers a third-party content handler as the default handler for a content type.
  2. The user then browses his corporate Intranet site and accesses a document that uses that content type.
  3. The user agent contacts the third party and hands the third party the URL to the Intranet content.

No actual confidential file data is leaked in this manner, but the URLs themselves could contain confidential information. For example, the URL could be http://www.corp.example.com/upcoming-aquisitions/the-sample-company.egf, which might tell the third party that Example Corporation is intending to merge with The Sample Company. Implementors might wish to consider allowing administrators to disable this feature for certain subdomains, content types, or schemes.

Leaking secure URLs. User agents should not send HTTPS URLs to third-party sites registered as content handlers without the user's informed consent, for the same reason that user agents sometimes avoid sending Referer (sic) HTTP headers from secure sites to third-party sites.

Leaking credentials. User agents must never send username or password information in the URLs that are escaped and included sent to the handler sites. User agents may even avoid attempting to pass to Web-based handlers the URLs of resources that are known to require authentication to access, as such sites would be unable to access the resources in question without prompting the user for credentials themselves (a practice that would require the user to know whether to trust the third-party handler, a decision many users are unable to make or even understand).

Interface interference. User agents should be prepared to handle intentionally long arguments to the methods. For example, if the user interface exposed consists of an "accept" button and a "deny" button, with the "accept" binding containing the name of the handler, it's important that a long name not cause the "deny" button to be pushed off the screen.

Fingerprinting users. Since a site can detect if it has attempted to register a particular handler or not, whether or not the user responds, the mechanism can be used to store data. User agents are therefore strongly urged to treat registrations in the same manner as cookies: clearing cookies for a site should also clear all registrations for that site, and disabling cookies for a site should also disable registrations.

Sample user interface

This section is non-normative.

A simple implementation of this feature for a desktop Web browser might work as follows.

The registerContentHandler() method could display a modal dialog box:

The modal dialog box could have the title 'Content Handler Registration', and could say 'This Web page: Kittens at work http://kittens.example.org/ ...would like permission to handle files of type: application/x-meowmeow using the following Web-based application: Kittens-at-work displayer http://kittens.example.org/?show=%s Do you trust the administrators of the "kittens.example.org" domain?' with two buttons, 'Trust kittens.example.org' and 'Cancel'.

In this dialog box, "Kittens at work" is the title of the page that invoked the method, "http://kittens.example.org/" is the URL of that page, "application/x-meowmeow" is the string that was passed to the registerContentHandler() method as its first argument (mimeType), "http://kittens.example.org/?show=%s" was the second argument (url), and "Kittens-at-work displayer" was the third argument (title).

If the user clicks the Cancel button, then nothing further happens. If the user clicks the "Trust" button, then the handler is remembered.

When the user then attempts to fetch a URL that uses the "application/x-meowmeow" MIME type, then it might display a dialog as follows:

The dialog box could have the title 'Unknown File Type' and could say 'You have attempted to access:' followed by a URL, followed by a prompt such as 'How would you like FerretBrowser to handle this resource?' with three radio buttons, one saying 'Contact the FerretBrowser plugin registry to see if there is an official way to handle this resource.', one saying 'Pass this URL to a local application' with an application selector, and one saying 'Pass this URL to the "Kittens-at-work displayer" application at "kittens.example.org"', with a checkbox labeled 'Always do this for resources using the "application/x-meowmeow" type in future.', and with two buttons, 'Ok' and 'Cancel'.

In this dialog, the third option is the one that was primed by the site registering itself earlier.

If the user does select that option, then the browser, in accordance with the requirements described in the previous two sections, will redirect the user to "http://kittens.example.org/?show=data%3Aapplication/x-meowmeow;base64,S2l0dGVucyBhcmUgdGhlIGN1dGVzdCE%253D".

The registerProtocolHandler() method would work equivalently, but for schemes instead of unknown content types.

Manually releasing the storage mutex

[NoInterfaceObject]
interface NavigatorStorageUtils {
  readonly attribute boolean cookieEnabled;
  void yieldForStorageUpdates();
};
window . navigator . cookieEnabled

Returns false if setting a cookie will be ignored, and true otherwise.

window . navigator . yieldForStorageUpdates()

If a script uses the document.cookie API, or the localStorage API, the browser will block other scripts from accessing cookies or storage until the first script finishes.

Calling the navigator.yieldForStorageUpdates() method tells the user agent to unblock any other scripts that may be blocked, even though the script hasn't returned.

Values of cookies and items in the Storage objects of localStorage attributes can change after calling this method, whence its name.

The cookieEnabled attribute must return true if the user agent attempts to handle cookies according to the cookie specification, and false if it ignores cookie change requests. [[!COOKIES]]

The yieldForStorageUpdates() method, when invoked, must, if the storage mutex is owned by the event loop of the task that resulted in the method being called, release the storage mutex so that it is once again free. Otherwise, it must do nothing.

Plugins

[NoInterfaceObject]
interface NavigatorPlugins {
  [SameObject] readonly attribute PluginArray plugins;
  [SameObject] readonly attribute MimeTypeArray mimeTypes;
  readonly attribute boolean javaEnabled;
};

interface PluginArray {
  void refresh(optional boolean reload = false);
  readonly attribute unsigned long length;
  getter Plugin? item(unsigned long index);
  getter Plugin? namedItem(DOMString name);
};

interface MimeTypeArray {
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

interface Plugin {
  readonly attribute DOMString name;
  readonly attribute DOMString description;
  readonly attribute DOMString filename;
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

interface MimeType {
  readonly attribute DOMString type;
  readonly attribute DOMString description;
  readonly attribute DOMString suffixes; // comma-separated
  readonly attribute Plugin enabledPlugin;
};
window . navigator . plugins . refresh( [ refresh ] )

Updates the lists of supported plugins and MIME types for this page, and reloads the page if the lists have changed.

window . navigator . plugins . length

Returns the number of plugins, represented by Plugin objects, that the user agent reports.

plugin = window . navigator . plugins . item(index)
window . navigator . plugins[index]

Returns the specified Plugin object.

plugin = window . navigator . plugins . item(name)
window . navigator . plugins[name]

Returns the Plugin object for the plugin with the given name.

window . navigator . mimeTypes . length

Returns the number of MIME types, represented by MimeType objects, supported by the plugins that the user agent reports.

mimeType = window . navigator . mimeTypes . item(index)
window . navigator . mimeTypes[index]

Returns the specified MimeType object.

mimeType = window . navigator . mimeTypes . item(name)
window . navigator . mimeTypes[name]

Returns the MimeType object for the given MIME type.

plugin . name

Returns the plugin's name.

plugin . description

Returns the plugin's description.

plugin . filename

Returns the plugin library's filename, if applicable on the current platform.

plugin . length

Returns the number of MIME types, represented by MimeType objects, supported by the plugin.

mimeType = plugin . item(index)
plugin[index]

Returns the specified MimeType object.

mimeType = plugin . item(name)
plugin[name]

Returns the MimeType object for the given MIME type.

mimeType . type

Returns the MIME type.

mimeType . description

Returns the MIME type's description.

mimeType . suffixes

Returns the MIME type's typical file extensions, in a comma-separated list.

mimeType . enabledPlugin

Returns the Plugin object that implements this MIME type.

window . navigator . javaEnabled

Returns true if there's a plugin that supports the MIME type "application/x-java-vm".

The navigator.plugins attribute must return a PluginArray object.

The navigator.mimeTypes attribute must return a MimeTypeArray object.


A PluginArray object represents none, some, or all of the plugins supported by the user agent, each of which is represented by a Plugin object. Each of these Plugin objects may be hidden plugins. A hidden plugin can't be enumerated, but can still be inspected by using its name.

The fewer plugins are represented by the PluginArray object, and of those, the more that are hidden, the more the user's privacy will be protected. Each exposed plugin increases the number of bits that can be derived for fingerprinting. Hiding a plugin helps, but unless it is an extremely rare plugin, it is likely that a site attempting to derive the list of plugins can still determine whether the plugin is supported or not by probing for it by name (the names of popular plugins are widely known). Therefore not exposing a plugin at all is preferred. Unfortunately, many legacy sites use this feature to determine, for example, which plugin to use to play video. Not exposing any plugins at all might therefore not be entirely plausible.

The PluginArray objects created by a user agent must not be live. The set of plugins represented by the objects must not change once an object is created, except when it is updated by the refresh() method.

Each plugin represented by a PluginArray can support a number of MIME types. For each such plugin, the user agent must pick one or more of these MIME types to be those that are explicitly supported.

The explicitly supported MIME types of a plugin are those that are exposed through the Plugin and MimeTypeArray interfaces. As with plugins themselves, any variation between users regarding what is exposed allows sites to fingerprint users. User agents are therefore encouraged to expose the same MIME types for all users of a plugin, regardless of the actual types supported... at least, within the constraints imposed by compatibility with legacy content.

The supported property indices of a PluginArray object are the numbers from zero to the number of non-hidden plugins represented by the object, if any. (This is a fingerprinting vector.)

The length attribute must return the number of non-hidden plugins represented by the object. (This is a fingerprinting vector.)

The item() method of a PluginArray object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the Plugin objects representing the non-hidden plugins represented by the PluginArray object.

  2. Sort list alphabetically by the name of each Plugin.

  3. Return the indexth entry in list.

It is important for privacy that the order of plugins not leak additional information, e.g. the order in which plugins were installed.

The supported property names of a PluginArray object are the values of the name attributes of all the Plugin objects represented by the PluginArray object. The properties exposed in this way must be unenumerable. (This is a fingerprinting vector.)

The namedItem() method of a PluginArray object must return null if the argument is not one of the object's supported property names, and otherwise must return the Plugin object, of those represented by the PluginArray object, that has a name equal to the method's argument.

The refresh() method of the PluginArray object of a Navigator object, when invoked, must check to see if any plugins have been installed or reconfigured since the user agent created the PluginArray object. If so, and the method's argument is true, then the user agent must act as if the location.reload() method was called instead. Otherwise, the user agent must update the PluginArray object and MimeTypeArray object created for attributes of that Navigator object, and the Plugin and MimeType objects created for those PluginArray and MimeTypeArray objects, using the same Plugin objects for cases where the name is the same, and the same MimeType objects for cases where the type is the same, and creating new objects for cases where there were no matching objects immediately prior to the refresh() call. Old Plugin and MimeType objects must continue to return the same values that they had prior to the update, though naturally now the data is stale and may appear inconsistent (for example, an old MimeType entry might list as its enabledPlugin a Plugin object that no longer lists that MimeType as a supported MimeType).


A MimeTypeArray object represents the MIME types explicitly supported by plugins supported by the user agent, each of which is represented by a MimeType object.

The MimeTypeArray objects created by a user agent must not be live. The set of MIME types represented by the objects must not change once an object is created, except when it is updated by the PluginArray object's refresh() method.

The supported property indices of a MimeTypeArray object are the numbers from zero to the number of MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any. (This is a fingerprinting vector.)

The length attribute must return the number of MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any. (This is a fingerprinting vector.)

The item() method of a MimeTypeArray object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the MimeType objects representing the MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any.

  2. Sort list alphabetically by the type of each MimeType.

  3. Return the indexth entry in list.

It is important for privacy that the order of MIME types not leak additional information, e.g. the order in which plugins were installed.

The supported property names of a MimeTypeArray object are the values of the type attributes of all the MimeType objects represented by the MimeTypeArray object. The properties exposed in this way must be unenumerable. (This is a fingerprinting vector.)

The namedItem() method of a MimeTypeArray object must return null if the argument is not one of the object's supported property names, and otherwise must return the MimeType object that has a type equal to the method's argument.


A Plugin object represents a plugin. It has several attributes to provide details about the plugin, and can be enumerated to obtain the list of MIME types that it explicitly supports.

The Plugin objects created by a user agent must not be live. The set of MIME types represented by the objects, and the values of the objects' attributes, must not change once an object is created, except when updated by the PluginArray object's refresh() method.

The reported MIME types for a Plugin object are the MIME types explicitly supported by the corresponding plugin when this object was last created or updated by PluginArray.refresh(), whichever happened most recently.

The supported property indices of a Plugin object are the numbers from zero to the number of reported MIME types. (This is a fingerprinting vector.)

The length attribute must return the number of reported MIME types. (This is a fingerprinting vector.)

The item() method of a Plugin object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the MimeType objects representing the reported MIME types.

  2. Sort list alphabetically by the type of each MimeType.

  3. Return the indexth entry in list.

It is important for privacy that the order of MIME types not leak additional information, e.g. the order in which plugins were installed.

The supported property names of a Plugin object are the values of the type attributes of the MimeType objects representing the reported MIME types. The properties exposed in this way must be unenumerable. (This is a fingerprinting vector.)

The namedItem() method of a Plugin object must return null if the argument is not one of the object's supported property names, and otherwise must return the MimeType object that has a type equal to the method's argument.

The name attribute must return the plugin's name.

The description and filename attributes must return user-agent-defined (or, in all likelihood, plugin-defined) strings. In each case, the same string must be returned each time, except that the strings returned may change when the PluginArray.refresh() method updates the object.

If the values returned by the description or filename attributes vary between versions of a plugin, they can be used both as a fingerprinting vector and, even more importantly, as a trivial way to determine what security vulnerabilities a plugin (and thus a browser) may have. It is thus highly recommended that the description attribute just return the same value as the name attribute, and that the filename attribute return the empty string. (This is a fingerprinting vector.)


A MimeType object represents a MIME type that is, or was, explicitly supported by a plugin.

The MimeType objects created by a user agent must not be live. The values of the objects' attributes must not change once an object is created, except when updated by the PluginArray object's refresh() method.

The type attribute must return the valid MIME type with no parameters describing the MIME type.

The description and suffixes attributes must return user-agent-defined (or, in all likelihood, plugin-defined) strings. In each case, the same string must be returned each time, except that the strings returned may change when the PluginArray.refresh() method updates the object.

If the values returned by the description or suffxies attributes vary between versions of a plugin, they can be used both as a fingerprinting vector and, even more importantly, as a trivial way to determine what security vulnerabilities a plugin (and thus a browser) may have. It is thus highly recommended that the description attribute just return the same value as the type attribute, and that the suffixes attribute return the empty string. (This is a fingerprinting vector.)

Commas in the suffixes attribute are interpreted as separating subsequent filename extensions, as in "htm,html".

The enabledPlugin attribute must return the Plugin object that represents the plugin that explicitly supported the MIME type that this MimeType object represents when this object was last created or updated by PluginArray.refresh(), whichever happened most recently.


The navigator.javaEnabled attribute must return true if the user agent supports a plugin that supports the MIME type "application/x-java-vm"; otherwise it must return false. (This is a fingerprinting vector.)

The External interface

The external attribute of the Window interface must return an instance of the External interface.

interface External {
  void AddSearchProvider(DOMString engineURL);
  unsigned long IsSearchProviderInstalled(DOMString engineURL);
};

For historical reasons, members on this interface are capitalized.

window . external . AddSearchProvider( url )

Adds the search engine described by the OpenSearch description document at url. [[!OPENSEARCH]]

The OpenSearch description document has to be on the same server as the script that calls this method.

installed = window . external . IsSearchProviderInstalled( url )

Returns a value based on comparing url to the URLs of the results pages of the installed search engines.

0
None of the installed search engines match url.
1
One or more installed search engines match url, but none are the user's default search engine.
2
The user's default search engine matches url.

The url is compared to the URLs of the results pages of the installed search engines using a prefix match. Only results pages on the same domain as the script that calls this method are checked.

Another way of exposing search engines using OpenSearch description documents is using a link element with the search link type.

The AddSearchProvider() method, when invoked, must run the following steps:

  1. Optionally, abort these steps. User agents may implement the method as a stub method that never does anything, or may arbitrarily ignore invocations with particular arguments for security, privacy, or usability reasons.

  2. Resolve the value of the method's first argument relative to the API base URL specified by the entry settings object.

  3. If this fails, abort these steps.

  4. Process the resulting absolute URL as the URL to an OpenSearch description document. [[!OPENSEARCH]]

The IsSearchProviderInstalled() method, when invoked, must run the following steps: (This is a fingerprinting vector.)

  1. Optionally, return 0 and abort these steps. User agents may implement the method as a stub method that never returns a non-zero value, or may arbitrarily ignore invocations with particular arguments for security, privacy, or usability reasons.

  2. If the origin specified by the entry settings object is an opaque identifier (i.e. it has no host component), then return 0 and abort these steps.

  3. Let host1 be the host component of the origin specified by the entry settings object.

  4. Resolve the scriptURL argument relative to the API base URL specified by the entry settings object.

  5. If this fails, return 0 and abort these steps.

  6. Let host2 be the host component of the resulting parsed URL.

  7. If the longest suffix in the Public Suffix List that matches the end of host1 is different than the longest suffix in the Public Suffix List that matches the end of host2, then return 0 and abort these steps. [[!PSL]]

    If the next domain component of host1 and host2 after their common suffix are not the same, then return 0 and abort these steps.

  8. Let search engines be the list of search engines known by the user agent and made available to the user by the user agent for which the resulting absolute URL is a prefix match of the search engine's URL, if any. For search engines registered using OpenSearch description documents, the URL of the search engine corresponds to the URL given in a Url element whose rel attribute is "results" (the default). [[!OPENSEARCH]]

  9. If search engines is empty, return 0 and abort these steps.

  10. If the user's default search engine (as determined by the user agent) is one of the search engines in search engines, then return 2 and abort these steps.

  11. Return 1.

Images

[Exposed=(Window,Worker)]
interface ImageBitmap {
  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
};

typedef (HTMLImageElement or
         HTMLVideoElement or
         HTMLCanvasElement or
         Blob or
         ImageData or
         CanvasRenderingContext2D or
         ImageBitmap) ImageBitmapSource;

[NoInterfaceObject, Exposed=(Window,Worker)]
interface ImageBitmapFactories {
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image);
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, long sx, long sy, long sw, long sh);
};
Window implements ImageBitmapFactories;
WorkerGlobalScope implements ImageBitmapFactories;

An ImageBitmap object represents a bitmap image that can be painted to a canvas without undue latency.

The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or system RAM, the latency is probably acceptable.

promise = Window . createImageBitmap(image [, sx, sy, sw, sh ] )

Takes image, which can be an img element, video, or canvas element, a Blob object, an ImageData object, a CanvasRenderingContext2D object, or another ImageBitmap object, and returns a Promise that is resolved when a new ImageBitmap is created.

If no ImageBitmap object can be constructed, for example because the provided image data is not actually an image, then the promise is rejected instead.

If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with any pixels missing in the original replaced by transparent black. These coordinates are in the source image's pixel coordinate space, not in CSS pixels.

Rejects the promise with an InvalidStateError exception if the source image is not in a valid state (e.g. an img element that hasn't finished loading, or a CanvasRenderingContext2D object whose bitmap data has zero length along one or both dimensions, or an ImageData object whose data is data attribute has been neutered). Rejects the promise with a SecurityError exception if the script is not allowed to access the image data of the source image (e.g. a video that is CORS-cross-origin, or a canvas being drawn on by a script in a worker from another origin).

imageBitmap . width

Returns the intrinsic width of the image, in CSS pixels.

imageBitmap . height

Returns the intrinsic height of the image, in CSS pixels.

An ImageBitmap object always has associated bitmap data, with a width and a height. However, it is possible for this data to be corrupted. If an ImageBitmap object's media data can be decoded without errors, it is said to be fully decodable.

An ImageBitmap object can be obtained from a variety of different objects, using the createImageBitmap() method. When invoked, the method must act as follows:

If image is an img element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

  2. If the img element is not completely available, then return a promise rejected with an InvalidStateError exception and abort these steps.

  3. If the origin of the img element's image is not the same origin as the origin specified by the entry settings object, then return a promise rejected with a SecurityError exception and abort these steps.

  4. If the img element's media data is not a bitmap (e.g. it's a vector graphic), then return a promise rejected with an InvalidStateError exception and abort these steps.

  5. Create a new ImageBitmap object.

  6. Let the ImageBitmap object's bitmap data be a copy of the img element's media data, cropped to the source rectangle. If this is an animated image, the ImageBitmap object's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.

  7. Return a new Promise, but continue running these steps in parallel.

  8. Resolve the Promise with the new ImageBitmap object as the value.

If image is a video element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

  2. If the video element's networkState attribute is NETWORK_EMPTY, then return a promise rejected with an InvalidStateError exception and abort these steps.

  3. If the origin of the video element is not the same origin as the origin specified by the entry settings object, then return a promise rejected with a SecurityError exception and abort these steps.

  4. If the video element's readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return a promise rejected with an InvalidStateError exception and abort these steps.

  5. Create a new ImageBitmap object.

  6. Let the ImageBitmap object's bitmap data be a copy of the frame at the current playback position, at the media resource's intrinsic width and intrinsic height (i.e. after any aspect-ratio correction has been applied), cropped to the source rectangle.

  7. Return a new Promise, but continue running these steps in parallel.

  8. Resolve the Promise with the new ImageBitmap object as the value.

If image is a canvas element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

  2. If the canvas element's bitmap data does not have its origin-clean flag set, then return a promise rejected with an InvalidStateError exception and abort these steps.

  3. If the canvas element's bitmap has either a horizontal dimension or a vertical dimension equal to zero, then return a promise rejected with an InvalidStateError exception and abort these steps.

  4. Create a new ImageBitmap object.

  5. Let the ImageBitmap object's bitmap data be a copy of the canvas element's bitmap data, cropped to the source rectangle.

  6. Return a new Promise, but continue running these steps in parallel.

  7. Resolve the Promise with the new ImageBitmap object as the value.

If image is a Blob object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

  2. If the Blob object has been disabled through the close() method, then return a promise rejected with an InvalidStateError exception and abort these steps.

  3. Return a new Promise, but continue running these steps in parallel.

  4. Read the Blob object's data. If an error occurs during reading of the object, then reject the Promise's associated resolver, with null as the value, and abort these steps.

  5. Apply the image sniffing rules to determine the file format of the image data, with MIME type of the Blob (as given by the Blob object's type attribute) giving the official type.

  6. If the image data is not in a supported file format (e.g. it's not actually an image at all), or if the image data is corrupted in some fatal way such that the image dimensions cannot be obtained, then reject the Promise's associated resolver, with null as the value, and abort these steps.

  7. Create a new ImageBitmap object.

  8. Let the ImageBitmap object's bitmap data be the image data read from the Blob object, cropped to the source rectangle. If this is an animated image, the ImageBitmap object's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.

  9. Resolve the Promise with the new ImageBitmap object as the value.

If image is an ImageData object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

  2. If the image object's data attribute has been neutered, return a promise rejected with an InvalidStateError exception and abort these steps.

  3. Create a new ImageBitmap object.

  4. Let the ImageBitmap object's bitmap data be the image data given by the ImageData object, cropped to the source rectangle.

  5. Return a new Promise, but continue running these steps in parallel.

  6. Resolve the Promise with the new ImageBitmap object as the value.

If image is a CanvasRenderingContext2D object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

  2. If the CanvasRenderingContext2D object's scratch bitmap does not have its origin-clean flag set, then return a promise rejected with an InvalidStateError exception and abort these steps.

  3. If the CanvasRenderingContext2D object's scratch bitmap has either a horizontal dimension or a vertical dimension equal to zero, then return a promise rejected with an InvalidStateError exception and abort these steps.

  4. Create a new ImageBitmap object.

  5. Let the ImageBitmap object's bitmap data be a copy of the CanvasRenderingContext2D object's scratch bitmap, cropped to the source rectangle.

  6. Return a new Promise, but continue running these steps in parallel.

  7. Resolve the Promise with the new ImageBitmap object as the value.

If image is an ImageBitmap object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

  2. Create a new ImageBitmap object.

  3. Let the ImageBitmap object's bitmap data be a copy of the image argument's bitmap data, cropped to the source rectangle.

  4. Return a new Promise, but continue running these steps in parallel.

  5. Resolve the Promise with the new ImageBitmap object as the value.

When the steps above require that the user agent crop bitmap data to the source rectangle, the user agent must run the following steps:

  1. Let input be the image data being cropped.

  2. If the sx, sy, sw, and sh arguments are omitted, return input.

  3. Place input on an infinite transparent black grid plane, positioned so that it's top left corner is at the origin of the plane, with the x-coordinate increasing to the right, and the y-coordinate increasing down, and with each pixel in the input image data occupying a cell on the plane's grid.

  4. Let output be the rectangle on the plane denoted by the rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).

    If either sw or sh are negative, then the top-left corner of this rectangle will be to the left or above the (sx, sy) point. If any of the pixels on this rectangle are outside the area where the input bitmap was placed, then they will be transparent black in output.

  5. Return output.

The width attribute must return the ImageBitmap object's width, in CSS pixels.

The height attribute must return the ImageBitmap object's height, in CSS pixels.

Using this API, a sprite sheet can be precut and prepared:

var sprites = {};
function loadMySprites() {
  var image = new Image();
  image.src = 'mysprites.png';
  var resolver;
  var promise = new Promise(function (arg) { resolver = arg });
  image.onload = function () {
    resolver(Promise.all(
      createImageBitmap(image,  0,  0, 40, 40).then(function (image) { sprites.woman = image }),
      createImageBitmap(image, 40,  0, 40, 40).then(function (image) { sprites.man   = image }),
      createImageBitmap(image, 80,  0, 40, 40).then(function (image) { sprites.tree  = image }),
      createImageBitmap(image,  0, 40, 40, 40).then(function (image) { sprites.hut   = image }),
      createImageBitmap(image, 40, 40, 40, 40).then(function (image) { sprites.apple = image }),
      createImageBitmap(image, 80, 40, 40, 40).then(function (image) { sprites.snake = image }),
    ));
  };
  return promise;
}

function runDemo() {
  var canvas = document.querySelector('canvas#demo');
  var context = canvas.getContext('2d');
  context.drawImage(sprites.tree, 30, 10);
  context.drawImage(sprites.snake, 70, 10);
}

loadMySprites().then(runDemo);

Animation Frames

Each Document has a list of animation frame callbacks, which must be initially empty, and an animation frame callback identifier, which is a number which must initially be zero.

When the requestAnimationFrame() method is called, the user agent must run the following steps:

  1. Let document be the Window object's Document object.

  2. Increment document's animation frame callback identifier by one.

  3. Append the method's argument to document's list of animation frame callbacks, associated with document's animation frame callback identifier's current value.

  4. Return document's animation frame callback identifier's current value.

When the cancelAnimationFrame() method is called, the user agent must run the following steps:

  1. Let document be the Window object's Document object.

  2. Find the entry in document's list of animation frame callbacks that is associated with the value given by the method's argument.

  3. If there is such an entry, remove it from document's list of animation frame callbacks.

When the user agent is to run the animation frame callbacks for a Document doc with a timestamp now, it must run the following steps:

  1. Let callbacks be a list of the entries in doc's list of animation frame callbacks, in the order in which they were added to the list.

  2. Set doc's list of animation frame callbacks to the empty list.

  3. For each entry in callbacks, in order: invoke the callback, passing now as the only argument, and if an exception is thrown, report the exception. [[!WEBIDL]]

Browsing the Web

Navigating across documents

Certain actions cause the browsing context to navigate to a new resource. A user agent may provide various ways for the user to explicitly cause a browsing context to navigate, in addition to those defined in this specification.

For example, following a hyperlink, form submission, and the window.open() and location.assign() methods can all cause a browsing context to navigate.

A resource has a URL, but that might not be the only information necessary to identify it. For example, a form submission that uses HTTP POST would also have the HTTP method and payload. Similarly, an iframe srcdoc document needs to know the data it is to use.

Navigation always involves source browsing context, which is the browsing context which was responsible for starting the navigation.

When a browsing context is navigated to a new resource, the user agent must run the following steps:

  1. Release the storage mutex.

  2. If there is a preexisting attempt to navigate the browsing context, and the source browsing context is the same as the browsing context being navigated, and that attempt is currently running the unload a document algorithm, and the origin of the URL of the resource being loaded in that navigation is not the same origin as the origin of the URL of the resource being loaded in this navigation, then abort these steps without affecting the preexisting attempt to navigate the browsing context.

  3. If a task queued by the traverse the history by a delta algorithm is running the unload a document algorithm for the active document of the browsing context being navigated, then abort these steps without affecting the unload a document algorithm or the aforementioned history traversal task.

  4. If the prompt to unload a document algorithm is being run for the active document of the browsing context being navigated, then abort these steps without affecting the prompt to unload a document algorithm.

  5. Let gone async be false.

    The handle redirects step later in this algorithm can in certain cases jump back to the step labeled fragment identifiers. Since, between those two steps, this algorithm goes from operating synchronously in the context of the calling task to operating in parallel independent of the event loop, some of the intervening steps need to be able to handle both being run as part of a task and running in parallel. The gone async flag is thus used to make these steps aware of which mode they are operating in.

  6. If gone async is false, cancel any preexisting but not yet mature attempt to navigate the browsing context, including canceling any instances of the fetch algorithm started by those attempts. If one of those attempts has already created and initialised a new Document object, abort that Document also. (Navigation attempts that have matured already have session history entries, and are therefore handled during the update the session history with the new page algorithm, later.)

  7. If the new resource is to be handled using a mechanism that does not affect the browsing context, e.g. ignoring the navigation request altogether because the specified scheme is not one of the supported protocols, then abort these steps and proceed with that mechanism instead.

  8. If gone async is false, prompt to unload the Document object. If the user refused to allow the document to be unloaded, then abort these steps.

    If this instance of the navigation algorithm gets canceled while this step is running, the prompt to unload a document algorithm must nonetheless be run to completion.

  9. If gone async is false, abort the active document of the browsing context.

  10. If the new resource is to be handled by displaying some sort of inline content, e.g. an error message because the specified scheme is not one of the supported protocols, or an inline prompt to allow the user to select a registered handler for the given scheme, then display the inline content and abort these steps.

    In the case of a registered handler being used, the algorithm will be reinvoked with a new URL to handle the request.

  11. If the browsing context being navigated is a nested browsing context, then put it in the delaying load events mode.

    The user agent must take this nested browsing context out of the delaying load events mode when this navigation algorithm later matures, or when it terminates (whether due to having run all the steps, or being canceled, or being aborted), whichever happens first.

  12. This is the step that attempts to obtain the resource, if necessary. Jump to the first appropriate substep:

    If the resource has already been obtained (e.g. because it is being used to populate an object element's new child browsing context)

    Skip this step. The data is already available.

    If the new resource is a URL whose scheme is javascript

    Queue a task to run these "javascript: URL" steps, associated with the active document of the browsing context being navigated:

    1. If the origin of the source browsing context is not the same origin as the origin of the active document of the browsing context being navigated, then act as if the result of evaluating the script was the void value, and jump to the step labeled process results below.

    2. Apply the URL parser to the URL being navigated.

    3. Let parsed URL be the result of the URL parser.

    4. Let script source be the empty string.

    5. Append parsed URL's scheme data component to script source.

    6. If parsed URL's query component is not null, then first append a U+003F QUESTION MARK character (?) to script source, and then append parsed URL's query component to script source.

    7. If parsed URL's fragment component is not null, then first append a U+0023 NUMBER SIGN character (#) to script source, and then append parsed URL's fragment component to script source.

    8. Replace script source with the result of applying the percent decode algorithm to script source.

    9. Replace script source with the result of applying the UTF-8 decode algorithm to script source.

    10. Let address be the address of the active document of the browsing context being navigated.

    11. Create a script, using script source as the script source, address as the script source URL, JavaScript as the scripting language, and the environment settings object of the Window object of the active document of the browsing context being navigated.

      Let result be the return value of the code entry-point of this script. If an exception was thrown, let result be void instead. (The result will be void also if scripting is disabled.)

    12. Process results: If the result of executing the script is void (there is no return value), then the result of obtaining the resource for the URL is equivalent to an HTTP resource with an HTTP 204 No Content response.

      Otherwise, the result of obtaining the resource for the URL is equivalent to an HTTP resource with a 200 OK response whose Content-Type metadata is text/html and whose response body is the return value converted to a string value.

      When it comes time to set the document's address in the navigation algorithm, use address as the override URL.

    The task source for this task is the DOM manipulation task source.

    So for example a javascript: URL in an href attribute of an a element would only be evaluated when the link was followed, while such a URL in the src attribute of an iframe element would be evaluated in the context of the iframe's own nested browsing context when the iframe is being set up; once evaluated, its return value (if it was not void) would replace that browsing context's Document, thus also changing the Window object of that browsing context.

    If the new resource is to be fetched using HTTP GET or equivalent, and there are relevant application caches that are identified by a URL with the same origin as the URL in question, and that have this URL as one of their entries, excluding entries marked as foreign, and whose mode is fast, and the user agent is not in a mode where it will avoid using application caches

    Fetch the resource from the most appropriate application cache of those that match.

    For example, imagine an HTML page with an associated application cache displaying an image and a form, where the image is also used by several other application caches. If the user right-clicks on the image and chooses "View Image", then the user agent could decide to show the image from any of those caches, but it is likely that the most useful cache for the user would be the one that was used for the aforementioned HTML page. On the other hand, if the user submits the form, and the form does a POST submission, then the user agent will not use an application cache at all; the submission will be made to the network.

    Otherwise

    Fetch the new resource, with the manual redirect flag set.

    If the steps above invoked the fetch algorithm, the following requirements also apply:

    If the resource is being fetched using a method other than one equivalent to HTTP's GET, or, if the navigation algorithm was invoked as a result of the form submission algorithm, then the fetching algorithm must be invoked from the origin of the active document of the source browsing context, if any.

    Otherwise, if the browsing context being navigated is a child browsing context, then the fetching algorithm must be invoked from the browsing context scope origin of the browsing context container of the browsing context being navigated, if it has one.

  13. If gone async is false, return to whatever algorithm invoked the navigation steps and continue running these steps asynchronously.

  14. Let gone async be true.

  15. Wait for one or more bytes to be available or for the user agent to establish that the resource in question is empty. During this time, the user agent may allow the user to cancel this navigation attempt or start other navigation attempts.

  16. Fallback in prefer-online mode: If the resource was not fetched from an application cache, and was to be fetched using HTTP GET or equivalent, and there are relevant application caches that are identified by a URL with the same origin as the URL in question, and that have this URL as one of their entries, excluding entries marked as foreign, and whose mode is prefer-online, and the user didn't cancel the navigation attempt during the earlier step, and the navigation attempt failed (e.g. the server returned a 4xx or 5xx status code or equivalent, or there was a DNS error), then:

    Let candidate be the resource identified by the URL in question from the most appropriate application cache of those that match.

    If candidate is not marked as foreign, then the user agent must discard the failed load and instead continue along these steps using candidate as the resource. The user agent may indicate to the user that the original page load failed, and that the page used was a previously cached resource.

    This does not affect the address of the resource from which Request-URIs are obtained, as used to set the document's referrer in the initialise the Document object steps below; they still use the value as computed by the original fetch algorithm.

  17. Fallback for fallback entries: If the resource was not fetched from an application cache, and was to be fetched using HTTP GET or equivalent, and its URL matches the fallback namespace of one or more relevant application caches, and the most appropriate application cache of those that match does not have an entry in its online whitelist that has the same origin as the resource's URL and that is a prefix match for the resource's URL, and the user didn't cancel the navigation attempt during the earlier step, and the navigation attempt failed (e.g. the server returned a 4xx or 5xx status code or equivalent, or there was a DNS error), then:

    Let candidate be the fallback resource specified for the fallback namespace in question. If multiple application caches match, the user agent must use the fallback of the most appropriate application cache of those that match.

    If candidate is not marked as foreign, then the user agent must discard the failed load and instead continue along these steps using candidate as the resource. The document's address, if appropriate, will still be the originally requested URL, not the fallback URL, but the user agent may indicate to the user that the original page load failed, that the page used was a fallback resource, and what the URL of the fallback resource actually is.

    This does not affect the address of the resource from which Request-URIs are obtained, as used to set the document's referrer in the initialise the Document object steps below; they still use the value as computed by the original fetch algorithm.

  18. Resource handling: If the resource's out-of-band metadata (e.g. HTTP headers), not counting any type information (such as the Content-Type HTTP header), requires some sort of processing that will not affect the browsing context, then perform that processing and abort these steps.

    Such processing might be triggered by, amongst other things, the following:

    • HTTP status codes (e.g. 204 No Content or 205 Reset Content)
    • Network errors (e.g. the network interface being unavailable)
    • Cryptographic protocol failures (e.g. an incorrect TLS certificate)

    Responses with HTTP Content-Disposition headers specifying the attachment disposition type must be handled as a download.

    HTTP 401 responses that do not include a challenge recognised by the user agent must be processed as if they had no challenge, e.g. rendering the entity body as if the response had been 200 OK.

    User agents may show the entity body of an HTTP 401 response even when the response does include a recognised challenge, with the option to login being included in a non-modal fashion, to enable the information provided by the server to be used by the user before authenticating. Similarly, user agents should allow the user to authenticate (in a non-modal fashion) against authentication challenges included in other responses such as HTTP 200 OK responses, effectively allowing resources to present HTTP login forms without requiring their use.

  19. Let type be the sniffed type of the resource.

  20. If the user agent has been configured to process resources of the given type using some mechanism other than rendering the content in a browsing context, then skip this step. Otherwise, if the type is one of the following types, jump to the appropriate entry in the following list, and process the resource as described there:

    "text/html"
    Follow the steps given in the HTML document section, and then, once they have completed, abort this navigate algorithm.
    "application/xml"
    "text/xml"
    "image/svg+xml"
    "application/xhtml+xml"
    Any other type ending in "+xml" that is not an explicitly supported XML type
    Follow the steps given in the XML document section. If that section determines that the content is not to be displayed as a generic XML document, then proceed to the next step in this overall set of steps. Otherwise, once the steps given in the XML document section have completed, abort this navigate algorithm.
    "text/plain"
    Follow the steps given in the plain text file section, and then, once they have completed, abort this navigate algorithm.
    "multipart/x-mixed-replace"
    Follow the steps given in the multipart/x-mixed-replace section, and then, once they have completed, abort this navigate algorithm.
    A supported image, video, or audio type
    Follow the steps given in the media section, and then, once they have completed, abort this navigate algorithm.
    A type that will use an external application to render the content in the browsing context
    Follow the steps given in the plugin section, and then, once they have completed, abort this navigate algorithm.

    An explicitly supported XML type is one for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in the browsing context, or a separate application), or one for which the user agent has dedicated processing rules (e.g. a Web browser with a built-in Atom feed viewer would be said to explicitly support the application/atom+xml MIME type), or one for which the user agent has a dedicated handler (e.g. one registered using registerContentHandler()).

    Setting the document's address: If there is no override URL, then any Document created by these steps must have its address set to the URL that was originally to be fetched, ignoring any other data that was used to obtain the resource (e.g. the entity body in the case of a POST submission is not part of the document's address, nor is the URL of the fallback resource in the case of the original load having failed and that URL having been found to match a fallback namespace). However, if there is an override URL, then any Document created by these steps must have its address set to that URL instead.

    An override URL is set when dereferencing a javascript: URL and when performing an overridden reload.

    Initialising a new Document object: when a Document is created as part of the above steps, the user agent will be required to additionally run the following algorithm after creating the new object:

    1. Create a new Window object, and associate it with the Document, with one exception: if the browsing context's only entry in its session history is the about:blank Document that was added when the browsing context was created, and navigation is occurring with replacement enabled, and that Document has the same origin as the new Document, then use the Window object of that Document instead, and change the document attribute of the Window object to point to the new Document.

    2. Set the document's referrer to the address of the resource from which Request-URIs are obtained as determined when the fetch algorithm obtained the resource, if that algorithm was used and determined such a value; otherwise, set it to the empty string.

    3. Implement the sandboxing for the Document.

    4. If the active sandboxing flag set of the Document's browsing context or any of its ancestor browsing contexts (if any) have the sandboxed fullscreen browsing context flag set, then skip this step.

      If the Document's browsing context has a browsing context container and either it is not an iframe element, or it does not have the allowfullscreen attribute specified, or its Document does not have the fullscreen enabled flag set, then also skip this step.

      Otherwise, set the Document's fullscreen enabled flag.

  21. Otherwise, the document's type is such that the resource will not affect the browsing context, e.g. because the resource is to be handed to an external application or because it is an unknown type that will be processed as a download. Process the resource appropriately.

When a resource is handled by passing its URL or data to an external software package separate from the user agent (e.g. handing a mailto: URL to a mail client, or a Word document to a word processor), user agents should attempt to mitigate the risk that this is an attempt to exploit the target software, e.g. by prompting the user to confirm that the source browsing context's active document's origin is to be allowed to invoke the specified software. In particular, if the navigate algorithm, when it was invoked, was not allowed to show a popup, the user agent should not invoke the external software package without prior user confirmation.

For example, there could be a vulnerability in the target software's URL handler which a hostile page would attempt to exploit by tricking a user into clicking a link.


Some of the sections below, to which the above algorithm defers in certain cases, require the user agent to update the session history with the new page. When a user agent is required to do this, it must queue a task (associated with the Document object of the current entry, not the new one) to run the following steps:

  1. Unload the Document object of the current entry, with the recycle parameter set to false.

    If this instance of the navigation algorithm is canceled while this step is running the unload a document algorithm, then the unload a document algorithm must be allowed to run to completion, but this instance of the navigation algorithm must not run beyond this step. (In particular, for instance, the cancelation of this algorithm does not abort any event dispatch or script execution occurring as part of unloading the document or its descendants.)

  2. If the navigation was initiated for entry update of an entry
    1. Replace the Document of the entry being updated, and any other entries that referenced the same document as that entry, with the new Document.

    2. Traverse the history to the new entry.

    This can only happen if the entry being updated is not the current entry, and can never happen with replacement enabled. (It happens when the user tried to traverse to a session history entry that no longer had a Document object.)

    Otherwise
    1. Remove all the entries in the browsing context's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

      This doesn't necessarily have to affect the user agent's user interface.

    2. Append a new entry at the end of the History object representing the new resource and its Document object and related state.

    3. Traverse the history to the new entry. If the navigation was initiated with replacement enabled, then the traversal must itself be initiated with replacement enabled.

  3. The navigation algorithm has now matured.

  4. Fragment identifier loop: Spin the event loop for a user-agent-defined amount of time, as desired by the user agent implementor. (This is intended to allow the user agent to optimise the user experience in the face of performance concerns.)

  5. If the Document object has no parser, or its parser has stopped parsing, or the user agent has reason to believe the user is no longer interested in scrolling to the fragment identifier, then abort these steps.

  6. Scroll to the fragment identifier given in the document's address. If this fails to find an indicated part of the document, then return to the fragment identifier loop step.

The task source for this task is the networking task source.

Page load processing model for HTML files

When an HTML document is to be loaded in a browsing context, the user agent must queue a task to create a Document object, mark it as being an HTML document, set its content type to "text/html", initialise the Document object, and finally create an HTML parser and associate it with the Document. Each task that the networking task source places on the task queue while the fetching algorithm runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

The input byte stream converts bytes into characters for use in the tokenizer. This process relies, in part, on character encoding information found in the real Content-Type metadata of the resource; the "sniffed type" is not used for this purpose.

When no more bytes are available, the user agent must queue a task for the parser to process the implied EOF character, which eventually causes a load event to be fired.

After creating the Document object, but before any script execution, certainly before the parser stops, the user agent must update the session history with the new page.

Application cache selection happens in the HTML parser.

The task source for the two tasks mentioned in this section must be the networking task source.

Page load processing model for XML files

When faced with displaying an XML file inline, user agents must follow the requirements defined in the XML and Namespaces in XML recommendations, RFC 7303, DOM, and other relevant specifications to create a Document object and a corresponding XML parser. [[!XML]] [[!XMLNS]] [[!RFC7303]] [[!DOM]]

At the time of writing, the XML specification community had not actually yet specified how XML and the DOM interact.

After the Document is created, the user agent must initialise the Document object.

The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification, are the ones that must be used when determining the character encoding according to the rules given in the above specifications. Once the character encoding is established, the document's character encoding must be set to that character encoding.

If the root element, as parsed according to the XML specifications cited above, is found to be an html element with an attribute manifest whose value is not the empty string, then, as soon as the element is inserted into the document, the user agent must resolve the value of that attribute relative to that element, and if that is successful, must apply the URL serialiser algorithm to the resulting parsed URL with the exclude fragment flag set to obtain manifest URL, and then run the application cache selection algorithm with manifest URL as the manifest URL, passing in the newly-created Document. Otherwise, if the attribute is absent, its value is the empty string, or resolving its value fails, then as soon as the root element is inserted into the document, the user agent must run the application cache selection algorithm with no manifest, and passing in the Document.

Because the processing of the manifest attribute happens only once the root element is parsed, any URLs referenced by processing instructions before the root element (such as <?xml-stylesheet?> PIs) will be fetched from the network and cannot be cached.

User agents may examine the namespace of the root Element node of this Document object to perform namespace-based dispatch to alternative processing tools, e.g. determining that the content is actually a syndication feed and passing it to a feed handler. If such processing is to take place, abort the steps in this section, and jump to the next step (labeled non-document content) in the navigate steps above.

Otherwise, then, with the newly created Document, the user agent must update the session history with the new page. User agents may do this before the complete document has been parsed (thus achieving incremental rendering), and must do this before any scripts are to be executed.

Error messages from the parse process (e.g. XML namespace well-formedness errors) may be reported inline by mutating the Document.

Page load processing model for text files

When a plain text document is to be loaded in a browsing context, the user agent must queue a task to create a Document object, mark it as being an HTML document, set its content type to "text/plain", initialise the Document object, create an HTML parser, associate it with the Document, act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, and switch the HTML parser's tokenizer to the PLAINTEXT state. Each task that the networking task source places on the task queue while the fetching algorithm runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

The rules for how to convert the bytes of the plain text document into actual characters, and the rules for actually rendering the text to the user, are defined in RFC 2046, RFC 3676, and subsequent versions thereof. [[!RFC2046]] [[!RFC3676]]

The document's character encoding must be set to the character encoding used to decode the document.

Upon creation of the Document object, the user agent must run the application cache selection algorithm with no manifest, and passing in the newly-created Document.

When no more bytes are available, the user agent must queue a task for the parser to process the implied EOF character, which eventually causes a load event to be fired.

After creating the Document object, but potentially before the page has finished parsing, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, e.g. linking to a style sheet or a binding, providing script, giving the document a title, etc.

In particular, if the user agent supports the Format=Flowed feature of RFC 3676 then the user agent would need to apply extra styling to cause the text to wrap correctly and to handle the quoting feature. This could be performed using, e.g., a binding or a CSS extension.

The task source for the two tasks mentioned in this section must be the networking task source.

Page load processing model for multipart/x-mixed-replace resources

When a resource with the type multipart/x-mixed-replace is to be loaded in a browsing context, the user agent must parse the resource using the rules for multipart types. [[!RFC2046]]

For each body part obtained from the resource, the user agent must run a new instance of the navigate algorithm, starting from the resource handling step, using the new body part as the resource being navigated, with replacement enabled if a previous body part from the same resource resulted in a Document object being created and initialised, and otherwise using the same setup as the navigate attempt that caused this section to be invoked in the first place.

For the purposes of algorithms processing these body parts as if they were complete stand-alone resources, the user agent must act as if there were no more bytes for those resources whenever the boundary following the body part is reached.

Thus, load events (and for that matter unload events) do fire for each body part loaded.

Page load processing model for media

When an image, video, or audio resource is to be loaded in a browsing context, the user agent should create a Document object, mark it as being an HTML document, set its content type to the sniffed MIME type of the resource (type in the navigate algorithm), initialise the Document object, append an html element to the Document, append a head element and a body element to the html element, append an element host element for the media, as described below, to the body element, and set the appropriate attribute of the element host element, as described below, to the address of the image, video, or audio resource.

The element host element to create for the media is the element given in the table below in the second cell of the row whose first cell describes the media. The appropriate attribute to set is the one given by the third cell in that same row.

Type of media Element for the media Appropriate attribute
Image img src
Video video src
Audio audio src

Then, the user agent must act as if it had stopped parsing.

Upon creation of the Document object, the user agent must run the application cache selection algorithm with no manifest, and passing in the newly-created Document.

After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, or attributes to the element host element, e.g. to link to a style sheet or a binding, to provide a script, to give the document a title, to make the media autoplay, etc.

Page load processing model for content that uses plugins

When a resource that requires an external resource to be rendered is to be loaded in a browsing context, the user agent should create a Document object, mark it as being an HTML document and mark it as being a plugin document, set its content type to the sniffed MIME type of the resource (type in the navigate algorithm), initialise the Document object, append an html element to the Document, append a head element and a body element to the html element, append an embed to the body element, and set the src attribute of the embed element to the address of the resource.

The term plugin document is used by the Content Security Policy specification as part of the mechanism that ensures iframes can't be used to evade plugin-types directives. [[CSP]]

Then, the user agent must act as if it had stopped parsing.

Upon creation of the Document object, the user agent must run the application cache selection algorithm with no manifest, and passing in the newly-created Document.

After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, or attributes to the embed element, e.g. to link to a style sheet or a binding, or to give the document a title.

If the Document's active sandboxing flag set has its sandboxed plugins browsing context flag set, the synthesized embed element will fail to render the content if the relevant plugin cannot be secured.

Page load processing model for inline content that doesn't have a DOM

When the user agent is to display a user agent page inline in a browsing context, the user agent should create a Document object, mark it as being an HTML document, set its content type to "text/html", initialise the Document object, and then either associate that Document with a custom rendering that is not rendered using the normal Document rendering rules, or mutate that Document until it represents the content the user agent wants to render.

Once the page has been set up, the user agent must act as if it had stopped parsing.

Upon creation of the Document object, the user agent must run the application cache selection algorithm with no manifest, passing in the newly-created Document.

After creating the Document object, but potentially before the page has been completely set up, the user agent must update the session history with the new page.

Navigating to a fragment identifier

When a user agent is supposed to navigate to a fragment identifier, then the user agent must run the following steps:

  1. Remove all the entries in the browsing context's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

    This doesn't necessarily have to affect the user agent's user interface.

  2. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context's document family.

  3. Append a new entry at the end of the History object representing the new resource and its Document object and related state. Its URL must be set to the address to which the user agent was navigating. The title must be left unset.

  4. Traverse the history to the new entry, with the non-blocking events flag set. This will scroll to the fragment identifier given in what is now the document's address.

If the scrolling fails because the relevant ID has not yet been parsed, then the original navigation algorithm will take care of the scrolling instead, as the last few steps of its update the session history with the new page algorithm.


When the user agent is required to scroll to the fragment identifier and the indicated part of the document, if any, is being rendered, the user agent must either change the scrolling position of the document using the following algorithm, or perform some other action such that the indicated part of the document is brought to the user's attention. If there is no indicated part, or if the indicated part is not being rendered, then the user agent must do nothing. The aforementioned algorithm is as follows:

  1. Let target be the indicated part of the document, as defined below.

  2. If target is the top of the document, then scroll to the beginning of the document for the Document, and abort these steps. [[!CSSOMVIEW]]

  3. Use the scroll an element into view algorithm to scroll target into view, with the align to top flag set. [[!CSSOMVIEW]]

  4. Run the focusing steps for that element, with the Document's viewport as the fallback target.

  5. Optionally, move the sequential focus navigation starting point to target.

The indicated part of the document is the one that the fragment identifier, if any, identifies. The semantics of the fragment identifier in terms of mapping it to a specific DOM Node is defined by the specification that defines the MIME type used by the Document (for example, the processing of fragment identifiers for XML MIME types is the responsibility of RFC7303). [[!RFC7303]]

For HTML documents (and HTML MIME types), the following processing model must be followed to determine what the indicated part of the document is.

  1. Apply the URL parser algorithm to the URL, and let fragid be the fragment component of the resulting parsed URL.

  2. If fragid is the empty string, then the indicated part of the document is the top of the document; stop the algorithm here.

  3. Let fragid bytes be the result of percent-decoding fragid.

  4. Let decoded fragid be the result of applying the UTF-8 decoder algorithm to fragid bytes. If the UTF-8 decoder emits a decoder error, abort the decoder and instead jump to the step labeled no decoded fragid.

  5. If there is an element in the DOM that has an ID exactly equal to decoded fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.

  6. No decoded fragid: If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.

  7. If fragid is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; stop the algorithm here.

  8. Otherwise, there is no indicated part of the document.

For the purposes of the interaction of HTML with Selectors' :target pseudo-class, the target element is the indicated part of the document, if that is an element; otherwise there is no target element. [[!SELECTORS]]

The task source for the task mentioned in this section must be the DOM manipulation task source.

History traversal

When a user agent is required to traverse the history to a specified entry, optionally with replacement enabled, and optionally with the non-blocking events flag set, the user agent must act as follows.

This algorithm is not just invoked when explicitly going back or forwards in the session history — it is also invoked in other situations, for example when navigating a browsing context, as part of updating the session history with the new page.

  1. If there is no longer a Document object for the entry in question, navigate the browsing context to the resource for that entry to perform an entry update of that entry, and abort these steps. The "navigate" algorithm reinvokes this "traverse" algorithm to complete the traversal, at which point there is a Document object and so this step gets skipped. The navigation must be done using the same source browsing context as was used the first time this entry was created. (This can never happen with replacement enabled.)

    If the resource was obtained usign a non-idempotent action, for example a POST form submission, or if the resource is no longer available, for example because the computer is now offline and the page wasn't cached, navigating to it again might not be possible. In this case, the navigation will result in a different page than previously; for example, it might be an error message explaining the problem or offering to resubmit the form.

  2. If the current entry's title was not set by the pushState() or replaceState() methods, then set its title to the value returned by the document.title IDL attribute.

  3. If appropriate, update the current entry in the browsing context's Document object's History object to reflect any state that the user agent wishes to persist. The entry is then said to be an entry with persisted user state.

  4. If the specified entry has a different Document object than the current entry, then run the following substeps:

    1. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context's document family.

    2. If the origin of the Document of the specified entry is not the same as the origin of the Document of the current entry, then run the following sub-sub-steps:

      1. The current browsing context name must be stored with all the entries in the history that are associated with Document objects with the same origin as the active document and that are contiguous with the current entry.

      2. If the browsing context is a top-level browsing context, but not an auxiliary browsing context, then the browsing context's browsing context name must be unset.

    3. Make the specified entry's Document object the active document of the browsing context.

    4. If the specified entry has a browsing context name stored with it, then run the following sub-sub-steps:

      1. Set the browsing context's browsing context name to the name stored with the specified entry.

      2. Clear any browsing context names stored with all entries in the history that are associated with Document objects with the same origin as the new active document and that are contiguous with the specified entry.

    5. If the specified entry's Document has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.

    6. If the current document readiness of the specified entry's Document is "complete", queue a task to run the following sub-sub-steps:

      1. If the Document's page showing flag is true, then abort this task (i.e. don't fire the event below).

      2. Set the Document's page showing flag to true.

      3. Run any session history document visibility change steps for Document that are defined by other applicable specifications.

        This is specifically intended for use by the Page Visibility specification. [[PAGEVIS]]

      4. Fire a trusted event with the name pageshow at the Window object of that Document, with target override set to the Document object, using the PageTransitionEvent interface, with the persisted attribute initialised to true. This event must not bubble, must not be cancelable, and has no default action.

  5. Set the document's address to the URL of the specified entry.

  6. If the specified entry has a URL whose fragment identifier differs from that of the current entry's when compared in a case-sensitive manner, and the two share the same Document object, then let hash changed be true, and let old URL be the URL of the current entry and new URL be the URL of the specified entry. Otherwise, let hash changed be false.

  7. If the traversal was initiated with replacement enabled, remove the entry immediately before the specified entry in the session history.

  8. If the specified entry is not an entry with persisted user state, but its URL has a fragment identifier, scroll to the fragment identifier.

  9. If the entry is an entry with persisted user state, the user agent may update aspects of the document and its rendering, for instance the scroll position or values of form fields, that it had previously recorded.

    This can even include updating the dir attribute of textarea elements or input elements whose type attribute is in either the Text state or the Search state, if the persisted state includes the directionality of user input in such controls.

  10. If the entry is a state object entry, let state be a structured clone of that state object. Otherwise, let state be null.

  11. Set history.state to state.

  12. Let state changed be true if the Document of the specified entry has a latest entry, and that entry is not the specified entry; otherwise let it be false.

  13. Let the latest entry of the Document of the specified entry be the specified entry.

  14. If the non-blocking events flag is not set, then run the following steps immediately. Otherwise, the non-blocking events flag is set; queue a task to run the following substeps instead.

    1. If state changed is true, fire a trusted event with the name popstate at the Window object of the Document, using the PopStateEvent interface, with the state attribute initialised to the value of state. This event must bubble but not be cancelable and has no default action.

    2. If hash changed is true, then fire a trusted event with the name hashchange at the browsing context's Window object, using the HashChangeEvent interface, with the oldURL attribute initialised to old URL and the newURL attribute initialised to new URL. This event must bubble but not be cancelable and has no default action.

  15. The current entry is now the specified entry.

The task source for the tasks mentioned above is the DOM manipulation task source.

The PopStateEvent interface

[Constructor(DOMString type, optional PopStateEventInit eventInitDict), Exposed=(Window,Worker)]
interface PopStateEvent : Event {
  readonly attribute any state;
};

dictionary PopStateEventInit : EventInit {
  any state;
};
event . state

Returns a copy of the information that was provided to pushState() or replaceState().

The state attribute must return the value it was initialised to. When the object is created, this attribute must be initialised to null. It represents the context information for the event, or null, if the state represented is the initial state of the Document.

The HashChangeEvent interface

[Constructor(DOMString type, optional HashChangeEventInit eventInitDict), Exposed=(Window,Worker)]
interface HashChangeEvent : Event {
  readonly attribute DOMString oldURL;
  readonly attribute DOMString newURL;
};

dictionary HashChangeEventInit : EventInit {
  DOMString oldURL;
  DOMString newURL;
};
event . oldURL

Returns the URL of the session history entry that was previously current.

event . newURL

Returns the URL of the session history entry that is now current.

The oldURL attribute must return the value it was initialised to. When the object is created, this attribute must be initialised to null. It represents context information for the event, specifically the URL of the session history entry that was traversed from.

The newURL attribute must return the value it was initialised to. When the object is created, this attribute must be initialised to null. It represents context information for the event, specifically the URL of the session history entry that was traversed to.

The PageTransitionEvent interface

[Constructor(DOMString type, optional PageTransitionEventInit eventInitDict), Exposed=(Window,Worker)]
interface PageTransitionEvent : Event {
  readonly attribute boolean persisted;
};

dictionary PageTransitionEventInit : EventInit {
  boolean persisted;
};
event . persisted

For the pageshow event, returns false if the page is newly being loaded (and the load event will fire). Otherwise, returns true.

For the pagehide event, returns false if the page is going away for the last time. Otherwise, returns true, meaning that (if nothing conspires to make the page unsalvageable) the page might be reused if the user navigates back to this page.

Things that can cause the page to be unsalvageable include:

The persisted attribute must return the value it was initialised to. When the object is created, this attribute must be initialised to false. It represents the context information for the event.

Unloading documents

A Document has a salvageable state, which must initially be true, a fired unload flag, which must initially be false, and a page showing flag, which must initially be false. The page showing flag is used to ensure that scripts receive pageshow and pagehide events in a consistent manner (e.g. that they never receive two pagehide events in a row without an intervening pageshow, or vice versa).

Event loops have a termination nesting level counter, which must initially be zero.

When a user agent is to prompt to unload a document, it must run the following steps.

  1. Increase the event loop's termination nesting level by one.

  2. Increase the Document's ignore-opens-during-unload counter by one.

  3. Let event be a new trusted BeforeUnloadEvent event object with the name beforeunload, which does not bubble but is cancelable.

  4. Dispatch: Dispatch event at the Document's Window object.

  5. Decrease the event loop's termination nesting level by one.

  6. Release the storage mutex.

  7. If any event listeners were triggered by the earlier dispatch step, then set the Document's salvageable state to false.

  8. If the returnValue attribute of the event object is not the empty string, or if the event was canceled, then the user agent should ask the user to confirm that they wish to unload the document.

    The prompt shown by the user agent may include the string of the returnValue attribute, or some leading subset thereof. (A user agent may want to truncate the string to 1024 characters for display, for instance.)

    The user agent must pause while waiting for the user's response.

    If the user did not confirm the page navigation, then the user agent refused to allow the document to be unloaded.

  9. If this algorithm was invoked by another instance of the "prompt to unload a document" algorithm (i.e. through the steps below that invoke this algorithm for all descendant browsing contexts), then jump to the step labeled end.

  10. Let descendants be the list of the descendant browsing contexts of the Document.

  11. If descendants is not an empty list, then for each browsing context b in descendants run the following substeps:

    1. Prompt to unload the active document of the browsing context b. If the user refused to allow the document to be unloaded, then the user implicitly also refused to allow this document to be unloaded; jump to the step labeled end.

    2. If the salvageable state of the active document of the browsing context b is false, then set the salvageable state of this document to false also.

  12. End: Decrease the Document's ignore-opens-during-unload counter by one.

When a user agent is to unload a document, it must run the following steps. These steps are passed an argument, recycle, which is either true or false, indicating whether the Document object is going to be re-used. (This is set by the document.open() method.)

  1. Increase the event loop's termination nesting level by one.

  2. Increase the Document's ignore-opens-during-unload counter by one.

  3. If the Document's page showing flag is false, then jump to the step labeled unload event below (i.e. skip firing the pagehide event and don't rerun the unloading document visibility change steps).

  4. Set the Document's page showing flag to false.

  5. Fire a trusted event with the name pagehide at the Window object of the Document, with target override set to the Document object, using the PageTransitionEvent interface, with the persisted attribute initialised to true if the Document object's salvageable state is true, and false otherwise. This event must not bubble, must not be cancelable, and has no default action.

  6. Run any unloading document visibility change steps for Document that are defined by other applicable specifications.

    This is specifically intended for use by the Page Visibility specification. [[PAGEVIS]]

  7. Unload event: If the Document's fired unload flag is false, fire a simple event named unload at the Document's Window object, with target override set to the Document object.

  8. Decrease the event loop's termination nesting level by one.

  9. Release the storage mutex.

  10. If any event listeners were triggered by the earlier unload event step, then set the Document object's salvageable state to false and set the Document's fired unload flag to true.

  11. Run any unloading document cleanup steps for Document that are defined by this specification and other applicable specifications.

  12. If this algorithm was invoked by another instance of the "unload a document" algorithm (i.e. by the steps below that invoke this algorithm for all descendant browsing contexts), then jump to the step labeled end.

  13. Let descendants be the list of the descendant browsing contexts of the Document.

  14. If descendants is not an empty list, then for each browsing context b in descendants run the following substeps:

    1. Unload the active document of the browsing context b with the recycle parameter set to false.

    2. If the salvageable state of the active document of the browsing context b is false, then set the salvageable state of this document to false also.

  15. If both the Document's salvageable state and recycle are false, then the Document's browsing context must discard the Document.

  16. End: Decrease the Document's ignore-opens-during-unload counter by one.

This specification defines the following unloading document cleanup steps. Other specifications can define more.

  1. Make disappear any WebSocket objects that were created by the WebSocket() constructor from the Document's Window object.

    If this affected any WebSocket objects, then set Document's salvageable state to false.

  2. If the Document's salvageable state is false, forcibly close any EventSource objects that whose constructor was invoked from the Document's Window object.

  3. If the Document's salvageable state is false, empty the Document's Window's list of active timers.

The BeforeUnloadEvent interface

interface BeforeUnloadEvent : Event {
  attribute DOMString returnValue;
};
event . returnValue [ = value ]

Returns the current return value of the event (the message to show the user).

Can be set, to update the message.

There are no BeforeUnloadEvent-specific initialisation methods.

The returnValue attribute represents the message to show the user. When the event is created, the attribute must be set to the empty string. On getting, it must return the last value it was set to. On setting, the attribute must be set to the new value.

Aborting a document load

If a Document is aborted, the user agent must run the following steps:

  1. Abort the active documents of every child browsing context. If this results in any of those Document objects having their salvageable state set to false, then set this Document's salvageable state to false also.

  2. Cancel any instances of the fetch algorithm in the context of this Document, discarding any tasks queued for them, and discarding any further data received from the network for them. If this resulted in any instances of the fetch algorithm being canceled or any queued tasks or any network data getting discarded, then set the Document's salvageable state to false.

  3. If the Document has an active parser, then abort that parser and set the Document's salvageable state to false.

User agents may allow users to explicitly invoke the abort a document algorithm for a Document. If the user does so, then, if that Document is an active document, the user agent should queue a task to fire a simple event named abort at that Document's Window object before invoking the abort algorithm.