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.
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:
Let source be the value of the browsing context's active document's reload override buffer.
Let address be the browsing context's active document's address.
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.
Document
objectThe 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;
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).
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:
Document
that has no browsing context.Document
whose address does not
use a server-based naming authority.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]]
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.
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:
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.
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.
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.
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).
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:
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]]
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.
Strip and collapse whitespace in value.
Return value.
On setting, the steps corresponding to the first matching condition in the following list must be run:
svg
element in the SVG
namespace [[!SVG]]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]]
Act as if the textContent
IDL attribute of element was
set to the new value being assigned.
If the title
element is null and the head
element is null, then abort these steps.
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.
Act as if the textContent
IDL attribute of element was
set to the new value being assigned.
Do nothing.
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:
body
or frameset
element, then throw a
HierarchyRequestError
exception and abort these steps.replaceChild()
method had
been called with the new value and the incumbent body
element as its two arguments respectively, then abort these steps.HierarchyRequestError
exception
and abort these steps.images
Returns an HTMLCollection
of the img
elements in the Document
.
embeds
plugins
Return an HTMLCollection
of the embed
elements in the Document
.
links
Returns an HTMLCollection
of the a
and area
elements
in the Document
that have href
attributes.
forms
Return an HTMLCollection
of the form
elements in the 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.
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.
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:
Return the Document
's CSS ID overrides list, maintaining the order
in which the entries were originally added to the list.
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.
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]]
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:
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.
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.
Otherwise, if elements has only one element, return that element and abort these steps.
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:
applet
, exposed embed
, form
,
iframe
, img
, or exposed object
elements that
have a name
content attribute whose value is name, orapplet
or exposed object
elements that have an id
content attribute whose value is name, orimg
elements that have an id
content attribute
whose value is name, and that have a non-empty name
content attribute present also.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.
partial interface XMLDocument { boolean load(DOMString url); };
The load(url)
method
must run the following steps:
Let document be the XMLDocument
object on which the
method was invoked.
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.
If the origin of url is not the same as the
origin of document, throw a SecurityError
exception
and abort these steps.
Remove all child nodes of document, without firing any mutation events.
Set the current document readiness of document to "loading
".
Run the remainder of these steps in parallel, and return true from the method.
Let result be a Document
object.
Let success be false.
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.
If the fetch attempt was successful, and the resource's Content-Type metadata is an XML MIME type, then run these substeps:
Create a new XML parser associated with the result document.
Pass this parser the fetched document.
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.
Queue a task to run the following steps.
Set the current document readiness of document to
"complete
".
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.
Fire a simple event named load
at document.
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 frame
s 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.
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:
Let list be an empty list.
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:
Append that child browsing context to the list list.
Append the list of the descendant browsing contexts of the active document of that child browsing context to the list list.
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 Document
s 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.
top
Returns the WindowProxy
for the top-level browsing context.
parent
Returns the WindowProxy
for the parent browsing context.
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:
If d is not a Document
in a nested browsing
context, return null and abort these steps.
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.
Return the browsing context container for b.
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.
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.
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.
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:
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.
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.
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.
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.
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 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 task in which the algorithm is running is currently
processing an activation behaviour whose click
event
was trusted.
The task in which the algorithm is running is currently running the event listener for a trusted event whose type is in the following list:
The task in which the algorithm is running was queued by an algorithm that was allowed to show a popup, and the chain of such algorithms started within a user-agent defined timeframe.
For example, if a user clicked a button, it might be acceptable for a popup to result from that after 4 seconds, but it would likely not be acceptable for a popup to result from that after 4 hours.
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.
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.
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.
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.
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.
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.
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.
noreferrer
keywordA 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.
noreferrer
keyword doesn't
applyA 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.
The chosen browsing context is the current 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.
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
frames
self
These attributes all return window.
document
Returns the Document
associated with window.
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.
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:
location
attribute
postMessage()
method
window
attribute
frames
attribute
self
attribute
top
attribute
parent
attribute
opener
attribute
closed
attribute
close()
method
blur()
method
focus()
method
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 Document
s from different origins access the same Window
object's postMessage()
method, they will get distinct objects that
are not equal.
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.
name
[ = value ]Returns the name of the window.
Can be set, to change the name.
close
()Closes the window.
closed
Returns true if the window has been closed, false otherwise.
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:
Let entry settings be the entry settings object when the method was invoked.
Let url be the first argument.
Let target be the second argument.
Let features be the third argument.
Let replace be the fourth argument.
Let source browsing context be the responsible browsing context specified by entry settings.
If target is the empty string, let it be the string "_blank
" instead.
If the user has indicated a preference for which browsing context to navigate, follow these substeps:
Let target browsing context be the browsing context indicated by the user.
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.
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.
Interpret features as defined in the CSSOM View specification. [[!CSSOMVIEW]]
If url is the empty string, run the appropriate steps from the following list:
Jump to the step labeled end.
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
".
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.
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.
length
Returns the number of child browsing contexts.
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.
Window
objectReturns 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:
name
content attribute for all a
,
applet
, area
, embed
, form
,
frameset
, img
, and object
elements in the active
document that have a non-empty name
content attribute, andid
content attribute of any HTML element in the active document with a non-empty id
content attribute.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:
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.
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.
Otherwise, if objects has only one element, return that element and abort these steps.
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:
a
, applet
, area
, embed
,
form
, frameset
, img
, or object
elements that
have a name
content attribute whose value is name, orid
content attribute
whose value is name.A browsing context has a strong reference to each of its Document
s
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:
Set the Document
's salvageable state to false.
Run any unloading document cleanup steps for the Document
that
are defined by this specification and other applicable specifications.
Remove any tasks associated with the
Document
in any task source, without running those tasks.
Discard all the child browsing contexts of the Document
.
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
Document
s 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.
When the user agent is required to close a browsing context, it must run the following steps:
Let specified browsing context be the browsing context being closed.
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.
Unload the active document of the specified browsing context with the recycle parameter set to false.
Remove the specified browsing context from the user interface (e.g. close or hide its tab in a tabbed browser).
Discard the specified browsing context.
User agents should offer users the ability to arbitrarily close any top-level browsing context.
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; };
locationbar
. visible
Returns true if the location bar is visible; otherwise, returns false.
menubar
. visible
Returns true if the menu bar is visible; otherwise, returns false.
personalbar
. visible
Returns true if the personal bar is visible; otherwise, returns false.
scrollbars
. visible
Returns true if the scroll bars are visible; otherwise, returns false.
statusbar
. visible
Returns true if the status bar is visible; otherwise, returns false.
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).
BarProp
objectBarProp
objectBarProp
objectBarProp
objectBarProp
objectvisible
attribute may return false).BarProp
objectvisible
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.
WindowProxy
objectAs 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
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:
Internal values, with no serialisation, for which the only meaningful operation is testing for equality.
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.
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:
The origin and effective script origin of the URL are the URL origin defined in the WHATWG URL standard. [[!URL]]
Document
objectsDocument
's active sandboxing flag set has
its sandboxed origin browsing context flag setThe 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
.
Document
was served over the network and has an address that uses a URL
scheme with a server-based naming authorityThe 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
.
Document
was generated from a data:
URL found in another Document
or in a
scriptThe 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
.
Document
is the initial "about:blank
" documentThe origin and effective script origin of the
Document
are those it was assigned when its
browsing context was created.
Document
was created as part of the processing for javascript:
URLsThe 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
.
Document
is an iframe
srcdoc
documentThe 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.
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.
img
elementsimg
element's node document.Images do not have an effective script origin.
audio
and video
elementsMedia elements do not have an effective script origin.
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:
If the origin in question is not a scheme/host/port tuple, then return the
literal string "null
" and abort these steps.
Otherwise, let result be the scheme part of the origin tuple.
Append the string "://
" to result.
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]]
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.
Return result.
The ASCII serialisation of an origin is the string obtained by applying the following algorithm to the given origin:
If the origin in question is not a scheme/host/port tuple, then return the
literal string "null
" and abort these steps.
Otherwise, let result be the scheme part of the origin tuple.
Append the string "://
" to result.
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.
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.
Return result.
Two origins are said to be the same origin if the following algorithm returns true:
Let A be the first origin being compared, and B be the second origin being compared.
If A and B are both opaque identifiers, and their value is equal, then return true.
Otherwise, if either A or B or both are opaque identifiers, return false.
If A and B have scheme components that are not identical, return false.
If A and B have host components that are not identical, return false.
If A and B have port components that are not identical, return false.
If either A or B have additional data, but that data is not identical for both, return false.
Return true.
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 iframe
s.)
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:
If the Document
has no browsing context, throw a
SecurityError
exception and abort these steps.
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.
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.
If new value is not exactly equal to the current value of the document.domain
attribute, then run these substeps:
If the current value is an IPv4 or IPv6 address, throw a SecurityError
exception and abort these steps.
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.
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]]
Release the storage mutex.
Set the attribute's value to new value.
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).
If new value is not the empty string, then run these substeps:
Set the host part of the effective script origin tuple of the
Document
to new value.
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.
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:
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.)
This flag prevents content from creating new auxiliary browsing
contexts, e.g. using the target
attribute, the
window.open()
method, or the showModalDialog()
method.
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.
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.
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).
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
.
This flag blocks form submission.
This flag disables the Pointer Lock API. [[!POINTERLOCK]]
This flag blocks script execution.
This flag blocks features that trigger automatically, such as automatically playing a video or automatically focusing a form control.
This flag prevents URL schemes that use storage areas from being able to access the origin's data.
This flag prevents content from using the requestFullscreen()
method.
document.domain
browsing context flagThis 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:
Split input on spaces, to obtain tokens.
Let output be empty.
Add the following flags to output:
The sandboxed auxiliary navigation browsing context flag, unless tokens contains the allow-popups
keyword.
The sandboxed top-level navigation browsing context flag, unless tokens contains the allow-top-navigation
keyword.
The sandboxed origin browsing context flag, unless the tokens contains the allow-same-origin
keyword.
The allow-same-origin
keyword
is intended for two cases.
First, it can be used to allow content from the same site to be sandboxed to disable scripting, while still allowing access to the DOM of the sandboxed content.
Second, it can be used to embed content from a third-party site, sandboxed to prevent that site from opening pop-up windows, etc, without preventing the embedded page from communicating back to its originating site, using the database APIs to store data, etc.
The sandboxed forms browsing context flag, unless tokens contains the allow-forms
keyword.
The sandboxed pointer lock browsing context flag, unless tokens contains the allow-pointer-lock
keyword.
The sandboxed scripts browsing context flag, unless tokens contains the allow-scripts
keyword.
The sandboxed automatic features browsing context flag, unless tokens contains the allow-scripts
keyword (defined above).
This flag is relaxed by the same keyword as scripts, because when scripts are enabled these features are trivially possible anyway, and it would be unfortunate to force authors to use script to do them when sandboxed rather than allowing them to use the declarative features.
The sandboxed fullscreen browsing context flag, unless the allow fullscreen flag was passed to the parse a sandboxing directive flag.
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:
If the Document
's browsing context is a top-level browsing
context, then: the flags set on the browsing context's popup sandboxing
flag set.
If the Document
's browsing context is a nested browsing
context, then: the flags set on the browsing context's
iframe
sandboxing flag set.
If the Document
's browsing context is a nested browsing
context, then: the flags set on the browsing context's parent browsing
context's active document's active sandboxing flag set.
The flags set on the Document
's resource's forced sandboxing flag
set, if it has one.
The sequence of Document
s 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.
History
interfaceinterface 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); };
history
. length
Returns the number of entries in the joint session history.
history
. state
Returns the current state object.
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.
history
. back
()Goes back one step in the joint session history.
If there is no previous page, does nothing.
history
. forward
()Goes forward one step in the joint session history.
If there is no next page, does nothing.
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.
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:
Wait until this top-level browsing context's session history traversal queue is not empty.
Pull the first task from this top-level browsing context's session history traversal queue, and execute it.
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:
Let delta be the argument to the method.
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.
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.
Let specified browsing context be the browsing context of the specified entry.
If the specified browsing context's active document's unload a document algorithm is currently running, abort these steps.
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.
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.
If the specified browsing context's active document is not
the same Document
as the Document
of the specified
entry, then run these substeps:
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.
Unload the active document of the specified browsing context with the recycle parameter set to false.
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:
Let cloned data be a structured clone of the specified data. If this throws an exception, then rethrow that exception and abort these steps.
If the third argument is not null, run these substeps:
SecurityError
exception and abort these steps.SecurityError
exception and abort these steps.SecurityError
exception
and abort these steps. (This prevents sandboxed content from spoofing other pages on the same
origin.)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.
If the third argument is null, then let new URL be the URL of the current entry.
If the method invoked was the pushState()
method:
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.
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.
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.
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.
Update the current entry to be this newly added entry.
Otherwise, if the method invoked was the replaceState()
method:
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.
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).
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.
Set history.state
to a structured clone
of cloned data.
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>
Location
interfaceEach Document
object in a browsing context's session history is
associated with a unique instance of a Location
object.
location
[ = value ]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;
assign
(url)Navigates to the given page.
replace
(url)Removes the current page from the session history and navigates to the given page.
reload
()Reloads the current page.
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:
resize
event in response to the user resizing the browsing
contextRepaint the browsing context and abort these steps.
iframe
srcdoc
documentReprocess the iframe
attributes of the browsing context's browsing context
container.
Perform an overridden reload, with the browsing context being navigated as the responsible browsing context.
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:
If any of the following conditions are met, let mode be normal navigation; otherwise, let it be replace navigation:
Location
object's relevant Document
has
completely loaded, orclick
event was trusted, orclick
event is being handled.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.
Let output be an empty ordered list of strings.
Let current be the browsing context of the Document
with which the Location
object is associated.
Loop: If current has no parent browsing context, jump to the step labeled end.
Let current be current's parent browsing context.
Append the Unicode serialisation of current's active document's origin to output as a new value.
Return to the step labeled loop.
End: Let output be the values of the array, in the same order.
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:
href
setter, if the responsible browsing
context specified by the entry settings object is familiar with
the browsing context with which the Location
object is associated
replace()
method, if the responsible
browsing context specified by the entry settings object is familiar
with the browsing context with which the Location
object is
associated
Location
object or indirectly via
one of those properties (e.g. toString()
, which is defined via the stringifier
keyword), if the effective script origin specified by
the entry settings object is the same origin as the
Location
object's associated Document
's effective script
origin
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).
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 iframe
s has a history
object distinct from the iframe
s' 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.
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.
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.
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:
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Remove all space characters from input.
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.
If the length of input divides by 4 leaving a remainder of 1, throw an
InvalidCharacterError
exception and abort these steps.
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:
Let output be a string, initially empty.
Let buffer be a buffer that can have bits appended to it, initially empty.
While position does not point past the end of input, run these substeps:
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 |
---|---|
A | 0 |
B | 1 |
C | 2 |
D | 3 |
E | 4 |
F | 5 |
G | 6 |
H | 7 |
I | 8 |
J | 9 |
K | 10 |
L | 11 |
M | 12 |
N | 13 |
O | 14 |
P | 15 |
Q | 16 |
R | 17 |
S | 18 |
T | 19 |
U | 20 |
V | 21 |
W | 22 |
X | 23 |
Y | 24 |
Z | 25 |
a | 26 |
b | 27 |
c | 28 |
d | 29 |
e | 30 |
f | 31 |
g | 32 |
h | 33 |
i | 34 |
j | 35 |
k | 36 |
l | 37 |
m | 38 |
n | 39 |
o | 40 |
p | 41 |
q | 42 |
r | 43 |
s | 44 |
t | 45 |
u | 46 |
v | 47 |
w | 48 |
x | 49 |
y | 50 |
z | 51 |
0 | 52 |
1 | 53 |
2 | 54 |
3 | 55 |
4 | 56 |
5 | 57 |
6 | 58 |
7 | 59 |
8 | 60 |
9 | 61 |
+ | 62 |
/ | 63 |
Append to buffer the six bits corresponding to number, most significant bit first.
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.
Advance position by one character.
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
".
Return output.
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).
The open()
method comes in several variants
with different numbers of arguments.
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.
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:
If the Document
object is not flagged as an HTML
document, throw an InvalidStateError
exception and abort these steps.
If the Document
object is not an active document, then abort
these steps.
Let type be the value of the first argument.
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.
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.
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.
Release the storage mutex.
Set the Document
's salvageable state to false.
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.
Unload the Document
object, with the
recycle parameter set to true.
Unregister all event listeners registered on the Document
node and its
descendants.
Remove any tasks associated with the
Document
in any task source.
Remove all child nodes of the document, without firing any mutation events.
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.
Change the document's character encoding to UTF-8.
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.
Set the Document
's salvageable state back to true.
Change the document's address to the address of the responsible document specified by the entry settings object.
If the Document
's iframe load in progress flag is set, set the
Document
's mute iframe load flag.
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.
Set the current document readiness of the document to "loading
".
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.
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.
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.
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.
Document
.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.
Finally, set the insertion point to point at just before the end of the input stream (which at this point will be empty).
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.
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:
If the Document
object is not flagged as an HTML
document, throw an InvalidStateError
exception and abort these
steps.
If there is no script-created parser associated with the document, then abort these steps.
Insert an explicit "EOF" character at the end of the parser's input stream.
If there is a pending parsing-blocking script, then abort these steps.
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()
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:
If the method was invoked on an XML document, throw an
InvalidStateError
exception and abort these steps.
If the Document
object is not an active document, then abort
these steps.
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.
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.
Insert the string consisting of the concatenation of all the arguments to the method into the input stream just before the insertion point.
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.
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.
Finally, return from the method.
document.writeln()
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).
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;
setTimeout
( handler [, timeout [, arguments... ] ] )Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.
setTimeout
( code [, timeout ] )Schedules a timeout to compile and run code after timeout milliseconds.
clearTimeout
( handle )Cancels the timeout set with setTimeout()
identified by handle.
setInterval
( handler [, timeout [, arguments... ] ] )Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.
setInterval
( code [, timeout ] )Schedules a timeout to compile and run code every timeout milliseconds.
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:
Let method context proxy be method context if that
is a WorkerGlobalScope
object, or else the WindowProxy
that corresponds
to method context.
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.
If previous handle was not provided, add an entry to the list of active timers for handle.
Let task be a task that runs the following substeps:
If the entry for handle in the list of active timers has been cleared, then abort this task's substeps.
Run the appropriate set of steps from the following list:
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]]
Let script source be the first method argument.
Let script language be JavaScript.
Let settings object be method context's environment settings object.
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.
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.
Let timeout be the second method argument.
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.
If nesting level is greater than 5, and timeout is less than 4, then increase timeout to 4.
Increment nesting level by one.
Let task's timer nesting level be nesting level.
Return handle, and then continue running this algorithm in parallel.
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).
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);
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.
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
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.
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.
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:
If the event loop's termination nesting level is non-zero, optionally abort these steps.
Release the storage mutex.
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.)
If the method was invoked with no arguments, then let message be the empty string; otherwise, let message be the method's first argument.
Show the given message to the user.
Optionally, pause while waiting for the user to acknowledge the message.
The confirm(message)
method,
when invoked, must run the following steps:
If the event loop's termination nesting level is non-zero, optionally abort these steps, returning false.
Release the storage mutex.
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.)
Show the given message to the user, and ask the user to respond with a positive or negative response.
Pause until the user responds either positively or negatively.
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:
If the event loop's termination nesting level is non-zero, optionally abort these steps, returning null.
Release the storage mutex.
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.)
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.
Pause while waiting for the user's response.
If the user aborts, then return null; otherwise, return the string that the user responded with.
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:
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.
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.
The user agent must release the storage mutex.
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.
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.
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:
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.
If the event loop's termination nesting level is non-zero, optionally abort these steps, returning the empty string.
Release the storage mutex.
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.
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.
Let incumbent origin be the effective script origin
specified by the incumbent settings object at the time the showModalDialog()
method was called.
Let the list of background browsing contexts be a list of all the browsing contexts that:
Window
object on which the showModalDialog()
method was called, and that...as well as any browsing contexts that are nested inside any of the browsing contexts matching those conditions.
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.
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 Document
s' Window
objects all implement the WindowModal
interface.
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.
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.
Let the dialog arguments' origin be incumbent origin.
Let the return value of the new browsing context be the undefined value.
Let the return value origin be incumbent origin.
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.
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.
Reenable the user interface for all the browsing contexts in the list of background browsing contexts.
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.
Return return value.
The Window
objects of Document
s 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; };
dialogArguments
Returns the argument argument that was passed to the showModalDialog()
method.
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.
Navigator
objectThe 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.
[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.
navigator
. appCodeName
Returns the string "Mozilla
".
navigator
. appName
Returns the name of the browser.
navigator
. appVersion
Returns the version of the browser.
navigator
. platform
Returns the name of the platform.
navigator
. product
Returns the string "Gecko
".
navigator
. taintEnabled
()Returns false.
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.
[NoInterfaceObject, Exposed=(Window,Worker)] interface NavigatorLanguage { readonly attribute DOMString? language; readonly attribute DOMString[] languages; };
navigator
. language
Returns a language tag representing the user's preferred language.
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:
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.
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]]
navigator
. registerProtocolHandler
(scheme, url, title)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.)
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.
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:
application/x-www-form-urlencoded
application/xhtml+xml
application/xml
image/gif
image/jpeg
image/png
image/svg+xml
multipart/x-mixed-replace
text/cache-manifest
text/css
text/html
text/ping
text/plain
text/xml
application/rss+xml
and application/atom+xml
This list can be changed. If there are MIME types that should be added, please send feedback.
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).
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.
navigator
. isProtocolHandlerRegistered
(scheme, url)navigator
. isContentHandlerRegistered
(mimeType, url)Returns one of the following strings describing the state of the handler given by the arguments:
new
registered
declined
navigator
. unregisterProtocolHandler
(scheme, url)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.
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.
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
registered
declined
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:
If the string does not contain the substring "%s
", abort these
steps. There's no matching handler.
Resolve the string relative to the API base URL specified by the entry settings object.
If this fails, then throw a SyntaxError
exception, aborting the
method.
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.
Return the resulting absolute URL as the result of preprocessing the argument.
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:
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.
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:
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:
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.
[NoInterfaceObject] interface NavigatorStorageUtils { readonly attribute boolean cookieEnabled; void yieldForStorageUpdates(); };
navigator
. cookieEnabled
Returns false if setting a cookie will be ignored, and true otherwise.
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.
[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; };
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.
navigator
. plugins
. length
Returns the number of plugins, represented by Plugin
objects, that the user agent reports.
navigator
. plugins
. item
(index)navigator
. plugins
[index]Returns the specified Plugin
object.
navigator
. plugins
. item
(name)navigator
. plugins
[name]Returns the Plugin
object for the plugin with the given name.
navigator
. mimeTypes
. length
Returns the number of MIME types, represented by MimeType
objects, supported by the plugins that the user agent reports.
navigator
. mimeTypes
. item
(index)navigator
. mimeTypes
[index]Returns the specified MimeType
object.
navigator
. mimeTypes
. item
(name)navigator
. mimeTypes
[name]Returns the MimeType
object for the given MIME type.
name
Returns the plugin's name.
description
Returns the plugin's description.
filename
Returns the plugin library's filename, if applicable on the current platform.
length
Returns the number of MIME types, represented by MimeType
objects, supported by the plugin.
item
(index)Returns the specified MimeType
object.
item
(name)Returns the MimeType
object for the given MIME type.
type
Returns the MIME type.
description
Returns the MIME type's description.
suffixes
Returns the MIME type's typical file extensions, in a comma-separated list.
enabledPlugin
Returns the Plugin
object that implements this MIME type.
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 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 , 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- plugins represented by the object, if any.
The length
attribute must return the
number of non- plugins
represented by the object.
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:
Let list be the Plugin
objects
representing the non- plugins represented by the PluginArray
object.
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.
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- plugins represented by the corresponding PluginArray
object, if
any.
The length
attribute must return the
number of MIME types explicitly supported by non- plugins represented by the
corresponding PluginArray
object, if any.
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:
Let list be the MimeType
objects representing the MIME types explicitly supported by non- plugins represented by the corresponding
PluginArray
object, if any.
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.
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.
The length
attribute must return the number
of reported MIME types.
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:
Let list be the MimeType
objects representing the
reported MIME types.
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.
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.
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.
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.
External
interfaceThe 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.
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.
external
. IsSearchProviderInstalled
( url )Returns a value based on comparing url to the URLs of the results pages of the installed search engines.
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:
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.
Resolve the value of the method's first argument relative to the API base URL specified by the entry settings object.
If this fails, abort these steps.
Process the resulting absolute URL as the URL to an OpenSearch description document. [[!OPENSEARCH]]
The IsSearchProviderInstalled()
method, when invoked, must run the following steps:
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.
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.
Let host1 be the host component of the origin specified by the entry settings object.
Resolve the scriptURL argument relative to the API base URL specified by the entry settings object.
If this fails, return 0 and abort these steps.
Let host2 be the host component of the resulting parsed URL.
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.
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]]
If search engines is empty, return 0 and abort these steps.
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.
Return 1.
[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.
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).
width
Returns the intrinsic width of the image, in CSS pixels.
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:
img
element
If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError
exception and abort these steps.
If the img
element is not completely
available, then return a promise rejected with an InvalidStateError
exception and abort these
steps.
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.
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.
Create a new ImageBitmap
object.
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.
Return a new Promise
, but continue running these steps
in parallel.
Resolve the Promise
with the new
ImageBitmap
object as the value.
video
element
If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError
exception and abort these steps.
If the video
element's networkState
attribute is NETWORK_EMPTY
, then return a promise rejected with an
InvalidStateError
exception and abort these steps.
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.
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.
Create a new ImageBitmap
object.
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.
Return a new Promise
, but continue running these steps
in parallel.
Resolve the Promise
with the new
ImageBitmap
object as the value.
canvas
element
If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError
exception and abort these steps.
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.
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.
Create a new ImageBitmap
object.
Let the ImageBitmap
object's bitmap data be a copy of the
canvas
element's bitmap data, cropped to the source
rectangle.
Return a new Promise
, but continue running these steps in parallel.
Resolve the Promise
with the new
ImageBitmap
object as the value.
Blob
object
If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError
exception and abort these steps.
If the Blob
object has been disabled through the close()
method, then return a promise rejected with an InvalidStateError
exception and abort these steps.
Return a new Promise
, but continue running these steps in parallel.
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.
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.
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.
Create a new ImageBitmap
object.
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.
Resolve the Promise
with the new
ImageBitmap
object as the value.
ImageData
object
If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError
exception and abort these steps.
If the image object's data
attribute has been neutered, return a promise rejected with an
InvalidStateError
exception and abort these steps.
Create a new ImageBitmap
object.
Let the ImageBitmap
object's bitmap data be the image data given by the
ImageData
object, cropped to the source rectangle.
Return a new Promise
, but continue running these steps in parallel.
Resolve the Promise
with the new
ImageBitmap
object as the value.
CanvasRenderingContext2D
object
If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError
exception and abort these steps.
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.
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.
Create a new ImageBitmap
object.
Let the ImageBitmap
object's bitmap data be a copy of the
CanvasRenderingContext2D
object's scratch bitmap, cropped to
the source rectangle.
Return a new Promise
, but continue running these steps
in parallel.
Resolve the Promise
with the new
ImageBitmap
object as the value.
ImageBitmap
object
If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError
exception and abort these steps.
Create a new ImageBitmap
object.
Let the ImageBitmap
object's bitmap data be a copy of the image argument's bitmap data, cropped to the source
rectangle.
Return a new Promise
, but continue running these steps
in parallel.
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:
Let input be the image data being cropped.
If the sx, sy, sw, and sh arguments are omitted, return input.
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.
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.
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);
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:
Let document be the
Window
object's Document
object.
Increment document's animation frame callback identifier by one.
Append the method's argument to document's list of animation frame callbacks, associated with document's animation frame callback identifier's current value.
Return document's animation frame callback identifier's current value.
When the cancelAnimationFrame()
method is called,
the user agent must run the following steps:
Let document be the
Window
object's Document
object.
Find the entry in document's list of animation frame callbacks that is associated with the value given by the method's argument.
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:
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.
Set doc's list of animation frame callbacks to the empty list.
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]]
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:
Release the storage mutex.
If the source browsing context is not allowed to navigate the browsing context being navigated, then abort these steps.
If these steps are aborted here, the user agent may instead offer to open the new resource in a new top-level browsing context or in the top-level browsing context of the source browsing context, at the user's option, in which case the user agent must navigate that designated top-level browsing context to the new resource as if the user had requested it independently.
Doing so, however, can be dangerous, as it means that the user is overriding the author's explicit request to sandbox the content.
If the navigate algorithm was invoked with exceptions enabled, and it
is aborted on this step, then in addition to aborting this algorithm, the user agent must also
throw a SecurityError
exception.
If the source browsing context is the same as the browsing context being navigated, and this browsing context has its seamless browsing context flag set, and the browsing context being navigated was not chosen using an explicit self-navigation override, then find the nearest ancestor browsing context that does not have its seamless browsing context flag set, and continue these steps as if that browsing context was the one that was going to be navigated instead.
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.
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.
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.
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.
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.)
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.
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.
If gone async is false, abort the active document of the browsing context.
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.
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.
This is the step that attempts to obtain the resource, if necessary. Jump to the first appropriate substep:
object
element's new child browsing context)Skip this step. The data is already available.
javascript
Queue a task to run these
"javascript:
URL" steps, associated with the active document
of the browsing context being navigated:
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.
Apply the URL parser to the URL being navigated.
Let parsed URL be the result of the URL parser.
Let script source be the empty string.
Append parsed URL's scheme data component to script source.
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.
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.
Replace script source with the result of applying the percent decode algorithm to script source.
Replace script source with the result of applying the UTF-8 decode algorithm to script source.
Let address be the address of the active document of the browsing context being navigated.
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.)
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.
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.
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.
If gone async is false, return to whatever algorithm invoked the navigation steps and continue running these steps asynchronously.
Let gone async be true.
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.
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.
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.
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:
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.
Let type be the sniffed type of the resource.
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
"application/xml
"text/xml
"image/svg+xml
"application/xhtml+xml
"+xml
" that is not an explicitly
supported XML typetext/plain
"multipart/x-mixed-replace
"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:
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
.
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.
Implement the sandboxing for the Document
.
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.
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:
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.)
Replace the Document
of the entry being updated, and any other entries
that referenced the same document as that entry, with the new Document
.
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.)
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.
Append a new entry at the end of the History
object representing the new
resource and its Document
object and related state.
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.
The navigation algorithm has now matured.
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.)
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.
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.
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.
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
.
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.
multipart/x-mixed-replace
resourcesWhen 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.
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.
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 iframe
s 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
.
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.
When a user agent is supposed to navigate to a fragment identifier, then the user agent must run the following steps:
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.
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.
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.
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:
Let target be the indicated part of the document, as defined below.
If target is the top of the document, then scroll to the
beginning of the document for the Document
, and abort these steps. [[!CSSOMVIEW]]
Use the scroll an element into view algorithm to scroll target into view, with the align to top flag set. [[!CSSOMVIEW]]
Run the focusing steps for that element, with the Document
's
viewport as the fallback target.
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.
Apply the URL parser algorithm to the URL, and let fragid be the fragment component of the resulting parsed URL.
If fragid is the empty string, then the indicated part of the document is the top of the document; stop the algorithm here.
Let fragid bytes be the result of percent-decoding fragid.
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.
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.
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.
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.
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.
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.
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.
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.
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.
If the specified entry has a different Document
object
than the current entry, then run the following substeps:
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.
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:
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.
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.
Make the specified entry's
Document
object the active document of the browsing
context.
If the specified entry has a browsing context name stored with it, then run the following sub-sub-steps:
Set the browsing context's browsing context name to the name stored with the specified entry.
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.
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.
If the current document readiness of the specified entry's
Document
is "complete
", queue a task to run
the following sub-sub-steps:
If the Document
's page showing flag is true, then abort this
task (i.e. don't fire the event below).
Set the Document
's page showing flag to true.
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]]
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.
Set the document's address to the URL of the specified entry.
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.
If the traversal was initiated with replacement enabled, remove the entry immediately before the specified entry in the session history.
If the specified entry is not an entry with persisted user state, but its URL has a fragment identifier, scroll to the fragment identifier.
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.
If the entry is a state object entry, let state be a structured clone of that state object. Otherwise, let state be null.
Set history.state
to state.
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.
Let the latest entry of the Document
of the specified entry be the specified entry.
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.
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.
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.
The current entry is now the specified entry.
The task source for the tasks mentioned above is the DOM manipulation task source.
PopStateEvent
interface[Constructor(DOMString type, optional PopStateEventInit eventInitDict), Exposed=(Window,Worker)] interface PopStateEvent : Event { readonly attribute any state; }; dictionary PopStateEventInit : EventInit { any state; };
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
.
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; };
oldURL
Returns the URL of the session history entry that was previously current.
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.
PageTransitionEvent
interface[Constructor(DOMString type, optional PageTransitionEventInit eventInitDict), Exposed=(Window,Worker)] interface PageTransitionEvent : Event { readonly attribute boolean persisted; }; dictionary PageTransitionEventInit : EventInit { boolean persisted; };
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:
document.open()
beforeunload
events
unload
events
iframe
s that are not salvageable
WebSocket
objects
Document
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.
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.
Increase the event loop's termination nesting level by one.
Increase the Document
's ignore-opens-during-unload counter by
one.
Let event be a new trusted
BeforeUnloadEvent
event object with the name beforeunload
, which does not bubble but is cancelable.
Decrease the event loop's termination nesting level by one.
Release the storage mutex.
If any event listeners were triggered by the earlier dispatch step, then set the
Document
's salvageable state to
false.
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.
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.
Let descendants be the list of the descendant browsing
contexts of the Document
.
If descendants is not an empty list, then for each browsing context b in descendants run the following substeps:
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.
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.
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.)
Increase the event loop's termination nesting level by one.
Increase the Document
's ignore-opens-during-unload counter by
one.
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).
Set the Document
's page showing flag to false.
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.
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]]
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.
Decrease the event loop's termination nesting level by one.
Release the storage mutex.
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.
Run any unloading document cleanup steps for Document
that are
defined by this specification and other applicable specifications.
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.
Let descendants be the list of the descendant browsing
contexts of the Document
.
If descendants is not an empty list, then for each browsing context b in descendants run the following substeps:
Unload the active document of the browsing context b with the recycle parameter set to false.
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.
If both the Document
's salvageable state and recycle are
false, then the Document
's browsing context must discard the Document
.
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.
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.
If the Document
's salvageable
state is false, forcibly close any
EventSource
objects that whose constructor was invoked from the
Document
's Window
object.
If the Document
's salvageable
state is false, empty the Document
's Window
's list of active
timers.
BeforeUnloadEvent
interfaceinterface BeforeUnloadEvent : Event { attribute DOMString returnValue; };
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.
If a Document
is aborted, the user agent must
run the following steps:
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.
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.
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.