6. Loading Web pages
This section describes features that apply most directly to Web browsers. Having said that, except where specified otherwise, the requirements defined in this section do apply to all user agents, whether they are Web browsers or not.
6.1. Browsing contexts
A browsing context is an environment in which Document
objects are presented to the user.
A tab or window in a Web browser typically contains a browsing context, as
does an iframe
or frame
s in a frameset
.
A browsing context has a corresponding WindowProxy
object.
A browsing context has a session history, which lists the Document
objects that the 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.
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 creator origin, creator URL, and creator base URL are the origin, URL, and base URL, respectively, of
the Document
that was the active document of that creator browsing context at
the time A was created.
To create a new browsing context:
-
Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:
-
For the global object, create a new
Window
object window. -
For the global this value, create a new
WindowProxy
object windowProxy, whose [[Window
]] internal slot value is window.The internal slot value is updated when navigations occur.
-
Let realm execution context be the created JavaScript execution context.
-
-
Set the new browsing context’s associated
WindowProxy
to windowProxy. -
Let document be a new
Document
, whose URL 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. -
Set the origin of document:
-
If the new browsing context has a creator browsing context, then the origin of document is the creator origin.
-
Otherwise, the origin of document is a unique opaque origin assigned when the new browsing context is created.
-
-
If the new browsing context has a creator browsing context, then set document’s referrer to the creator URL.
-
Ensure that document has a single child
html
node, which itself has two empty child nodes: ahead
element, and abody
element. -
Implement the sandboxing for document.
-
Add document to the new browsing context’s session history.
-
Set window’s associated
Document
to document. -
Set up a browsing context environment settings object with realm execution context.
6.1.1. Nested browsing contexts
Certain elements (for example, iframe
elements) can instantiate further browsing contexts. These are called nested browsing contexts. If a browsing context P has a Document
D with an element E that nests
another browsing context C inside it, then C is said to be nested through D, and E is said to be the browsing context container of C.
If the browsing context container element E is in the Document
D, then P is
said to be the parent browsing context of C and C is said to be a child browsing context of P.
Otherwise, the nested browsing context C has no parent
browsing context.
A browsing context A is said to be an ancestor of a browsing context B if there exists a browsing context A that is a child browsing context of A and that is itself an ancestor of B, or if the browsing context A is the parent browsing context of B.
A browsing context that is not a nested browsing context has no parent browsing context, and is the top-level browsing context of all the browsing contexts for which it is an ancestor browsing context.
The transitive closure of parent browsing contexts for a nested browsing context gives the list of ancestor browsing contexts.
The list of the descendant browsing contexts of a Document
d is the (ordered) list returned by the following algorithm:
- 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 has a browsing context and it is the active document of
that 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 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.
6.1.1.1. Navigating nested browsing contexts in the DOM
- window .
top
-
Returns the
WindowProxy
for the top-level browsing context. - window .
parent
-
Returns the
WindowProxy
for the parent browsing context. - window .
frameElement
-
Returns the
Element
for the browsing context container.Returns null if there isn’t one, and 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
that has 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 getting, must
run the following algorithm:
-
Let d be the
Window
object’s associatedDocument
. -
Let context be d’s browsing context.
-
If context is not a nested browsing context, return null and abort these steps.
-
Let container be context’s browsing context container.
-
If container’s node document’s origin is not same origin-domain with the entry settings object’s origin, then return null and abort these steps.
-
Return container.
6.1.2. Auxiliary browsing contexts
It is possible to create new browsing contexts that are related to a top-level browsing context without being nested through an element. Such browsing contexts are called auxiliary browsing contexts. Auxiliary browsing contexts are always top-level browsing contexts.
An auxiliary browsing context has an opener browsing context, which is the browsing context from which the auxiliary browsing context was created.
6.1.2.1. Navigating auxiliary browsing contexts in the DOM
The opener
IDL attribute on the Window
object, on getting, must return the WindowProxy
object of the browsing
context from which the current browsing context was created (its opener
browsing context), if there is one, if it is still available, and if the current browsing context has not disowned its opener;
otherwise, it must return null. On setting, if the new value is null then the current browsing context must disown its opener; if
the new value is anything else then the user agent must
call the [[DefineOwnProperty]] internal method of the Window
object, passing the
property name "opener
" as the property key, and the Property Descriptor {
[[Value]]: value, [[Writable]]: true, [[Enumerable]]: true,
[[Configurable]]: true } as the property descriptor,
where value is the new value.
6.1.3. Security
A browsing context A is familiar with a second browsing context B if one of the following conditions is true:
- Either the origin of the active document of A is the same as the origin of the active document of B, or
- The browsing context A is a nested browsing context with a top-level browsing context, and its top-level browsing context is B, or
- The browsing context B is an auxiliary browsing context and A is familiar with B’s opener browsing context, or
- The browsing context B is not a top-level browsing context, but there exists an ancestor browsing context of B whose active document has the same origin as the active document of A (possibly in fact being A itself).
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 active 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.
6.1.4. Groupings of browsing contexts
Each browsing context is defined as having a list of one or more directly reachable browsing contexts. These are:
-
The browsing context itself.
-
All the browsing context’s child browsing contexts.
-
All the browsing contexts that have the browsing context as their opener browsing context.
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 origin that, through appropriate manipulation of the document.domain
attribute, could be made to be same origin-domain with
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).
6.1.5. Browsing context names
Browsing contexts can have a browsing context name. By default, a browsing context has no name (its name is not set).
A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)
A valid browsing context name or keyword is any string that is either a valid
browsing context name or that is an ASCII case-insensitive match for one of: _blank
, _self
, _parent
, or _top
.
These values have different meanings based on whether the page is sandboxed or not, as summarized
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, "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...
| |
---|---|---|---|
sandbox=""
| sandbox="allow-top-navigation"
| ||
none specified, for links and form submissions | current | current | current |
empty string | current | current | current |
_blank
| new | maybe new | maybe new |
_self
| current | current | current |
_parent if there isn’t a parent
| current | current | current |
_parent if parent is also top
| parent/top | none | parent/top |
_parent if there is one and it’s not top
| parent | none | none |
_top if top is current
| current | current | current |
_top if top is not current
| top | none | top |
name that doesn’t exist | new | maybe new | maybe new |
name that exists and is a descendant | specified descendant | specified descendant | specified descendant |
name that exists and is current | current | current | current |
name that exists and is an ancestor that is top | specified ancestor | none | specified ancestor/top |
name that exists and is an ancestor that is not top | specified ancestor | none | none |
other name that exists with common top | specified | none | none |
name that exists with different top, if familiar and one permitted sandboxed navigator | specified | specified | specified |
name that exists with different top, if familiar but not one permitted sandboxed navigator | specified | none | none |
name that exists with different top, not familiar | 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 behavior 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:
change
click
dblclick
mouseup
reset
submit
-
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
_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. -
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:
- If the algorithm is not allowed to show a popup and the user agent has been configured to not show popups (i.e., the user agent has a "popup blocker" enabled)
-
There is no chosen browsing context. The user agent may inform the user that a popup has been blocked.
- If the current browsing context’s active document’s active sandboxing flag set has the sandboxed auxiliary navigation browsing context flag set.
-
Typically, there is no chosen browsing context.
The user agent may offer to create a new top-level browsing context or reuse an existing top-level browsing context. If the user picks one of those options, then the designated browsing context must be the chosen one (the browsing context’s name isn’t set to the given browsing context name). The default behavior (if the user agent doesn’t offer the option to the user, or if the user declines to allow a browsing context to be used) must be that there must not be a chosen browsing context.
If this case occurs, it means that an author has explicitly sandboxed the document that is trying to open a link.
- If the user agent has been configured such that in this instance it will
create a new browsing context, and the browsing context is being requested as part of following a hyperlink whose link
types include the
noreferrer
keyword -
A new top-level browsing context must be created. If the given browsing
context name is not
_blank
, then the new top-level browsing context’s name must be the given browsing context name (otherwise, it has no name). The chosen browsing context must be this new browsing context. The creation of such a browsing context is a new start for session storage.If it is immediately navigated, then the navigation will be done with replacement enabled.
- If the user agent has been configured such that in this instance it will create a new
browsing context, and the
noreferrer
keyword doesn’t apply -
A new auxiliary browsing context must be created, with the opener
browsing context being the current one. If the given browsing context name is not
_blank
, then the new auxiliary browsing context’s name must be the given browsing context name (otherwise, it has no name). The chosen browsing context must be this new browsing context.If it is immediately navigated, then the navigation will be done with replacement enabled.
- If the user agent has been configured such that in this instance it will reuse the current browsing context
- The chosen browsing context is the current browsing context.
- If the user agent has been configured such that in this instance it will not find a browsing context
- There must not be a chosen browsing context.
User agent implementors are encouraged to provide a way for users to configure the user agent to always reuse the current browsing context.
If the current browsing context’s active document’s active sandboxing flag set has both the sandboxed navigation browsing context flag and sandbox propagates to auxiliary browsing contexts flag set, and the chosen browsing context picked above, if any, is a new browsing context, 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.
6.1.6. Script settings for browsing contexts
When the user agent is required to set up a browsing context environment settings object, given a JavaScript execution context execution context, it must run the following steps:
-
Let realm be the value of execution context’s Realm component.
-
Let window be realm’s global object.
-
Let url be a copy of the URL of the
Document
with which window is associated. -
Let settings object be a new environment settings object whose algorithms are defined as follows:
-
Return execution context.
-
Return the browsing context with which window is associated.
-
Return the event loop that is associated with the unit of related similar-origin browsing contexts to which window’s browsing context belongs.
-
Return the
Document
with which window is currently associated. -
Return the current character encoding of the
Document
with which window is currently associated. -
The API base URL
-
Return the current base URL of the
Document
with which window is currently associated. -
The origin
-
Return the origin of the
Document
with which window is currently associated. -
The creation URL
-
Return url.
-
The HTTPS state
-
Return the HTTPS state of the
Document
with which window is currently associated.
-
Set realm’s [[HostDefined]] field to settings object.
-
Return settings object.
6.2. Security infrastructure for Window
, WindowProxy
, and Location
objects
Although typically objects cannot be accessed across origins, the web platform would not be true to itself if it did not have some legacy exceptions to that rule that the web depends upon.
6.2.1. Integration with IDL
When perform a security check is invoked, with a platformObject, realm, identifier, and type, run these steps:
-
If platformObject is a
Window
orLocation
object, then:-
Repeat for each e that is an element of CrossOriginProperties(platformObject):
-
If SameValue(e.[[Property]], identifier) is true, then:
-
If type is "
method
" and e has neither [[NeedsGet]] nor [[NeedsGet]], then return. -
Otherwise, if type is "
getter
" and e.[[NeedsGet]] is true, then return. -
Otherwise, if type is "
setter
" and e.[[NeedsSet]] is true, then return.
-
-
-
-
If IsPlatformObjectSameOrigin(platformObject) is false, then throw a "
SecurityError
"DOMException
.
6.2.2. Shared internal slot: [[CrossOriginPropertyDescriptorMap]]
Window
and Location
objects both have a [[CrossOriginPropertyDescriptorMap]]
internal slot, whose value is initially an empty map.
The [[CrossOriginPropertyDescriptorMap]] internal slot contains a map with
entries whose keys are (currentOrigin, objectOrigin, propertyKey)-tuples and values are property
descriptors, as a memoization of what is visible to scripts when currentOrigin inspects a Window
or Location
object from objectOrigin. It is filled lazily by CrossOriginGetOwnPropertyHelper, which consults it on future lookups.
User agents should allow a value held in the map to be garbage collected along with its corresponding key when nothing holds a reference to any part of the value. That is, as long as garbage collection is not observable.
const href = Object.getOwnPropertyDescriptor(crossOriginLocation, "href").set
the value and its corresponding key in the map cannot be garbage collected as that would be observable.
User agents may have an optimization whereby they remove key-value pairs from the map when document.domain
is set. This is not observable as document.domain
cannot revisit an earlier value.
document.domain
to "example.com
" on www.example.com
means user agents can remove all key-value pairs from the map where
part of the key is www.example.com
, as that can never be part of the origin again and
therefore the corresponding value could never be retrieved from the map. 6.2.3. Shared abstract operations
6.2.3.1. CrossOriginProperties ( O )
-
Assert: O is a
2. If O is aLocation
orWindow
object.Location
object, then return« { [[Property]]: "href", [[NeedsGet]]: false, [[NeedsSet]]: true }, { [[Property]]: "replace" } »
3. Let crossOriginWindowProperties be« { [[Property]]: "window", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "self", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "location", [[NeedsGet]]: true, [[NeedsSet]]: true }, { [[Property]]: "close" }, { [[Property]]: "closed", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "focus" }, { [[Property]]: "blur" }, { [[Property]]: "frames", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "length", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "top", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "opener", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "parent", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "postMessage" } »
-
Repeat for each e that is an element of the child browsing context name property set:
-
Add { [[Property]]: e } as the last element of crossOriginWindowProperties.
-
-
Return crossOriginWindowProperties.
Indexed properties do not need to be safelisted as they are handled directly by
the WindowProxy
object.
6.2.3.2. IsPlatformObjectSameOrigin ( O )
-
Return true if the current settings object’s origin is same origin-domain with O’s relevant settings object’s origin, and false otherwise.
6.2.3.3. CrossOriginGetOwnPropertyHelper ( O, P )
If this abstract operation returns undefined and there is no custom behavior, the
caller needs to throw a "SecurityError
" DOMException
.
-
If P is @@toStringTag, @@hasInstance, or @@isConcatSpreadable, then return PropertyDescriptor { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
-
Let crossOriginKey be a tuple consisting of the current settings object’s origin’s effective domain, O’s relevant settings object’s origin’s effective domain, and P.
-
Repeat for each e that is an element of CrossOriginProperties(O):
-
If SameValue(e.[[Property]], P) is true, then:
-
If the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O contains an entry whose key is crossOriginKey, then return that entry’s value.
-
Let originalDesc be OrdinaryGetOwnProperty(O, P).
-
Let crossOriginDesc be CrossOriginPropertyDescriptor(e, originalDesc).
-
Create an entry in the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O with key crossOriginKey and value crossOriginDesc.
-
Return crossOriginDesc.
-
-
-
Return undefined.
6.2.3.3.1. CrossOriginPropertyDescriptor ( crossOriginProperty, originalDesc )
-
If crossOriginProperty.[[NeedsGet]] and crossOriginProperty.[[NeedsSet]] are absent, then:
-
Let value be originalDesc.[[Value]].
-
If IsCallable(value) is true, set value to CrossOriginFunctionWrapper(true, value).
-
Return PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.
-
-
Otherwise:
-
Let crossOriginGet be CrossOriginFunctionWrapper(crossOriginProperty.[[NeedsGet]], originalDesc.[[Get]]).
-
Let crossOriginSet be CrossOriginFunctionWrapper(crossOriginProperty.[[NeedsSet]], originalDesc.[[Set]]).
-
Return PropertyDescriptor{ [[Get]]: crossOriginGet, [[Set]]: crossOriginSet, [[Enumerable]]: false, [[Configurable]]: true }.
-
6.2.3.3.2. CrossOriginFunctionWrapper ( needsWrapping, functionToWrap )
-
If needsWrapping is false, then return undefined.
-
Return a new cross-origin wrapper function whose [[Wrapped]] internal slot is functionToWrap.
A cross-origin wrapper function is an anonymous built-in function that has a [[Wrapped]] internal slot.
When a cross-origin wrapper function F is called with a list of arguments argumentsList, the following steps are taken:
-
Assert: F has a [[Wrapped]] internal slot that is a function.
-
Let wrappedFunction be the [[Wrapped]] internal slot of F.
-
Return Call(wrappedFunction, this, argumentsList).
Due to this being invoked from a different origin, a cross-origin wrapper function will have a different value for Function.prototype
from the function being wrapped. This follows from how JavaScript
creates anonymous built-in functions.
6.2.3.4. CrossOriginGet ( O, P, Receiver )
-
Let desc be O.[[GetOwnProperty]](P).
-
Assert: desc is not undefined.
-
If IsDataDescriptor(desc) is true, then return desc.[[Value]].
-
Assert: IsAccessorDescriptor(desc) is true.
-
Let getter be desc.[[Get]].
-
If getter is undefined, throw a "
SecurityError
"DOMException
. -
Return Call(getter, Receiver).
6.2.3.5. CrossOriginSet ( O, P, V, Receiver )
-
Let desc be O.[[GetOwnProperty]](P).
-
Assert: desc is not undefined.
-
If IsAccessorDescriptor(desc) is true, then:
-
Let setter be desc.[[Set]].
-
If setter is undefined, return false.
-
Perform Call(setter, Receiver, «V»).
-
Return true.
-
-
Return false.
6.2.3.6. CrossOriginOwnPropertyKeys ( O )
-
Let keys be a new empty List.
-
Repeat for each e that is an element of CrossOriginProperties(O):
-
Add e.[[Property]] as the last element of keys.
-
-
Return keys.
6.3. The Window
object
[PrimaryGlobal, LegacyUnenumerableNamedProperties] /*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; // 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 unsigned long requestAnimationFrame(FrameRequestCallback callback); void cancelAnimationFrame(unsigned long handle); }; Window implements GlobalEventHandlers; Window implements WindowEventHandlers; callback FrameRequestCallback = void (DOMHighResTimeStamp time);
- window .
window
- window .
frames
- window .
self
-
These attributes all return window.
- window .
document
-
Returns the
Document
associated with window. - document .
defaultView
-
Returns the
Window
object of the active document.
The window
, frames
, and self
IDL attributes must all return the Window
object’s browsing context’s WindowProxy
object.
The document
IDL attribute must return the Window
object’s newest Document
object.
The Document
object associated with a Window
object can change in
exactly one case: when the navigate algorithm initializes 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.
6.3.1. APIs for creating and navigating browsing contexts by name
- window = window .
open
( [ url [, target [, features [, replace ] ] ] ] ) -
Opens a window to show url (defaults to
about:blank
), and returns it. The target argument gives the name of the new window. If a window exists with that name already, it is reused. The replace attribute, if true, means that whatever page is currently open in that window will be removed from the window’s session history. The features argument can be used to influence the rendering of the new window. - window .
name
[ = value ] -
Returns the name of the window.
Can be set, to change the name.
- window .
close
() -
Closes the window.
- window .
closed
-
Returns true if the window has been closed, false otherwise.
- window .
stop
() -
Cancels the document load.
The open()
method on Window
objects
provides a mechanism for navigating an existing browsing
context or opening and navigating an auxiliary browsing context.
When the method is invoked, the user agent must run the following steps:
- 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 thewindow.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. [CSSOM-VIEW]
-
If url is the empty string, run the appropriate steps from the following list:
- If new is false
- Jump to the step labeled end.
- If new is true
- Let resource be the URL "
about:blank
".
Otherwise, parse url relative to entry settings, and let resource be the resulting URL record, if any. If the parse 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 namedload
at target browsing context’sWindow
object, with target override set to target browsing context’sWindow
object’sDocument
object.Otherwise, navigate target browsing context to resource, with the exceptions enabled flag set. 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:
- The corresponding browsing context A is script-closable.
- The responsible browsing context specified by the incumbent settings object is familiar with the browsing context A.
- The responsible browsing context specified by the incumbent settings object is allowed to navigate 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.
6.3.2. Accessing other browsing contexts
- window .
length
- Returns the number of child browsing contexts.
- window[index]
- Returns the indicated child browsing context.
The number of child browsing contexts of a Window
object W is the number
of child browsing contexts that are nested through elements that are in a Document
that is the active document of the Window
object’s associated Document
object’s browsing context.
The length
IDL attribute’s getter must return the number of child browsing contexts of this Window
object.
Indexed access to child browsing contexts is defined through the [[GetOwnProperty]] internal method of the WindowProxy
object.
6.3.3. Named access on the Window
object
- window[name]
-
Returns the indicated element or collection of elements.
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use
document.getElementById()
ordocument.querySelector()
.
The child browsing context name property set consists of the browsing context names of any child browsing context of the active document whose name is not the empty string, with duplicates omitted.
The Window
interface supports named properties.
The supported property names at any moment consist of the following, in tree order,
ignoring later duplicates:
-
the value of the
name
content attribute for alla
,applet
,area
,embed
,form
,frameset
,img
, andobject
elements in the active document that have a non-emptyname
content attribute, and -
the value of the
id
content attribute of any HTML element in the active document with a non-emptyid
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 theDocument
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:
- child browsing contexts of the active document whose name is name,
a
,applet
,area
,embed
,form
,frameset
,img
, orobject
elements that have aname
content attribute whose value is name, or- html elements that have an
id
content attribute whose value is name.
6.3.4. Garbage collection and browsing contexts
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. - Abort the
Document
. - 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 theDocument
.
Whenever a Document
object is discarded, it is also removed from the list of the worker’s Documents
of each worker whose list contains that Document
.
When a browsing context is discarded, the strong reference from the user
agent itself to the browsing context must be severed, and all the Document
objects for all the entries in the browsing context’s session
history must be discarded as well.
User agents may discard top-level browsing contexts at any time (typically, in
response to user requests, e.g., when a user force-closes a window containing one or more top-level browsing contexts). Other browsing contexts must be discarded once their WindowProxy
object is eligible for garbage collection.
6.3.5. Closing browsing contexts
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.
6.3.6. Browser interface elements
To allow Web pages to integrate with Web browsers, certain Web browser interface elements are exposed in a limited way to scripts in Web pages.
Each interface element is represented by a BarProp
object:
interface BarProp { readonly attribute boolean visible; };
- window .
locationbar
.visible
- Returns true if the location bar is visible; otherwise, returns false.
- window .
menubar
.visible
- Returns true if the menu bar is visible; otherwise, returns false.
- window .
personalbar
.visible
- Returns true if the personal bar is visible; otherwise, returns false.
- window .
scrollbars
.visible
- Returns true if the scroll bars are visible; otherwise, returns false.
- window .
statusbar
.visible
- Returns true if the status bar is visible; otherwise, returns false.
- window .
toolbar
.visible
- Returns true if the toolbar is visible; otherwise, returns false.
The visible attribute, on getting, must return either true or a value determined by the user agent to most accurately represent the visibility state of the user interface element that the object represents, as described below.
The following BarProp
objects exist for each Document
object in a browsing context. Some of the user interface elements represented by these objects
might have no equivalent in some user agents; for those user agents, except when otherwise
specified, the object must act as if it was present and visible (i.e., its visible
attribute must return true).
- The location bar
BarProp
object - Represents the user interface element that contains a control that displays the URL of the active document, or some similar interface concept.
- The menu bar
BarProp
object - Represents the user interface element that contains a list of commands in menu form, or some similar interface concept.
- The personal bar
BarProp
object - Represents the user interface element that contains links to the user’s favorite pages, or some similar interface concept.
- The scrollbar
BarProp
object - Represents the user interface element that contains a scrolling mechanism, or some similar interface concept.
- The status bar
BarProp
object - Represents a user interface element found immediately below or after the document, as
appropriate for the user’s media, which typically provides information about ongoing network
activity or information about elements that the user’s pointing device is current indicating. If
the user agent has no such user interface element, then the object may act as if the
corresponding user interface element was absent (i.e., its
visible
attribute may return false). - The toolbar
BarProp
object - Represents the user interface element found immediately above or before the document, as
appropriate for the user’s media, which typically provides session history traversal
controls (back and forward buttons, reload buttons, etc). If the user agent has no such user
interface element, then the object may act as if the corresponding user interface element was
absent (i.e., its
visible
attribute may return false).
The locationbar
attribute must return the location bar BarProp
object.
The menubar
attribute must return the
menu bar BarProp
object.
The personalbar
attribute must return the personal bar BarProp
object.
The scrollbars
attribute must return the scrollbar BarProp
object.
The statusbar
attribute must return the status bar BarProp
object.
The toolbar
attribute must return the
toolbar BarProp
object.
For historical reasons, the status
attribute
on the Window
object must, on getting, return the last string it was set to, and on
setting, must set itself to the new value. When the Window
object is created, the
attribute must be set to the empty string. It does not do anything else.
6.3.7. The WindowProxy
object
A WindowProxy
is an exotic object that wraps a Window
ordinary object, indirecting most operations through to the wrapped object. Each browsing context has an associated WindowProxy
object. When the browsing context is navigated, the Window
object wrapped by the browsing context’s associated WindowProxy
object is changed.
There is no WindowProxy
interface object.
Every WindowProxy
object has a [[Window]] internal slot
representing the wrapped Window
object.
Although WindowProxy
is named as a "proxy", it does not do polymorphic
dispatch on its target’s internal methods as a real proxy would, due to a desire to reuse
machinery between WindowProxy
and Location
objects. As long as the Window
object
remains an ordinary object this is unobservable and can be implemented either way.
WindowProxy
object
returned by the window
accessor on the global object. All of the
expressions following the assignment return true, because the WindowProxy
object passes
most operations through to the underlying ordinary Window
object.
var x = window; x instanceof Window; // true x === this; // true
6.3.7.1. The WindowProxy
internal methods
The WindowProxy
object internal methods are described in the subsections below.
6.3.7.1.1. [[GetPrototypeOf]] ( )
-
Let W be the value of the [[Window]] internal slot of this.
-
If IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetPrototypeOf(W).
-
Return null.
6.3.7.1.2. [[SetPrototypeOf]] ( V )
-
Return false.
6.3.7.1.3. [[IsExtensible]] ( )
-
Return true.
6.3.7.1.4. [[PreventExtensions]] ( )
-
Return false.
6.3.7.1.5. [[GetOwnProperty]] ( P )
-
Let W be the value of the [[Window]] internal slot of this.
-
If P is an array index property name, then:
-
Let index be ToUint32(P).
-
Let maxProperties be the number of child browsing contexts of W.
-
Let value be undefined.
-
If maxProperties is greater than 0 and index is less than maxProperties, then:
-
Set value to the
WindowProxy
object of the indexth child browsing context of theDocument
that is nested through an element that is in W’sDocument
, sorted in the order that the elements nesting those browsing contexts were most recently inserted into theDocument
, theWindowProxy
object of the most recently inserted browsing context container’s nested browsing context being last.
-
-
Return PropertyDescriptor{ [[Value]]: value, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
-
-
If IsPlatformObjectSameOrigin(W) is true, then return OrdinaryGetOwnProperty(W, P).
This violates JavaScript’s internal method invariants.
-
Let property be CrossOriginGetOwnPropertyHelper(W, P).
-
If property is not undefined, return property.
-
If property is undefined and P is in the child browsing context name property set, then:
-
Let value be the
WindowProxy
object of the named object with the name P. -
Return PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.
-
-
Throw a "
SecurityError
"DOMException
.
6.3.7.1.6. [[DefineOwnProperty]] ( P, Desc )
-
If P is an array index property name, return false.
-
Let W be the value of the [[Window]] internal slot of this.
-
If IsPlatformObjectSameOrigin(W) is true, then return OrdinaryDefineOwnProperty(W, P, Desc).
See above about how this violates JavaScript’s internal method invariants.
-
Return false.
6.3.7.1.7. [[Get]] ( P, Receiver )
-
Let W be the value of the [[Window]] internal slot of this.
-
If IsPlatformObjectSameOrigin(W) is true, then return OrdinaryGet(this, P, Receiver).
-
Return ? CrossOriginGet(this, P, Receiver).
6.3.7.1.8. [[Set]] ( P, V, Receiver )
-
Let W be the value of the [[Window]] internal slot of this.
-
If IsPlatformObjectSameOrigin(W) is true, then return OrdinarySet(W, this, Receiver).
-
Return CrossOriginSet(this, P, V, Receiver).
6.3.7.1.9. [[Delete]] ( P )
-
If P is an array index property name, return false.
-
Let W be the value of the [[Window]] internal slot of this.
-
If IsPlatformObjectSameOrigin(W) is true, then return OrdinaryDelete(W, P).
-
Return false.
6.3.7.1.10. [[OwnPropertyKeys]] ( )
-
Let W be the value of the [[Window]] internal slot of this.
-
Let keys be a new empty List.
-
Let maxProperties be the number of child browsing contexts of W.
-
Let index be 0.
-
Repeat while index < maxProperties,
-
Add ! ToString(index) as the last element of keys.
-
Increment index by 1.
-
-
If IsPlatformObjectSameOrigin(W) is true, then return the concatenation of keys and ! OrdinaryOwnPropertyKeys(W).
-
Return the concatenation of keys and ! CrossOriginOwnPropertyKeys(W).
6.4. Origin
Origins are the fundamental currency of the Web’s security model. Two actors in the Web platform that share an origin are assumed to trust each other and to have the same authority. Actors with differing origins are considered potentially hostile versus each other, and are isolated from each other to varying degrees.
For example, if Example Bank’s Web site, hosted at bank.example.com
, tries to examine the DOM of Example Charity’s Web site, hosted at charity.example.org
, a "SecurityError
" DOMException
will be raised.
An origin is one of the following:
-
An opaque origin
-
An internal value, with no serialisation, for which the only meaningful operation is testing for equality.
-
A tuple origin
-
A tuple consists of:
Origins can be shared, e.g., among multiple Document
objects. Furthermore, origins are generally immutable. Only the domain of a tuple origin can be changed, and only through the document.domain
API.
The effective domain of an origin origin is computed as follows:
-
If origin is an opaque origin, then return origin.
-
If origin’s domain is non-null, then return origin’s domain.
-
Return origin’s host.
Various specification objects are defined to have an origin. These origins are determined as follows:
-
For
Document
objects -
- If the
Document
's active sandboxing flag set has its sandboxed origin browsing context flag set - A unique opaque origin is assigned when the
Document
is created. - If the
Document
's URL’s scheme is a network scheme -
A copy of the
Document
's URL’s origin assigned when theDocument
is created.The
document.open()
method can change theDocument
's URL to "about:blank
". Therefore the origin is assigned when theDocument
is created. - If the
Document
is the initial "about:blank
" document - The one it was assigned when its browsing context was created.
- If the
Document
is a non-initial "about:blank
" document - If the
Document
was generated from adata:
URL found in anotherDocument
or in a script - The origin of 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.
- If the
Document
was created as part of the processing forjavascript:
URLs - The origin of the active document of the browsing context being navigated when the navigate algorithm was invoked.
- If the
Document
is aniframe
srcdoc
document - The origin of the
Document
's browsing context’s browsing context container’s node document. - If the
Document
was obtained in some other manner (e.g., adata:
URL typed in by the user or that was returned as the location of a redirect, aDocument
created using thecreateDocument()
API, etc) -
The default behavior as defined in the DOM standard applies. [DOM].
The origin is a unique opaque origin assigned when the
Document
is created.
- If the
-
For images of
img
elements -
- If the image data is CORS-cross-origin
- A unique opaque origin assigned when the image is created.
- If the image data is CORS-same-origin
- The
img
element’s node document’s origin.
-
- If the media data is CORS-cross-origin
- A unique opaque origin assigned when the media data is fetched.
- If the media data is CORS-same-origin
- The media element’s node document’s origin.
-
For fonts
-
For a downloadable Web font it is a copy of the origin of the URL record used to obtain the font (after any redirects). [CSS-FONTS-3] [CSS-FONT-LOADING-3]
For a locally installed system font it is the origin of the
Document
in which that font is being used.
Other specifications can override the above definitions by themselves specifying the origin of
a particular Document
object, image, media element, or font.
The Unicode serialization of an origin is the string obtained by applying the following algorithm to the given origin origin:
-
If origin is an opaque origin, then return "
null
". -
Let host be origin’s host.
-
Let unicodeHost be host if host is not a domain, and the result of applying domain to Unicode to host otherwise.
-
Let unicodeOrigin be a new tuple origin consisting origin’s scheme, unicodeHost, and origin’s port.
-
Return the ASCII serialization of an origin, given unicodeOrigin.
The name ASCII serialization of an origin is misleading, as it merely serialises an origin, which are all ASCII by default due to the URL parser.
https
", "xn--maraa-rta.example
",
null, null) is "https://maraña.example
". The ASCII serialization of an origin is the string obtained by applying the following algorithm to the given origin origin:
-
If origin is an opaque origin, then return "
null
". -
Otherwise, let result be origin’s scheme.
-
Append "
://
" to result. -
Append origin’s host, serialized, to result.
-
If origin’s port is non-null, append a U+003A COLON character (:), and origin’s port, serialized, to result.
-
Return result.
Two origins A and B are said to be same origin if the following algorithm returns true:
-
If A and B are the same opaque origin, then return true.
-
If A and B are both tuple origins, and their schemes, hosts, and ports are identical, then return true.
-
Return false.
Two origins A and B are said to be same origin-domain if the following algorithm returns true:
-
If A and B are the same opaque origin, then return true.
-
If A and B are both tuple origins, run these substeps:
-
If A and B’s schemes are identical, and their domains are identical and non-null, then return true.
-
Otherwise, if A and B are same origin and their domains are identical and null, then return true.
-
-
Return false.
A | B | same origin | same origin-domain |
---|---|---|---|
("https ", "example.org ", null, null)
| ("https ", "example.org ", null, null)
| ✅ | ✅ |
("https ", "example.org ", 314, "example.org ")
| ("https ", "example.org ", 420, "example.org ")
| ❌ | ✅ |
("https ", "example.org ", null, null)
| ("https ", "example.org ", null, "example.org ")
| ✅ | ❌ |
("https ", "example.org ", null, "example.org ")
| ("http", "example.org ", null, "example.org ")
| ❌ | ❌ |
6.4.1. Relaxing the same-origin restriction
- document .
domain
[ = domain ] -
Returns the current domain used for security checks.
Can be set to a value that removes subdomains, to change the origin’s domain 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’s getter must run these
steps:
-
If this
Document
object does not have a browsing context, then return the empty string. -
Let effectiveDomain be this
Document
's origin’s effective domain. -
If effectiveDomain is an opaque origin, then return the empty string.
-
Return effectiveDomain, serialised.
The domain
attribute on setting must run these steps:
-
If this
Document
object has no browsing context, throw a "SecurityError
"DOMException
. -
If this
Document
object’s active sandboxing flag set has its sandboxeddocument.domain
browsing context flag set, then throw a "SecurityError
"DOMException
. -
If the given value is the empty string, then throw a "
SecurityError
"DOMException
. -
Let host be the result of parsing the given value.
-
If host is failure, then throw a "
SecurityError
"DOMException
. -
Let effectiveDomain be this
Document
object’s origin’s effective domain. -
If host is not equal to effectiveDomain, then run these substeps:
-
If host or effectiveDomain is not domain, then throw a "
SecurityError
"DOMException
.This is meant to exclude hosts that are an IPv4 address or an IPv6 address.
-
If host, prefixed by a U+002E FULL STOP (.), does not exactly match the effectiveDomain, then throw a "
SecurityError
"DOMException
. -
If host matches a suffix in the Public Suffix List, or, if host, prefixed by a U+002E FULL STOP (.), matches the end of a suffix in the Public Suffix List, then throw a "
SecurityError
"DOMException
. [PSL]Suffixes must be compared after applying the host parser algorithm. [URL]
-
-
Set origin’s domain to host.
The document.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.
6.5. Sandboxing
A sandboxing flag set is a set of zero or more of the following flags, which are used to restrict the abilities that potentially untrusted resources have:
- The sandboxed navigation browsing context flag
-
This flag prevents content from navigating browsing contexts other than the sandboxed browsing context itself (or browsing contexts further nested inside it), auxiliary browsing contexts (which are protected by the sandboxed auxiliary navigation browsing context flag defined next), and the top-level browsing context (which is protected by the sandboxed top-level navigation browsing context flag defined below).
If the sandboxed auxiliary navigation browsing context flag is not set, then in certain cases the restrictions nonetheless allow popups (new top-level browsing contexts) to be opened. These browsing contexts always have one permitted sandboxed navigator, set when the browsing context is created, which allows the browsing context that created them to actually navigate them. (Otherwise, the sandboxed navigation browsing context flag would prevent them from being navigated even if they were opened.)
- The sandboxed auxiliary navigation browsing context flag
-
This flag prevents content from creating new auxiliary browsing contexts, e.g., using the
target
attribute, thewindow.open()
method, or theshowModalDialog()
method. - The sandboxed top-level navigation browsing context flag
-
This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context.
When the sandboxed top-level navigation browsing context flag is not set, content can navigate its top-level browsing context, but other browsing contexts are still protected by the sandboxed navigation browsing context flag and possibly the sandboxed auxiliary navigation browsing context flag.
- The sandboxed plugins browsing context flag
-
This flag prevents content from instantiating plugins, whether using the
embed
element, theobject
element, theapplet
element, or through navigation of a nested browsing context, unless those plugins can be secured. - The sandboxed origin browsing context flag
-
This flag forces content into a unique origin, thus preventing it from accessing other content from the same origin.
This flag also prevents script from reading from or writing to the
document.cookie
IDL attribute, and blocks access tolocalStorage
. [WEBSTORAGE] - The sandboxed forms browsing context flag
-
This flag blocks form submission.
- The sandboxed pointer lock browsing context flag
-
This flag disables the Pointer Lock API. [POINTERLOCK]
- The sandboxed scripts browsing context flag
-
This flag blocks script execution.
- The sandboxed automatic features browsing context flag
-
This flag blocks features that trigger automatically, such as automatically playing a video or automatically focusing a form control.
- The sandboxed storage area URLs flag
-
This flag prevents URL schemes that use storage areas from being able to access the origin’s data.
- The sandboxed fullscreen browsing context flag
-
This flag prevents content from using the
requestFullscreen()
method. - The sandboxed
document.domain
browsing context flag - This flag prevents content from using the
document.domain
setter. - The sandbox propagates to auxiliary browsing contexts flag
-
This flag prevents content from escaping the sandbox by ensuring that any auxiliary browsing context it creates inherits the content’s active sandboxing flag set.
- The sandboxed modals flag
-
This flag prevents content from using any of the following features to produce modal dialogs:
window.alert()
window.confirm()
window.print()
window.prompt()
window.showModalDialog()
- the
beforeunload
event
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 navigation browsing context flag.
- 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 plugins browsing context flag.
-
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 storage area URLs flag.
- The sandboxed fullscreen browsing context flag, unless the allow fullscreen flag was passed to the parse a sandboxing directive flag.
- The sandboxed
document.domain
browsing context flag. - The sandbox propagates to auxiliary browsing contexts flag, unless tokens contains the
allow-popups-to-escape-sandbox
keyword. - The sandboxed modals flag, unless tokens contains the
allow-modals
keyword.
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. [CSP3]
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’siframe
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.
6.6. Session history and navigation
6.6.1. The session history of browsing contexts
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 restoration mode, 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.
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.
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.
An entry’s scroll restoration mode indicates whether the user agent should restore the persisted scroll position (if any) when traversing to it. The scroll restoration mode may be one of the following:
- "
auto
" - The user agent is responsible for restoring the scroll position upon navigation.
- "
manual
" - The page is responsible for restoring the scroll position and the user agent does not attempt to do so automatically
If unspecified, the scroll restoration mode of a new entry must be set to
"auto
".
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.
6.6.2. The History
interface
enum ScrollRestoration { "auto", "manual" };
interface History { readonly attribute unsigned long length; attribute ScrollRestoration scrollRestoration; readonly attribute any state; void go(optional long delta = 0); void back(); void forward(); void pushState(any data, DOMString title, optional DOMString? url = null); void replaceState(any data, DOMString title, optional DOMString? url = null); };
- window .
history
.length
-
Returns the number of entries in the joint session history.
- window .
history
.scrollRestoration
[ = value ] -
Returns the scroll restoration mode of the current entry in the session history.
Can be set, to change the scroll restoration mode of the current entry in the session history.
- window .
history
.state
-
Returns the current state object.
- window .
history
.go
( [ delta ] ) -
Goes back or forward the specified number of steps in the joint session history.
A zero delta will reload the current page.
If the delta is out of range, does nothing.
- window .
history
.back
() -
Goes back one step in the joint session history.
If there is no previous page, does nothing.
- window .
history
.forward
() -
Goes forward one step in the joint session history.
If there is no next page, does nothing.
- window .
history
.pushState
(data, title [, url ] ) -
Pushes the given data onto the session history, with the given title, and, if provided and not null, the given URL.
- window .
history
.replaceState
(data, title [, url ] ) -
Updates the current entry in the session history to have the given data, title, and, if provided and not null, URL.
The joint session history of a top-level browsing context is the union
of all the session histories of all browsing contexts of all the fully active Document
objects that share that top-level browsing context, with all the entries that are current entries in their respective session histories removed except for the current entry of the joint session
history.
The current entry of the joint session history is the entry that most recently became a current entry in its session history.
Entries in the joint session history are ordered chronologically by the time they were added to their respective session histories. Each entry has an index; the earliest entry has index 0, and the subsequent entries are numbered with consecutively increasing integers (1, 2, 3, etc).
Since each Document
in a browsing context might have a
different event loop, the actual state of the joint session history can
be somewhat nebulous. For example, two sibling iframe
elements could both traverse from one unique origin to another at the same time,
so their precise order might not be well-defined; similarly, since they might only find out about
each other later, they might disagree about the length of the joint session
history.
The length
attribute of the History
interface, on getting, must return the number of entries in the top-level browsing context’s joint session history. If this History
object is associated with a Document
that is not fully active, getting must instead throw a "SecurityError
" DOMException
.
The actual entries are not accessible from script.
The scrollRestoration
attribute
of the History interface, on getting, must return the scroll restoration mode of the
current entry in the session history. On setting, the scroll restoration mode of the current entry in the session history must be set to the new
value. If this History
object is associated with a Document
that is
not fully active, both getting and setting must instead throw a
"SecurityError
" DOMException
.
The state
attribute of the History
interface, on getting, must return the last value it was set to by the user
agent. If this History
object is associated with a Document
that is
not fully active, getting must instead throw a SecurityError
DOMException
.
Initially, its value must be null.
When the go(delta)
method is
invoked, if delta is 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 delta If this History
object is associated with a Document
that is not fully active, invoking must instead throw a
"SecurityError
" DOMException
.
When the back()
method is invoked, the user
agent must traverse the history by a delta −1. If this History
object is associated with a Document
that is not fully active,
invoking must instead throw a "SecurityError
" DOMException
.
When the forward()
method is invoked, the
user agent must traverse the history by a delta +1. If this History
object is associated with a Document
that is not fully active,
invoking must instead throw a "SecurityError
" DOMException
.
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 synchronization.
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:
- 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 theDocument
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.
- 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
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()
method adds a state object entry to
the history.
The replaceState()
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:
-
If this
History
object is associated with aDocument
that is not fully active, throw a "SecurityError
"DOMException
. -
Optionally, abort these steps. (For example, the user agent might disallow calls to these methods 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.)
-
Let targetRealm be this
History
object’s relevant settings object’s Realm. -
Let cloned data be a StructuredClone(data, targetRealm). Rethrow any exceptions.
-
If the third argument is not null, run these substeps:
-
Parse the value of the third argument, relative to the entry settings object.
-
If that fails, throw a "
SecurityError
"DOMException
and abort these steps. -
Let new URL be the resulting URL record.
-
Compare new URL to the document’s URL. If any component of these two URL records differ other than the path, query, and fragment components, then throw a "
SecurityError
"DOMException
and abort these steps. -
If the origin of new URL is not the same as the origin of the responsible document specified by the entry settings object, and either the path or query components of the two URL records compared in the previous step differ, throw a "
SecurityError
"DOMException
and abort these steps. (This prevents sandboxed content from spoofing other pages on the same origin.)
-
-
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, new URL as the URL of the entry, and the scroll restoration mode of the current entry in the session history as the scroll restoration mode.
-
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.
-
Set the document’s URL 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. -
Let targetRealm be this
History
object’s relevant settings object’s Realm. -
Set
history.state
to StructuredClone(cloned data, targetRealm). -
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 user agent-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.)
A static page implementing the x=5 position in such a game could look like the following:
<!DOCTYPE HTML> <!-- this is https://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 https://example.com/line?x=5 --> <title>Line Game - 5</title> <p>You are at coordinate <span>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.
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>
scrollRestoration
attribute as soon as possible
(e.g., in the first script
element in the document’s head
element) to
ensure that any entry added to the history session gets the desired scroll restoration mode.
<head> <script> if ('scrollRestoration' in history) history.scrollRestoration = 'manual'; </script> </head>
6.6.3. Implementation notes for session history
This section is non-normative.
The History
interface is not meant to place restrictions on how implementations represent the
session history to the user.
For example, session history could be implemented in a tree-like manner, with each page having
multiple "forward" pages. This specification doesn’t define how the linear list of pages in the history
object are derived from the actual session history as seen from the user’s
perspective.
Similarly, a page containing two 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.
For both pushState()
and replaceState()
, user agents are encouraged to
prevent abuse of these APIs via too-frequent calls or over-large state objects. As detailed above,
the algorithm explicitly allows user agents to ignore any such calls when appropriate.
6.6.4. The Location
interface
Each Window
object is associated with a unique instance of a Location
object, allocated
when the Window
object is created.
To create a Location
object, run these steps:
-
Let location be a new
Location
platform object. -
Perform ! location.[[DefineOwnProperty]]("
toString
", { [[Value]]: %ObjProto_toString%, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }). -
Perform ! location.[[DefineOwnProperty]]("
toJSON
", { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }). -
Perform ! location.[[DefineOwnProperty]]("
valueOf
", { [[Value]]: %ObjProto_valueOf%, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }). -
Perform ! location.[[DefineOwnProperty]](@@toPrimitive, { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).
-
Set the value of the [[DefaultProperties]] internal slot of location to location.[[OwnPropertyKeys]]().
-
Return location.
- document .
location
[ = value ] - window .
location
[ = value ] -
Returns a
Location
object with the current page’s location.Can be set, to navigate to another page.
The location
attribute of the Document
interface must return the Location
object for that Document
object’s global object,
if it has a browsing context, and null otherwise.
The location
attribute of the Window
interface
must return the Location
object for that Window
object.
Location
objects provide a representation of the URL 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 { stringifier attribute USVString href; readonly attribute USVString origin; attribute USVString protocol; attribute USVString host; attribute USVString hostname; attribute USVString port; attribute USVString pathname; attribute USVString search; attribute USVString hash; void assign(USVString url); void replace(USVString url); void reload(); [SameObject] readonly attribute USVString[] ancestorOrigins; };
- location .
toString()
- location .
href
-
Returns the
Location
object’s URL.Can be set, to navigate to the given URL.
- location .
origin
- Returns the
Location
object’s URL’s origin. - location .
protocol
-
Returns the
Location
object’s URL’s scheme.Can be set, to navigate to the same URL with a changed scheme.
- location .
host
-
Returns the
Location
object’s URL’s host and port (if different from the default port for the scheme).Can be set, to navigate to the same URL with a changed host and port.
- location .
hostname
-
Returns the
Location
object’s URL’s host.Can be set, to navigate to the same URL with a changed host.
- location .
port
-
Returns the
Location
object’s URL’s port.Can be set, to navigate to the same URL with a changed port.
- location .
pathname
-
Returns the
Location
object’s URL’s path.Can be set, to navigate to the same URL with a changed path.
- location .
search
-
Returns the
Location
object’s URL’s query (includes leading "?
" if non-empty).Can be set, to navigate to the same URL with a changed query (ignores leading "
?
"). - location .
hash
-
Returns the
Location
object’s URL’s fragment (includes leading "#
" if non-empty).Can be set, to navigate to the same URL with a changed fragment (ignores leading "
#
"). - location . {{Location/assign(url)}}
- Navigates to the given URL.
- location . {{Location/replace(url)}}
- Removes the current page from the session history and navigates to the given URL.
- location .
reload()
- Reloads the current page.
- location .
ancestorOrigins
- Returns an array whose values are the origins of the ancestor browsing contexts, from the parent browsing context to the top-level browsing context.
A Location
object has an associated relevant Document
, which is this Location
object’s associated Document
object’s browsing context’s active document.
A Location
object has an associated url, which is this Location
object’s relevant Document
’s URL.
A Location
object has an associated ancestor origins array. When a Location
object is created, its ancestor origins array must be set to a array created from the list
of strings that the following steps would produce:
-
Let output be an empty ordered list of strings.
-
Let current be the browsing context of the
Document
with which theLocation
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 serialization of current’s active document’s origin to output as a new value.
-
Return to the step labeled Loop.
-
End: Return output.
A Location
object has an associated Location
-object-setter navigate algorithm, which given a url, runs these steps:
-
If any of the following conditions are met, let replacement flag be unset; otherwise, let it be set:
-
This
Location
object’s relevantDocument
has completely loaded, or -
In the task in which the algorithm is running, an activation behavior is currently being processed whose
click
event was trusted, or -
In the task in which the algorithm is running, the event listener for a trusted
click
event is being handled.
-
-
Location
-object navigate, given url and replacement flag.
To Location
-object navigate, given a url and replacement flag, run these steps:
-
The source browsing context is the responsible browsing context specified by the incumbent settings object.
-
Navigate the browsing context to url, with the exceptions enabled flag set. Rethrow any exceptions.
If the replacement flag is set or the browsing context’s session history contains only one
Document
, and that was theabout:blank
Document
created when the browsing context was created, then the navigation must be done with replacement enabled.
The href
attribute’s getter must return this Location
object’s URL, serialized.
The href
attribute’s setter must run these steps:
- Let newURL be the resulting URL string of parsing the given value relative to the entry settings object’s API base URL.
- If that aborted with an error, throw a
TypeError
exception. Location
-object-setter navigate to newURL.
The origin
attribute’s getter must return
the Unicode serialization of this Location
object’s URL’s origin.
It returns the Unicode rather than the ASCII serialization for
compatibility with MessageEvent
.
The protocol
attribute’s getter must
return this Location
object’s URL’s scheme, followed by ":
".
The protocol
attribute’s setter must run these
steps:
- Let copyURL be a copy of this
Location
object’s URL. - Let possibleFailure be the result of basic URL parsing the given value, followed by "
:
", with copyURL as url and scheme start state as state override. - If possibleFailure is failure, throw a
TypeError
exception. - If copyURL’s scheme is not "
http
" or "https
", terminate these steps. Location
-object-setter navigate to copyURL.
The host
attribute’s getter must run these
steps:
- Let url be this
Location
object’s URL. - If url’s host is null, return the empty string.
- If url’s port is null, return url’s host, serialized.
- Return url’s host, serialized, followed by "
:
" and url’s port, serialized.
The host
attribute’s setter must run these steps:
- Let copyURL be a copy of this
Location
object’s URL. - If copyURL’s non-relative flag is set, terminate these steps.
- Basic URL parse the given value, with copyURL as url and host state as state override.
Location
-object-setter navigate to copyURL.
The hostname
attribute’s getter must
run these steps:
- If this
Location
object’s URL’s host is null, return the empty string. - Return this
Location
object’s URL’s host, serialized.
The hostname
attribute’s setter must run these
steps:
- Let copyURL be a copy of this
Location
object’s URL. - If copyURL’s non-relative flag is set, terminate these steps.
- Basic URL parse the given value, with copyURL as url and hostname state as state override.
Location
-object-setter navigate to copyURL.
The port
attribute’s getter must run these
steps:
- If this
Location
object’s URL’s port is null, return the empty string. - Return this
Location
object’s URL’s port, serialized.
The port
attribute’s setter must run these steps:
- Let copyURL be a copy of this
Location
object’s URL. - If copyURL’s host is null, copyURL’s non-relative flag is set, or copyURL’s scheme is "
file
", terminate these steps. - Basic URL parse the given value, with copyURL as url and port state as state override.
Location
-object-setter navigate to copyURL.
The pathname
attribute’s getter must
run these steps:
- Let url be this
Location
object’s URL. - If url’s non-relative flag is set, return the first string in url’s path.
- Return "
/
", followed by the strings in url’s path (including empty strings), separated from each other by "/
".
The pathname
attribute’s setter must run these
steps:
- Let copyURL be a copy of this
Location
object’s URL. - If copyURL’s non-relative flag is set, terminate these steps.
- Set copyURL’s path to the empty list.
- Basic URL parse the given value, with copyURL as url and path start state as state override.
Location
-object-setter navigate to copyURL.
The search
attribute’s getter must run
these steps:
- If this
Location
object’s URL’s query is either null or the empty string, return the empty string. - Return "
?
", followed by thisLocation
object’s URL’s query.
The search
attribute’s setter must run these
steps:
- Let copyURL be a copy of this
Location
object’s URL. - If the given value is the empty string, set copyURL’s query to null.
-
Otherwise, run these substeps:
- Let input be the given value with a single leading "
?
" removed, if any. - Set copyURL’s query to the empty string.
- Basic URL parse input, with copyURL as url and query state as state override,
and the relevant
Document
’s document’s character encoding as encoding override.
- Let input be the given value with a single leading "
Location
-object-setter navigate to copyURL.
The hash
attribute’s getter must run these
steps:
- If this
Location
object’s URL’s fragment is either null or the empty string, return the empty string. - Return "
#
", followed by thisLocation
object’s URL’s fragment.
The hash
attribute’s setter must run these steps:
- Let copyURL be a copy of this
Location
object’s URL. - If copyURL’s scheme is "
javascript
", terminate these steps. - If the given value is the empty string, set copyURL’s fragment to null.
-
Otherwise, run these substeps:
- Let input be the given value with a single leading "
#
" removed, if any. - Set copyURL’s fragment to the empty string.
- Basic URL parse input, with copyURL as url and fragment state as state override.
- Let input be the given value with a single leading "
Location
-object-setter navigate to copyURL.
When the assign(url)
method is invoked, the user agent must run the following steps:
-
Parse url, relative to the API base URL specified by the entry settings object and let parsedURL be the resulting URL string.
If this is not successful, throw a "
SyntaxError
"DOMException
and abort these steps. Location
-object navigate to parsedURL.
When the replace(url)
method is invoked, the user agent must run the following steps:
-
Parse url, relative to the API base URL specified by the entry settings object and let parsedURL be the resulting URL string.
If this is not successful, throw a "
SyntaxError
"DOMException
and abort these steps. Location
-object navigate to parsedURL with the replacement flag set.
When the reload()
method is invoked, the
user agent must run the appropriate steps from the following list:
- If the currently executing task is the dispatch of a
resize
event in response to the user resizing the browsing context - Repaint the browsing context and abort these steps.
- If the browsing context’s active document is an
iframe
srcdoc
document - Reprocess the
iframe
attributes of the browsing context’s browsing context container. - If the browsing context’s active document has its reload override flag set
- Perform an overridden reload, with the browsing context being navigated as the responsible browsing context.
- Otherwise
- Navigate the browsing context to the document’s URL with the exceptions enabled flag set and replacement enabled. The source browsing context must be the browsing context being navigated. This is a reload-triggered navigation. Rethrow any exceptions.
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 ancestorOrigins
attribute’s getter must run
these steps:
-
If this
Location
object’s relevantDocument
’s origin is not same origin-domain with the entry settings object’s origin, then throw a "SecurityError
"DOMException
. -
Otherwise, return this
Location
object’s ancestor origins array.
The Location
object requires additional logic beyond IDL for security purposes. The internal
slot and internal methods Location
objects must implement are defined below.
Every Location
object has a [[DefaultProperties]] internal slot representing its
own properties at time of its creation.
6.7. Browsing the Web
6.7.1. Navigating across documents
Certain actions cause the browsing context to navigate to a new resource. A user agent may provide various ways for the user to explicitly cause a browsing context to navigate, in addition to those defined in this specification.
For example, following a hyperlink, §4.10.22 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:
-
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 optionally with an exceptions enabled flag, and it is aborted on this step, then in addition to aborting this algorithm, the user agent must also throw a "
SecurityError
"DOMException
. - 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 immediately 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.
- Fragment identifiers: If this is not a reload-triggered navigation: apply the URL parser algorithm to the absolute URL of the new resource and the address of the active document of the browsing context being navigated; if all the components of the resulting parsed
URLs, ignoring any fragment components, are
identical, and the new resource is to be fetched using
GET
, and the URL record of the new resource has a fragment component that is not null (even if it is empty), then navigate to that fragment identifier and abort these steps. - 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 initialized a new
Document
object, abort thatDocument
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:
- If the resource has already been obtained (e.g., because it is being used to populate an
object
element’s new child browsing context) - Skip this step. The data is already available.
- If the new resource is a URL whose scheme is
javascript
-
Queue a task to run these "
javascript:
URL" steps, associated with the active document of the browsing context being navigated:-
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 let result be undefined, and jump to the step labeled process results below.
-
Let urlRecord be the result of running the URL parser on the URL of the new resource.
-
Let script source be the empty string.
-
Append the first string of urlRecord’s path component to script source.
-
If urlRecord’s query component is not null, then first append a U+003F QUESTION MARK character (?) to script source, and then append urlRecord’s query component to script source.
-
If urlRecord’s fragment component is not null, then first append a U+0023 NUMBER SIGN character (#) to script source, and then append urlRecord’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.
-
Let settings be the relevant settings object of the browsing context being navigated.
-
Let script be the result of creating a classic script given script source and settings.
-
Let result be the result of running the classic script script. If evaluation was unsuccessful, let result be undefined instead. (The result will also be undefined if scripting is disabled.)
-
Process results: If Type(result) is not
String
, then the result of obtaining the resource for the URL is a response whose status is204
.Otherwise, the result of obtaining the resource for the URL is a response whose header list consists of
Content-Type
/text/html
and whose body is result, and whose HTTPS state is settings’s HTTPS state.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 ajavascript:
URL in anhref
attribute of ana
element would only be evaluated when the link was followed, while such a URL in thesrc
attribute of aniframe
element would be evaluated in the context of theiframe
’s own nested browsing context when theiframe
is being set up; once evaluated, its return value (if it was not void) would replace that browsing context’sDocument
, thus also changing theWindow
object of that browsing context. -
- Otherwise
-
- Let request be the new resource.
- If request is a URL, set request to a new request whose URL is request.
- Set request’s client to the source browsing context’s active document’s
Window
object’s environment settings object, target browsing context to the browsing context being navigated, destination to "document
", mode to "navigate
", credentials mode to "include
", use-URL-credentials flag, and redirect mode to "manual
". - Set request’s omit-
Origin
-header flag. - If request’s method is not
GET
, or, if the navigation algorithm was invoked as a result of the form submission algorithm, then if there is an origin of the active document of the source browsing context, unset request’s omit-Origin
-header flag. - Otherwise, if the browsing context being navigated is a child
browsing context, and the browsing context container of the browsing context being navigated has a browsing context scope
origin, set request’s origin to that browsing context scope origin and unset request’s omit-
Origin
-header flag. - Fetch request.
- If the resource has already been obtained (e.g., because it is being used to populate an
-
If gone async is false, return to whatever algorithm invoked the navigation steps and continue running these steps in parallel.
- 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.
-
Handle redirects: If fetching the resource results in a redirect, and either the URL of the target of the redirect has the same origin as the original resource, or the resource is being obtained using the POST method or a safe method (in HTTP terms), return to the step labeled fragment identifiers with the new resource, except that if the URL of the target of the redirect does not have a fragment identifier and the URL of the resource that led to the redirect does, then the fragment identifier of the resource that led to the redirect must be propagated to the URL of the target of the redirect.
So for instance, if the original URL was "
https://example.com/#!sample
" and "https://example.com/
" is found to redirect to "https://example.com/
", the URL of the new resource will be "https://example.com/#!sample
".Otherwise, if fetching the resource results in a redirect but the URL of the target of the redirect does not have the same origin as the original resource and the resource is being obtained using a method that is neither the POST method nor a safe method (in HTTP terms), then abort these steps. The user agent may indicate to the user that the navigation has been aborted for security reasons.
-
Resource handling: If the resource’s out-of-band metadata (e.g., HTTP headers), not counting any type information (such as the Content-Type HTTP header), requires some sort of processing that will not affect the browsing context, then perform that processing and abort these steps.
Such processing might be triggered by, amongst other things, the following:- HTTP status codes (e.g., 204 No Content or 205 Reset Content)
- Network errors (e.g., the network interface being unavailable)
- Cryptographic protocol failures (e.g., an incorrect TLS certificate)
Responses with HTTP
Content-Disposition
headers specifying theattachment
disposition type must be handled as a download.HTTP 401 responses that do not include a challenge recognized 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 recognized 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 computed 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:
- an HTML MIME type
- Follow the steps given in the HTML document section, and then, once they have completed, abort this navigate algorithm.
- an XML MIME type that is not an explicitly supported XML type
- Follow the steps given in the XML document section. If that section determines that the content is not to be displayed as a generic XML document, then proceed to the next step in this overall set of steps. Otherwise, once the steps given in the XML document section have completed, abort this navigate algorithm.
- a JavaScript MIME type
- a JSON MIME type that is not an explicitly supported JSON type
- "
text/css
" - "
text/plain
" - "
text/vtt
" - Follow the steps given in the plain text file section, and then, once they have completed, abort this navigate algorithm.
- "
multipart/x-mixed-replace
" - Follow the steps given in the §12.2 multipart/x-mixed-replace section, and then, once they have completed, abort this navigate algorithm.
- A supported image, video, or audio type
- Follow the steps given in the media section, and then, once they have completed, abort this navigate algorithm.
- A type that will use an external application to render the content in the browsing context
- Follow the steps given in the plugin section, and then, once they have completed, abort this navigate algorithm.
An explicitly supported XML type is one for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in the browsing context, or a separate application), or one for which the user agent has dedicated processing rules (e.g., a Web browser with a built-in Atom feed viewer would be said to explicitly support the
application/atom+xml
MIME type), or one for which the user agent has a dedicated handler (e.g., one registered usingregisterContentHandler()
).The term JSON MIME type is used to refer to the MIME types
application/json
,text/json
, and any MIME type whose subtype ends with the five characters "+json
".An explicitly supported JSON 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, 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. However, if there is an override URL, then anyDocument
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.Initializing a new
Document
object: when aDocument
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:-
If browsingContext’s only entry in its session history is the about:blank
Document
that was added when browsingContext was created, and navigation is occurring with replacement enabled, and thatDocument
has the same origin as the newDocument
, then -
Otherwise,
-
Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:
-
For the global object, create a new
Window
object window. -
For the global this value, use browsingContext’s
WindowProxy
object. -
Let realm execution context be the created JavaScript execution context.
-
Do not obtain any source texts for scripts.
-
-
Set up a browsing context environment settings object with realm execution context, and let settings object be the result.
-
Set window’s associated
Document
to the newDocument
.
-
-
Set browsingContext’s
WindowProxy
object’s [[Window]] internal slot value to window. -
Set the
Document
's HTTPS state to the HTTPS state of the resource used to generate the document. -
Execute the Initialize a
Document
’s CSP list algorithm on theDocument
object and the resource used to generate the document. [CSP3] -
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 aniframe
element, or it does not have theallowfullscreen
attribute specified, or itsDocument
does not have the fullscreen enabled flag set, then also skip this step.Otherwise, set the
Document
's fullscreen enabled flag. -
Non-document content: If, given type, the new resource is to be handled by displaying some sort of inline content, e.g., a native rendering of the content, an error message because the specified type is not supported, or an inline prompt to allow the user to select a registered handler for the given type, then display the inline content, and then 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.
- 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.)
-
- If the navigation was initiated for entry update of an entry
-
- Replace the
Document
of the entry being updated, and any other entries that referenced the same document as that entry, with the newDocument
. - 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.) - Replace the
- Otherwise
-
-
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 itsDocument
object, related state, and the default scroll restoration mode of "auto
". - 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 optimize 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.
6.7.2. Page load processing model for HTML files
When an HTML document is to be loaded in a browsing context, the user agent must queue a task to create a Document
object, mark it as being an HTML document, set its content type to "text/html
",
initialize 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 fetching 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 "computed 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.
The task source for the two tasks mentioned in this section must be the networking task source.
6.7.3. Page load processing model for XML files
When faced with displaying an XML file inline, user agents must follow the requirements defined
in the XML and Namespaces in XML recommendations, RFC 7303, DOM, and other relevant specifications
to create a Document
object and a corresponding XML parser. [XML] [XML-NAMES] [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 initialize 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.
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
.
6.7.4. Page load processing model for text files
When a plain text document is to be loaded in a browsing context, the user agent
must queue a task to create a Document
object, mark it as being an HTML document, set its content type to the computed MIME type of the
resource (type in the navigate algorithm), initialize 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 §8.2.4.7 PLAINTEXT state. Each task that
the networking task source places on the task queue while fetching 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 by the specifications for the computed MIME type of the resource (type in the navigate algorithm).
The document’s character encoding must be set to the character encoding used to decode the 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.,
to link to a style sheet, provide a script, give the document a title
, etc.
In particular, if the user agent supports the Format=Flowed
feature of RFC3676 then the user agent would need to apply extra styling to cause the text to
wrap correctly and to handle the quoting feature. [RFC3676]
The task source for the two tasks mentioned in this section must be the networking task source.
6.7.5. Page load processing model for multipart/x-mixed-replace
resources
When a resource with the type multipart/x-mixed-replace
is to be loaded in a browsing context, the user agent must parse the resource using the rules for
multipart types. [RFC2046]
For each body part obtained from the resource, the user agent must run a new instance of the navigate algorithm, starting from the resource handling step, using the new
body part as the resource being navigated, with replacement enabled if a previous
body part from the same resource resulted in a Document
object being created and initialized, 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.
6.7.6. Page load processing model for media
When an image, video, or audio resource is to be loaded in a browsing context, the
user agent should create a Document
object, mark it as being an HTML document, set its content
type to the computed MIME type of the resource (type in the navigate algorithm), initialize 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.
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, provide a script, give the document a title
, make the media autoplay, etc.
6.7.7. Page load processing model for content that uses plugins
When a resource that requires an external resource to be rendered is to be loaded in a browsing context, the user agent should create a Document
object, mark
it as being an HTML document and mark it as being a plugin document, set its content
type to the computed MIME type of the resource (type in the navigate algorithm), initialize 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 Content Security Policy as part of the mechanism that ensures iframe
s
can’t be used to evade plugin-types
directives. [CSP3]
Then, the user agent must act as if it had stopped parsing.
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,
to give the document a title
, etc.
If the Document
's active sandboxing
flag set has its sandboxed plugins browsing context flag set, the synthesized embed
element will fail to render the content if
the relevant plugin cannot be secured.
6.7.8. Page load processing model for inline content that doesn’t have a DOM
When the user agent is to display a user agent page inline in a browsing context,
the user agent should create a Document
object, mark it as being an HTML document, set its content type to "text/html
",
initialize 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.
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.
6.7.9. Navigating to a fragment identifier
When a user agent is supposed to navigate to a fragment identifier, then the user agent must run the following steps:
-
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 itsDocument
object, related state, and current history scroll restoration preference. 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. [CSSOM-VIEW] - Use the scroll an element into view algorithm to scroll target into view, with the align to top flag set. [CSSOM-VIEW]
- Run the focusing steps for that element, with the
Document
's viewport as the fallback target. - 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 URL record.
- 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 running UTF-8 decode without BOM or fail on fragid bytes. If decoded fragid is failure, 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 aname
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. [CSS3-SELECTORS]
The task source for the task mentioned in this section must be the DOM manipulation task source.
6.7.10. History traversal
When a user agent is required to traverse the history to a specified entry, optionally with replacement enabled, and optionally with the non-blocking events flag set, the user agent must act as follows.
This algorithm is not just invoked when explicitly going back or forwards in the session history — it is also invoked in other situations, for example when navigating a browsing context, as part of updating the session history with the new page.
-
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 aDocument
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 using 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()
orreplaceState()
methods, then set its title to the value returned by thedocument.title
IDL attribute. - If appropriate, update the current entry in the browsing
context’s
Document
object’sHistory
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 theDocument
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.
- The current browsing context name must be stored with all the entries in
the history that are associated with
- 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. [PAGE-VISIBILITY]
- Fire a trusted event with the name
pageshow
at theWindow
object of thatDocument
, with target override set to theDocument
object, using thePageTransitionEvent
interface, with thepersisted
attribute initialized to true. This event must not bubble, must not be cancelable, and has no default action.
- If the
- Remove any tasks queued by the history traversal
task source that are associated with any
- 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 restore persisted user state and update aspects of the document and its rendering.
- Let targetRealm be the current Realm Record.
- If the entry is a state object entry, let state be StructuredClone(that state object, targetRealm) 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 theWindow
object of theDocument
, using thePopStateEvent
interface, with thestate
attribute initialized 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’sWindow
object, using theHashChangeEvent
interface, with theoldURL
attribute initialized to old URL and thenewURL
attribute initialized to new URL. This event must bubble but not be cancelable and has no default action.
- If state changed is true, fire a trusted event with the name
- The current entry is now the specified entry.
The task source for the tasks mentioned above is the DOM manipulation task source.
6.7.10.1. Persisted user state restoration
When the user agent is to restore persisted user state from a history entry, it must run the following steps immediately:
- If the entry has a scroll restoration mode, let scrollRestoration be that. Otherwise let scrollRestoration be "
auto
" - If scrollRestoration is "
manual
" the user agent should not restore the scroll position for the document, otherwise, it may do so. - Optionally, update other aspects of the document and its rendering, for instance values of form fields, that the user agent 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.
6.7.10.2. The PopStateEvent
interface
[Constructor(DOMString type, optional PopStateEventInit eventInitDict), Exposed=(Window,Worker)] interface PopStateEvent : Event { readonly attribute any state; };
dictionary PopStateEventInit : EventInit { any state; };
- event .
state
-
Returns a copy of the information that was provided to
pushState()
orreplaceState()
.
The state
attribute must return the
value it was initialized to. When the object is created, this attribute must be initialized to
null. It represents the context information for the event, or null, if the state represented is
the initial state of the Document
.
6.7.10.3. The HashChangeEvent
interface
[Constructor(DOMString type, optional HashChangeEventInit eventInitDict), Exposed=(Window,Worker)] interface HashChangeEvent : Event { readonly attribute DOMString oldURL; readonly attribute DOMString newURL; };
dictionary HashChangeEventInit : EventInit { DOMString oldURL; DOMString newURL; };
- event .
oldURL
-
Returns the URL of the session history entry that was previously current.
- event .
newURL
-
Returns the URL of the session history entry that is now current.
The oldURL
attribute must return the
value it was initialized to. When the object is created, this attribute must be initialized 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 initialized to. When the object is created, this attribute must be initialized to
null. It represents context information for the event, specifically the URL of the session
history entry that was traversed to.
6.7.10.4. The PageTransitionEvent
interface
[Constructor(DOMString type, optional PageTransitionEventInit eventInitDict), Exposed=(Window,Worker)] interface PageTransitionEvent : Event { readonly attribute boolean persisted; };
dictionary PageTransitionEventInit : EventInit { boolean persisted; };
- event .
persisted
-
For the
pageshow
event, returns false if the page is newly being loaded (and theload
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()
- Listening for
beforeunload
events - Listening for
unload
events - Having
iframe
s that are not salvageable - Active
WebSocket
objects - Aborting a
Document
The persisted
attribute must
return the value it was initialized to. When the object is created, this attribute must be
initialized to false. It represents the context information for the event.
6.7.11. Unloading documents
A Document
has a salvageable state, which must initially be
true, a fired unload flag, which must initially be false, and a page showing flag, which must initially be false. The page showing flag is used to ensure that
scripts receive pageshow
and pagehide
events in a consistent manner (e.g., that they never
receive two pagehide
events in a row without an intervening pageshow
, or vice versa).
Event loops have a termination nesting level counter, which must initially be zero.
When a user agent is to prompt to unload a document, it must run the following steps.
- 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 namebeforeunload
, which does not bubble but is cancelable. - Dispatch: Dispatch event at the
Document
'sWindow
object. - Decrease the event loop’s termination nesting level by one.
- If any event listeners were triggered by the earlier dispatch step, then set the
Document
's salvageable state to false. -
If the
Document
's active sandboxing flag set does not have its sandboxed modals flag set, and thereturnValue
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 thepagehide
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 theWindow
object of theDocument
, with target override set to theDocument
object, using thePageTransitionEvent
interface, with thepersisted
attribute initialized to true if theDocument
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. [PAGE-VISIBILITY]
- Unload event: If the
Document
's fired unload flag is false, fire a simple event namedunload
at theDocument
'sWindow
object, with target override set to theDocument
object. - Decrease the event loop’s termination nesting level by one.
- If any event listeners were triggered by the earlier unload event step, then set
the
Document
object’s salvageable state to false and set theDocument
'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 theDocument
's browsing context must discard theDocument
. - 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 theWebSocket()
constructor from theDocument
'sWindow
object.If this affected any
WebSocket
objects, then setDocument
's salvageable state to false. - If the
Document
's salvageable state is false, forcibly close anyEventSource
objects that whose constructor was invoked from theDocument
'sWindow
object. - If the
Document
's salvageable state is false, empty theDocument
'sWindow
’s list of active timers.
6.7.11.1. The BeforeUnloadEvent
interface
interface BeforeUnloadEvent : Event { attribute DOMString returnValue; };
- event .
returnValue
[ = value ] -
Returns the current return value of the event (the message to show the user).
Can be set, to update the message.
There are no BeforeUnloadEvent
-specific initialization 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.
6.7.12. Aborting a document load
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 thisDocument
'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 theDocument
's salvageable state to false. - If the
Document
has an active parser, then abort that parser and set theDocument
'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.
6.7.13. Browser state
[NoInterfaceObject, Exposed=(Window, Worker)] interface NavigatorOnLine { readonly attribute boolean onLine; };
- window .
navigator
.onLine
-
Returns false if the user agent is definitely offline (disconnected from the network). Returns true if the user agent might be online.
The events
online
andoffline
are fired when the value of this attribute changes.
The navigator.onLine
attribute must return
false if the user agent will not contact the network when the user follows links or when a script
requests a remote page (or knows that such an attempt would fail), and must return true
otherwise.
When the value that would be returned by the navigator.onLine
attribute of a Window
or WorkerGlobalScope
changes from true to false, the user agent must queue a
task to fire a simple event named offline
at the Window
or WorkerGlobalScope
object.
On the other hand, when the value that would be returned by the navigator.onLine
attribute of a Window
or WorkerGlobalScope
changes from false to true, the user agent must queue a
task to fire a simple event named online
at
the Window
or WorkerGlobalScope
object.
The task source for these tasks is the networking task source.
This attribute is inherently unreliable. A computer can be connected to a network without having Internet access.
<!DOCTYPE HTML> <html> <head> <title>Online status</title> <script> function updateIndicator() { document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline'; } </script> </head> <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()"> <p>The network is: <span>(state unknown)</span> </body> </html>