Living Standard — Last Updated 11 August 2026
Window,
WindowProxy, and Location objectsWindow objectWindowProxy exotic objectLocation interfaceHistory interfaceNavigation interfaceNavigationHistoryEntry interfaceNavigationActivation interfacenavigate eventNotRestoredReasons interfaceWindow,
WindowProxy, and Location objectsAlthough 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.
This section uses the terminology and typographic conventions from the JavaScript specification. [JAVASCRIPT]
When perform a security check is invoked, with a platformObject, identifier, and type, run these steps:
If platformObject is not a Window or Location object,
then return.
For each e of CrossOriginProperties(platformObject):
If SameValue(e.[[Property]], identifier) is true:
If type is "method" and e has neither
[[NeedsGetter]] nor [[NeedsSetter]], then return.
Otherwise, if type is "getter" and
e.[[NeedsGetter]] is true, then return.
Otherwise, if type is "setter" and
e.[[NeedsSetter]] is true, then return.
If IsPlatformObjectSameOrigin(platformObject) is false, then
throw a "SecurityError" DOMException.
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 (currentGlobal, objectGlobal,
propertyKey)-tuples and values are property descriptors, as a memoization of what is
visible to scripts when currentGlobal inspects a Window or
Location object from objectGlobal. 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.
For example, with 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.
For example, setting 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.
If O is a Location object, then return «
{ [[Property]]: "href", [[NeedsGetter]]: false, [[NeedsSetter]]: true },
{ [[Property]]: "replace" } ».
Return «
{ [[Property]]: "window", [[NeedsGetter]]: true, [[NeedsSetter]]: false },
{ [[Property]]: "self", [[NeedsGetter]]: true, [[NeedsSetter]]: false },
{ [[Property]]: "location", [[NeedsGetter]]: true, [[NeedsSetter]]: true },
{ [[Property]]: "close" },
{ [[Property]]: "closed", [[NeedsGetter]]: true, [[NeedsSetter]]: false },
{ [[Property]]: "focus" },
{ [[Property]]: "blur" },
{ [[Property]]: "frames", [[NeedsGetter]]: true, [[NeedsSetter]]: false },
{ [[Property]]: "length", [[NeedsGetter]]: true, [[NeedsSetter]]: false },
{ [[Property]]: "top", [[NeedsGetter]]: true, [[NeedsSetter]]: false },
{ [[Property]]: "opener", [[NeedsGetter]]: true, [[NeedsSetter]]: false },
{ [[Property]]: "parent", [[NeedsGetter]]: true, [[NeedsSetter]]: false },
{ [[Property]]: "postMessage" } ».
This abstract operation does not return a Completion Record.
Indexed properties do not need to be safelisted in this algorithm, as they are
handled directly by the WindowProxy object.
A JavaScript property name P is a cross-origin accessible window property
name if it is "window", "self", "location", "close", "closed",
"focus", "blur", "frames",
"length", "top", "opener",
"parent", "postMessage", or an array index
property name.
If P is "then", %Symbol.toStringTag%,
%Symbol.hasInstance%, or %Symbol.isConcatSpreadable%, then return
PropertyDescriptor {
[[Value]]: undefined,
[[Writable]]: false,
[[Enumerable]]: false,
[[Configurable]]: true }.
Throw a "SecurityError" DOMException.
Return true if the current settings object's origin is same origin-domain with O's relevant settings object's origin, and false otherwise.
This abstract operation does not return a Completion Record.
Here the current settings object roughly corresponds to the "caller",
because this check occurs before the execution
context for the getter/setter/method in question makes its way onto the JavaScript
execution context stack. For example, in the code w.document, this
step is invoked before the document getter is reached as part
of the [[Get]] algorithm for the WindowProxy
w.
If this abstract operation returns undefined and there is no custom behavior, the
caller needs to throw a "SecurityError" DOMException. In
practice this is handled by the caller calling CrossOriginPropertyFallback.
Let crossOriginKey be a tuple consisting of the current settings object, O's relevant settings object, and P.
For each e of CrossOriginProperties(O):
If SameValue(e.[[Property]], P) is true:
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 undefined.
If e.[[NeedsGetter]] and e.[[NeedsSetter]] are absent:
Let value be originalDesc.[[Value]].
If IsCallable(value) is true, then set value to an anonymous built-in function, created in the current realm, that performs the same steps as the IDL operation P on object O.
Set crossOriginDesc to PropertyDescriptor { [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.
Otherwise:
Let crossOriginGetter be undefined.
If e.[[NeedsGetter]] is true, then set crossOriginGetter to an anonymous built-in function, created in the current realm, that performs the same steps as the getter of the IDL attribute P on object O.
Let crossOriginSetter be undefined.
If e.[[NeedsSetter]] is true, then set crossOriginSetter to an anonymous built-in function, created in the current realm, that performs the same steps as the setter of the IDL attribute P on object O.
Set crossOriginDesc to PropertyDescriptor { [[Getter]]: crossOriginGetter, [[Setter]]: crossOriginSetter, [[Enumerable]]: false, [[Configurable]]: true }.
Create an entry in the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O with key crossOriginKey and value crossOriginDesc.
Return crossOriginDesc.
Return undefined.
This abstract operation does not return a Completion Record.
The reason that the property descriptors produced here are configurable is to preserve the invariants of the essential internal methods required by the JavaScript specification. In particular, since the value of the property can change as a consequence of navigation, it is required that the property be configurable. (However, see tc39/ecma262 issue #672 and references to it elsewhere in this specification for cases where we are not able to preserve these invariants, for compatibility with existing web content.) [JAVASCRIPT]
The reason the property descriptors are non-enumerable, despite this mismatching the same-origin behavior, is for compatibility with existing web content. See issue #3183 for details.
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.[[Getter]].
If getter is undefined, then throw a "SecurityError"
DOMException.
Return ? Call(getter, Receiver).
Let desc be ? O.[[GetOwnProperty]](P).
Assert: desc is not undefined.
If desc.[[Setter]] is present and its value is not undefined:
Perform ? Call(desc.[[Setter]], Receiver, « V »).
Return true.
Throw a "SecurityError" DOMException.
Let keys be a new empty List.
For each e of CrossOriginProperties(O), append e.[[Property]] to keys.
Return the concatenation of keys and « "then",
%Symbol.toStringTag%, %Symbol.hasInstance%, %Symbol.isConcatSpreadable%
».
This abstract operation does not return a Completion Record.
Window objectSupport in all current engines.
[Global =Window ,
Exposed =Window ,
LegacyUnenumerableNamedProperties ]
interface Window : EventTarget {
// the current browsing context
[LegacyUnforgeable ] readonly attribute WindowProxy window ;
[Replaceable ] readonly attribute WindowProxy self ;
[LegacyUnforgeable ] readonly attribute Document document ;
attribute DOMString name ;
[PutForwards =href , LegacyUnforgeable ] readonly attribute Location location ;
readonly attribute History history ;
[Replaceable ] readonly attribute Navigation navigation ;
readonly attribute CustomElementRegistry customElements ;
[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 ;
undefined close ();
readonly attribute boolean closed ;
undefined stop ();
undefined focus ();
undefined blur ();
// other browsing contexts
[Replaceable ] readonly attribute WindowProxy frames ;
[Replaceable ] readonly attribute unsigned long length ;
[LegacyUnforgeable ] readonly attribute WindowProxy ? top ;
attribute any opener ;
[Replaceable ] readonly attribute WindowProxy ? parent ;
readonly attribute Element ? frameElement ;
WindowProxy ? open (optional USVString url = "", optional DOMString target = "_blank", optional [LegacyNullToEmptyString ] DOMString features = "");
// Since this is the global object, the IDL named getter adds a NamedPropertiesObject exotic
// object on the prototype chain. Indeed, this does not make the global object an exotic object.
// Indexed access is taken care of by the WindowProxy exotic object.
getter object (DOMString name );
// the user agent
readonly attribute Navigator navigator ;
[Replaceable ] readonly attribute Navigator clientInformation ; // legacy alias of .navigator
readonly attribute boolean originAgentCluster ;
// user prompts
undefined alert ();
undefined alert (DOMString message );
boolean confirm (optional DOMString message = "");
DOMString ? prompt (optional DOMString message = "", optional DOMString default = "");
undefined print ();
undefined postMessage (any message , USVString targetOrigin , optional sequence <object > transfer = []);
undefined postMessage (any message , optional WindowPostMessageOptions options = {});
// also has obsolete members
};
Window includes GlobalEventHandlers ;
Window includes WindowEventHandlers ;
dictionary WindowPostMessageOptions : StructuredSerializeOptions {
USVString targetOrigin = "/";
};
window.windowSupport in all current engines.
window.framesSupport in all current engines.
window.selfSupport in all current engines.
These attributes all return window.
window.documentSupport in all current engines.
Returns the Document associated with window.
document.defaultViewSupport in all current engines.
Returns the Window associated with document, if there is one, or null otherwise.
The Window object has an associated
Document, which is a Document object. It is set when the
Window object is created, and only ever changed during navigation from the initial
about:blank Document.
A Window's browsing context is
its associated Document's browsing context. It is either null or a
browsing context.
A Window's navigable is
the navigable whose active document is the
Window's associated
Document's, or null if there is no such navigable.
The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
The document getter steps
are to return this's associated
Document.
The Document object associated with a Window object can
change in exactly one case: when the navigate algorithm creates a new Document object for the
first page loaded in a browsing context. In that specific case, the
Window object of the initial
about:blank page is reused and gets a new Document object.
The defaultView getter steps are:
If this's browsing context is null, then return null.
Return this's browsing context's
WindowProxy object.
Support in all current engines.
For historical reasons, Window objects must also have a writable, configurable,
non-enumerable property named HTMLDocument whose value is the
Document interface object.
window = window.open([ url [, target [, features ] ] ])Support in all current engines.
Opens a window to show url (defaults to "about:blank"), and returns
it. target (defaults to "_blank") gives the name of the new
window. If a window already exists with that name, it is reused. The features
argument can contain a set of comma-separated tokens:
noopener"noreferrer"These behave equivalently to the noopener and noreferrer link types on hyperlinks.
popup"Encourages user agents to provide a minimal web browser user interface for the new
window. (Impacts the visible getter on all
BarProp objects as well.)
globalThis. open( "https://email.example/message/CAOOOkFcWW97r8yg=SsWg7GgCmp4suVX9o85y8BvNRqMjuc5PXg" , undefined , "noopener,popup" );
window.name [ = value ]Support in all current engines.
Returns the name of the window.
Can be set, to change the name.
window.close()Support in all current engines.
Closes the window.
window.closedSupport in all current engines.
Returns true if the window has been closed, false otherwise.
window.stop()Support in all current engines.
Cancels the document load.
To get noopener for window open, given a Document
sourceDocument, an ordered map tokenizedFeatures, and a
URL record-or-null url, perform the following steps. They return a
boolean.
If url is not null and url's blob URL entry is not null:
Let blobOrigin be url's blob URL entry's environment's origin.
Let topLevelOrigin be sourceDocument's relevant settings object's top-level origin.
If blobOrigin is not same site with topLevelOrigin, then return true.
Let noopener be false.
If tokenizedFeatures["noopener"] exists, then set noopener to the result of parsing tokenizedFeatures["noopener"] as a boolean feature.
Return noopener.
The window open steps, given a string url, a string target, and a string features, are as follows:
If the event loop's termination nesting level is nonzero, then return null.
Let sourceDocument be the entry global object's associated Document.
Let urlRecord be null.
If url is not the empty string:
Set urlRecord to the result of encoding-parsing a URL given url, relative to sourceDocument.
If urlRecord is failure, then throw a "SyntaxError"
DOMException.
If target is the empty string, then set target to "_blank".
Let tokenizedFeatures be the result of tokenizing features.
Let noreferrer be false.
If tokenizedFeatures["noreferrer"] exists, then set noreferrer to the result of parsing tokenizedFeatures["noreferrer"] as a boolean feature.
Let noopener be the result of getting noopener for window open with sourceDocument, tokenizedFeatures, and urlRecord.
Remove tokenizedFeatures["noopener"] and tokenizedFeatures["noreferrer"].
Let referrerPolicy be the empty string.
If noreferrer is true, then set noopener to true and set
referrerPolicy to "no-referrer".
Let targetNavigable and windowType be the result of applying the rules for choosing a navigable given target, sourceDocument's node navigable, and noopener.
If there is a user agent that supports control-clicking a link to open it in
a new tab, and the user control-clicks on an element whose onclick handler uses the window.open() API to open a page in an iframe element,
the user agent could override the selection of the target browsing context to instead target a
new tab.
If targetNavigable is null, then return null.
If windowType is either "new and unrestricted" or "new with no opener":
Set targetNavigable's active browsing context's is popup to the result of checking if a popup window is requested, given tokenizedFeatures.
Set up browsing context features for targetNavigable's active browsing context given tokenizedFeatures. [CSSOMVIEW]
If urlRecord is null, then set urlRecord to a URL
record representing about:blank.
If urlRecord matches about:blank, then perform the
URL and history update steps given targetNavigable's active document and urlRecord.
This is necessary in case url is something like about:blank?foo. If url is just plain about:blank, this will do nothing.
Otherwise, navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
Otherwise:
If urlRecord is not null, then navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
If noopener is false, then set targetNavigable's active browsing context's opener browsing context to sourceDocument's browsing context.
If noopener is true or windowType is "new with no
opener", then return null.
Return targetNavigable's active
WindowProxy.
The open(url, target,
features) method steps are to run the window open steps with
url, target, and features.
The method provides a mechanism for navigating an existing browsing context or opening and navigating an auxiliary browsing context.
To tokenize the features argument:
Let tokenizedFeatures be a new ordered map.
Let position point at the first code point of features.
While position is not past the end of features:
Let name be the empty string.
Let value be the empty string.
Collect a sequence of code points that are feature separators from features given position. This skips past leading separators before the name.
Collect a sequence of code points that are not feature separators from features given position. Set name to the collected characters, converted to ASCII lowercase.
Set name to the result of normalizing the feature name name.
While position is not past the end of features and the code point at position in features is not U+003D (=):
If the code point at position in features is U+002C (,), or if it is not a feature separator, then break.
Advance position by 1.
This skips to the first U+003D (=) but does not skip past a U+002C (,) or a non-separator.
If the code point at position in features is a feature separator:
While position is not past the end of features and the code point at position in features is a feature separator:
If the code point at position in features is U+002C (,), then break.
Advance position by 1.
This skips to the first non-separator but does not skip past a U+002C (,).
Collect a sequence of code points that are not feature separators code points from features given position. Set value to the collected code points, converted to ASCII lowercase.
If name is not the empty string, then set tokenizedFeatures[name] to value.
Return tokenizedFeatures.
To check if a window feature is set, given tokenizedFeatures, featureName, and defaultValue:
If tokenizedFeatures[featureName] exists, then return the result of parsing tokenizedFeatures[featureName] as a boolean feature.
Return defaultValue.
To check if a popup window is requested, given tokenizedFeatures:
If tokenizedFeatures is empty, then return false.
If tokenizedFeatures["popup"] exists, then return the result of parsing
tokenizedFeatures["popup"] as a boolean
feature.
Let location be the result of checking if
a window feature is set, given tokenizedFeatures, "location", and false.
Let toolbar be the result of checking if
a window feature is set, given tokenizedFeatures, "toolbar", and false.
If location and toolbar are both false, then return true.
Let menubar be the result of checking if
a window feature is set, given tokenizedFeatures, "menubar", and false.
If menubar is false, then return true.
Let resizable be the result of checking if
a window feature is set, given tokenizedFeatures, "resizable", and true.
If resizable is false, then return true.
Let scrollbars be the result of checking
if a window feature is set, given tokenizedFeatures, "scrollbars", and false.
If scrollbars is false, then return true.
Let status be the result of checking if
a window feature is set, given tokenizedFeatures, "status", and false.
If status is false, then return true.
Return false.
A code point is a feature separator if it is ASCII whitespace, U+003D (=), or U+002C (,).
For legacy reasons, there are some aliases of some feature names. To normalize a feature name name, switch on name:
screenx"
left".
screeny"
top".
innerwidth"
width".
innerheight"
height".
To parse a boolean feature given a string value:
If value is the empty string, then return true.
If value is "yes", then return
true.
If value is "true", then return
true.
Let parsed be the result of parsing value as an integer.
If parsed is an error, then set it to 0.
Return false if parsed is 0, and true otherwise.
The name getter steps are:
Return this's navigable's target name.
The name setter steps are:
Set this's navigable's active session history entry's document state's navigable target name to the given value.
The name gets reset when the navigable is navigated to another origin.
The close() method steps
are:
If thisTraversable is not a top-level traversable, then return.
If thisTraversable's is closing is true, then return.
Let browsingContext be thisTraversable's active browsing context.
Let sourceSnapshotParams be the result of snapshotting source snapshot params given thisTraversable's active document.
If all the following are true:
thisTraversable is script-closable;
the incumbent global object's browsing context is familiar with browsingContext; and
the incumbent global object's navigable is allowed by sandboxing to navigate thisTraversable, given sourceSnapshotParams,
then:
Set thisTraversable's is closing to true.
Queue a task on the DOM manipulation task source to definitely close thisTraversable.
A navigable is script-closable if it is a top-level traversable, and any of the following are true:
The closed getter
steps are to return true if this's browsing context
is null or its is closing is true; otherwise false.
The stop() method steps
are:
Window objectwindow.lengthSupport in all current engines.
Returns the number of document-tree child navigables.
window[index]Returns the WindowProxy corresponding to the indicated document-tree child navigables.
The length getter steps are
to return this's associated
Document's document-tree child navigables's size.
Indexed access to document-tree child navigables is defined through
the [[GetOwnProperty]] internal method of the
WindowProxy object.
Window objectwindow[name]Returns the indicated element or collection of elements.
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to
this API can vary over time, as new features are added to the web platform, for example. Instead
of this, use document.getElementById() or document.querySelector().
The document-tree child
navigable target name property set of a Window object window is the
return value of running these steps:
Let children be the document-tree child navigables of
window's associated
Document.
Let firstNamedChildren be an empty ordered set.
For each navigable of children:
Let name be navigable's target name.
If name is the empty string, then continue.
If firstNamedChildren contains a navigable whose target name is name, then continue.
Append navigable to firstNamedChildren.
Let names be an empty ordered set.
For each navigable of firstNamedChildren:
Let name be navigable's target name.
If navigable's active document's origin is same origin with window's relevant settings object's origin, then append name to names.
Return names.
The two seperate iterations mean that in the following example, hosted on https://example.org/, assuming https://elsewhere.example/
sets window.name to "spices", evaluating
window.spices after everything has loaded will yield undefined:
< iframe src = https://elsewhere.example.com/ ></ iframe >
< iframe name = spices ></ iframe >
The Window object supports named
properties. The supported property names of a Window object
window at any moment consist of the following, in tree order according to
the element that contributed them, ignoring later duplicates:
window's document-tree child navigable target name property set;
the value of the name content attribute for all embed,
form, img, and object elements that
have a non-empty name content attribute and are in a document
tree with window's associated
Document as their root; and
the value of the id content attribute for all HTML
elements that have a non-empty id content attribute and are
in a document tree with window's associated Document as their
root.
To determine the value of a named property
name in a Window object window, the user agent must return the
value obtained using the following steps:
Let objects be the list of named objects of window with the name name.
There will be at least one such object, since the algorithm would otherwise not have been invoked by Web IDL.
If objects contains a navigable:
Let container be the first navigable container in
window's associated
Document's descendants whose
content navigable is in objects.
Return container's content navigable's active WindowProxy.
Otherwise, if objects has only one element, return that element.
Otherwise, return an HTMLCollection rooted at window's associated Document, whose filter matches
only named objects of window with
the name name. (By definition, these will all be elements.)
Named objects of Window object
window with the name name, for the purposes of the above algorithm, consist
of the following:
document-tree child navigables of window's associated Document whose target name is name;
embed, form, img, or
object elements that have a name content attribute whose
value is name and are in a document tree with window's associated Document as their
root; and
HTML elements that have an id content attribute
whose value is name and are in a document tree with window's
associated Document as their
root.
Since the Window interface has the [Global] extended attribute, its named properties follow the rules for
named properties objects rather than legacy platform objects.
window.topSupport in all current engines.
Returns the WindowProxy for the top-level traversable.
window.opener [ = value ]Support in all current engines.
Returns the WindowProxy for the opener browsing context.
Returns null if there isn't one or if it has been set to null.
Can be set to null.
window.parentSupport in all current engines.
Returns the WindowProxy for the parent
navigable.
window.frameElementSupport in all current engines.
Returns the navigable container element.
Returns null if there isn't one, and in cross-origin situations.
The top getter steps are:
Return this's navigable's top-level traversable's active
WindowProxy.
The opener getter steps
are:
Let current be this's browsing context.
If current is null, then return null.
If current's opener browsing context is null, then return null.
Return current's opener browsing context's
WindowProxy object.
The opener setter steps are:
If the given value is null and this's browsing context is non-null, then set this's browsing context's opener browsing context to null.
If the given value is non-null, then perform ?
DefinePropertyOrThrow(this, "opener", {
[[Value]]: the given value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true
}).
Setting window.opener to null clears the opener
browsing context reference. In practice, this prevents future scripts from accessing their
opener browsing context's Window object.
By default, scripts can access their opener browsing context's
Window object through the window.opener getter.
E.g., a script can set window.opener.location, causing the opener
browsing context to navigate.
The parent getter steps
are:
If navigable is null, then return null.
If navigable's parent is not null, then set navigable to navigable's parent.
Return navigable's active
WindowProxy.
The frameElement
getter steps are:
Let current be this's node navigable.
If current is null, then return null.
Let container be current's container.
If container is null, then return null.
If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.
Return container.
An example of when these properties can return null is as follows:
<!DOCTYPE html>
< iframe ></ iframe >
< script >
"use strict" ;
const element = document. querySelector( "iframe" );
const iframeWindow = element. contentWindow;
element. remove();
console. assert( iframeWindow. top === null );
console. assert( iframeWindow. parent === null );
console. assert( iframeWindow. frameElement === null );
</ script >
Here the browsing context corresponding to iframeWindow
was nulled out when element was
removed from the document.
For historical reasons, the Window interface had some properties that represented
the visibility of certain web browser interface elements.
For privacy and interoperability reasons, those properties now return values that
represent whether the Window's browsing context's
is popup property is true or false.
Each interface element is represented by a BarProp object:
Support in all current engines.
[Exposed =Window ]
interface BarProp {
readonly attribute boolean visible ;
};
window.locationbar.visibleSupport in all current engines.
window.menubar.visibleSupport in all current engines.
window.personalbar.visibleSupport in all current engines.
window.scrollbars.visibleSupport in all current engines.
window.statusbar.visibleSupport in all current engines.
window.toolbar.visibleSupport in all current engines.
Returns true if the Window is not a popup; otherwise, returns false.
Support in all current engines.
The visible getter
steps are:
Let browsingContext be this's relevant global object's browsing context.
If browsingContext is null, then return true.
Return the negation of browsingContext's top-level browsing context's is popup.
The following BarProp objects must exist for each Window object:
BarProp objectBarProp objectBarProp objectBarProp objectBarProp objectBarProp objectThe 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.
Window objectsTo set up a window environment settings object, given a URL creationURL, a JavaScript execution context execution context, null or an environment reservedEnvironment, a URL topLevelCreationURL, and an origin topLevelOrigin, run these steps:
Let realm be the value of execution context's Realm component.
Let window be realm's global object.
Let settings object be a new environment settings object whose algorithms are defined as follows:
Return execution context.
Return the module map of
window's associated
Document.
Return the current base URL of window's
associated Document.
Return the origin of window's
associated Document.
Let parentDocument be window's navigable's parent's active document.
If parentDocument's relevant settings object's has cross-site ancestor is true, then return true.
If parentDocument's origin
is not same site with window's associated Document's origin, then return true.
Return false.
Return the policy container of
window's associated
Document.
Return true if both of the following hold, and false otherwise:
realm's agent cluster's cross-origin-isolation mode is "concrete", and
window's associated
Document is allowed to use the "cross-origin-isolated" feature.
Return window's associated
Document's load timing info's navigation start
time.
If reservedEnvironment is non-null:
Set settings object's id to reservedEnvironment's id, target browsing context to reservedEnvironment's target browsing context, and active service worker to reservedEnvironment's active service worker.
Set reservedEnvironment's id to the empty string.
The identity of the reserved environment is considered to be fully transferred to the created environment settings object. The reserved environment is not searchable by the environment’s id from this point on.
Otherwise, set settings object's id to a new unique opaque string, settings object's target browsing context to null, and settings object's active service worker to null.
Set settings object's creation URL to creationURL, settings object's top-level creation URL to topLevelCreationURL, and settings object's top-level origin to topLevelOrigin.
Set realm's [[HostDefined]] field to settings object.
WindowProxy exotic objectA 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.
The WindowProxy exotic object must use the ordinary internal methods except where
it is explicitly specified otherwise below.
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.
Let W be the value of the [[Window]] internal slot of this.
If IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetPrototypeOf(W).
Return null.
Return ! SetImmutablePrototype(this, V).
Let W be the value of the [[Window]] internal slot of this.
If P is an array index property name:
Let index be ! ToUint32(P).
Let children be the document-tree child navigables of
W's associated
Document.
Let value be undefined.
If index is less than children's size:
Sort children in ascending order, with
navigableA being less than navigableB if navigableA's container was inserted into W's associated Document earlier than
navigableB's container was.
Set value to children[index]'s active WindowProxy.
If value is undefined:
If IsPlatformObjectSameOrigin(W) is true, then return undefined.
Throw a "SecurityError" DOMException.
Return PropertyDescriptor { [[Value]]: value, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: true }.
If IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetOwnProperty(W, P).
This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT]
Let property be CrossOriginGetOwnPropertyHelper(W, P).
If property is not undefined, then return property.
If property is undefined and P is in W's document-tree child navigable target name property set:
Let value be the active
WindowProxy of the named
object of W with the name P.
Return PropertyDescriptor { [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.
The reason the property descriptors are non-enumerable, despite this mismatching the same-origin behavior, is for compatibility with existing web content. See issue #3183 for details.
Return ? CrossOriginPropertyFallback(P).
Let W be the value of the [[Window]] internal slot of this.
If IsPlatformObjectSameOrigin(W) is true:
If P is an array index property name, return false.
Return ? OrdinaryDefineOwnProperty(W, P, Desc).
This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT]
Throw a "SecurityError" DOMException.
Let W be the value of the [[Window]] internal slot of this.
Check if an access between two browsing contexts should be reported, given the current global object's browsing context, W's browsing context, P, and the current settings object.
If IsPlatformObjectSameOrigin(W) is true, then return ? OrdinaryGet(this, P, Receiver).
Return ? CrossOriginGet(this, P, Receiver).
this is passed rather than W as OrdinaryGet and CrossOriginGet will invoke the [[GetOwnProperty]] internal method.
Let W be the value of the [[Window]] internal slot of this.
Check if an access between two browsing contexts should be reported, given the current global object's browsing context, W's browsing context, P, and the current settings object.
If IsPlatformObjectSameOrigin(W) is true:
If P is an array index property name, then return false.
Return ? OrdinarySet(W, P, V, Receiver).
Return ? CrossOriginSet(this, P, V, Receiver).
this is passed rather than W as CrossOriginSet will invoke the [[GetOwnProperty]] internal method.
Let W be the value of the [[Window]] internal slot of this.
If IsPlatformObjectSameOrigin(W) is true:
If P is an array index property name:
Let desc be ! this.[[GetOwnProperty]](P).
If desc is undefined, then return true.
Return false.
Return ? OrdinaryDelete(W, P).
Throw a "SecurityError" DOMException.
Let W be the value of the [[Window]] internal slot of this.
Let maxProperties be W's associated Document's document-tree
child navigables's size.
Let keys be the range 0 to maxProperties, exclusive.
If IsPlatformObjectSameOrigin(W) is true, then return the concatenation of keys and OrdinaryOwnPropertyKeys(W).
Return the concatenation of keys and ! CrossOriginOwnPropertyKeys(W).
Location interfaceSupport in all current engines.
Support in all current engines.
Support in all current engines.
Each Window object is associated with a unique instance of a Location
object, allocated when the Window object is created.
The Location exotic object is defined through a mishmash of IDL,
invocation of JavaScript internal methods post-creation, and overridden JavaScript internal
methods. Coupled with its scary security policy, please take extra care while implementing
this excrescence.
To create a Location object, run these steps:
Let location be a new Location platform
object.
Let valueOf be location's relevant realm.[[Intrinsics]].[[%Object.prototype.valueOf%]].
Perform ! location.[[DefineOwnProperty]]("valueOf", {
[[Value]]: valueOf,
[[Writable]]: false,
[[Enumerable]]: false,
[[Configurable]]: false }).
Perform ! location.[[DefineOwnProperty]](%Symbol.toPrimitive%, { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).
Set the value of the [[DefaultProperties]] internal slot of location to location.[[OwnPropertyKeys]]().
Return location.
The addition of valueOf and %Symbol.toPrimitive% own
data properties, as well as the fact that all of Location's IDL attributes are marked
[LegacyUnforgeable], is required by legacy code that consulted
the Location interface, or stringified it, to determine the document URL, and then used it in a security-sensitive way.
In particular, the valueOf, %Symbol.toPrimitive%, and [LegacyUnforgeable] stringifier mitigations ensure that code such as
foo[location] = bar or location + "" cannot be
misdirected.
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 Document object's location getter steps are to return
this's relevant global object's Location object, if
this is fully active, and null otherwise.
Location objects provide a representation of the URL of their associated Document, as well as
methods for navigating and reloading
the associated navigable.
[Exposed =Window ]
interface Location { // but see also additional creation steps and overridden internal methods
[LegacyUnforgeable ] stringifier attribute USVString href ;
[LegacyUnforgeable ] readonly attribute USVString origin ;
[LegacyUnforgeable ] attribute USVString protocol ;
[LegacyUnforgeable ] attribute USVString host ;
[LegacyUnforgeable ] attribute USVString hostname ;
[LegacyUnforgeable ] attribute USVString port ;
[LegacyUnforgeable ] attribute USVString pathname ;
[LegacyUnforgeable ] attribute USVString search ;
[LegacyUnforgeable ] attribute USVString hash ;
[LegacyUnforgeable ] undefined assign (USVString url );
[LegacyUnforgeable ] undefined replace (USVString url );
[LegacyUnforgeable ] undefined reload ();
[LegacyUnforgeable ] readonly attribute DOMStringList ancestorOrigins ;
};
location.toString()location.hrefSupport in all current engines.
Support in all current engines.
Returns the Location object's URL.
Can be set, to navigate to the given URL.
location.originSupport in all current engines.
Returns the Location object's URL's origin.
location.protocolSupport in all current engines.
Returns the Location object's URL's scheme.
Can be set, to navigate to the same URL with a changed scheme.
location.hostSupport in all current engines.
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.hostnameSupport in all current engines.
Returns the Location object's URL's host.
Can be set, to navigate to the same URL with a changed host.
location.portSupport in all current engines.
Returns the Location object's URL's port.
Can be set, to navigate to the same URL with a changed port.
location.pathnameSupport in all current engines.
Returns the Location object's URL's path.
Can be set, to navigate to the same URL with a changed path.
location.searchSupport in all current engines.
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.hashSupport in all current engines.
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.assign(url)Support in all current engines.
Navigates to the given URL.
location.replace(url)Support in all current engines.
Removes the current page from the session history and navigates to the given URL.
location.reload()Support in all current engines.
Reloads the current page.
location.ancestorOriginsReturns a DOMStringList object listing the origins of the ancestor navigables' active documents.
A Location object has an associated relevant Document,
which is its relevant global object's browsing context's active document, if this
Location object's relevant global object's browsing context is non-null, and null otherwise.
A Location object has an associated url,
which is this Location object's relevant Document's URL, if this Location object's relevant
Document is non-null, and about:blank otherwise.
To Location-object navigate a Location object
location to a URL url, optionally given a NavigationHistoryBehavior historyHandling
(default "auto"):
Let navigable be location's relevant global object's navigable.
Let sourceDocument be the incumbent
global object's associated
Document.
If location's relevant Document is not yet
completely loaded, and the incumbent global
object does not have transient activation, then set
historyHandling to "replace".
Navigate navigable to url using sourceDocument, with exceptionsEnabled set to true and historyHandling set to historyHandling.
The href getter
steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
Return this's url, serialized.
The href setter steps are:
If this's relevant Document is null, then
return.
Let url be the result of encoding-parsing a URL given the given value, relative to the entry settings object.
If url is failure, then throw a "SyntaxError"
DOMException.
Location-object navigate this to
url.
The href setter intentionally has no
security check.
The origin
getter steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
Return the serialization of this's url's origin.
The protocol
getter steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
The protocol setter steps are:
If this's relevant Document is null, then
return.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
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.
Because the URL parser ignores multiple consecutive colons, providing a value
of "https:" (or even "https::::") is the same as
providing a value of "https".
If possibleFailure is failure, then throw a
"SyntaxError" DOMException.
If copyURL's scheme is not an HTTP(S) scheme, then terminate these steps.
Location-object navigate this to
copyURL.
The host getter
steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
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 setter steps are:
If this's relevant Document is null, then
return.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
If copyURL has an opaque path, then return.
Basic URL parse the given value, with copyURL as url and host state as state override.
Location-object navigate this to
copyURL.
The hostname
getter steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
Return this's url's host, serialized.
The hostname setter steps are:
If this's relevant Document is null, then
return.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
If copyURL has an opaque path, then return.
Basic URL parse the given value, with copyURL as url and hostname state as state override.
Location-object navigate this to
copyURL.
The port getter
steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
Return this's url's port, serialized.
The port setter steps are:
If this's relevant Document is null, then
return.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
If copyURL cannot have a username/password/port, then return.
If the given value is the empty string, then set copyURL's port to null.
Otherwise, basic URL parse the given value, with copyURL as url and port state as state override.
Location-object navigate this to
copyURL.
The pathname
getter steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
Return the result of URL path serializing this
Location object's url.
The pathname setter steps are:
If this's relevant Document is null, then
return.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
If copyURL has an opaque path, then return.
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 navigate this to
copyURL.
The search
getter steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
If this's url's query is either null or the empty string, return the empty string.
The search setter steps are:
If this's relevant Document is null, then
return.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
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 null, the
relevant Document's document's character encoding,
copyURL as url, and query
state as state
override.
Location-object navigate this to
copyURL.
The hash getter
steps are:
If this's relevant Document is non-null and its
origin is not same origin-domain with
the entry settings object's origin, then throw a
"SecurityError" DOMException.
If this's url's fragment is either null or the empty string, return the empty string.
The hash setter steps are:
If this's relevant Document is null, then
return.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
Let thisURLFragment be copyURL's fragment if it is non-null; otherwise the empty string.
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.
If copyURL's fragment is thisURLFragment, then return.
This bailout is necessary for compatibility with deployed content, which redundantly sets location.hash on scroll. It does not apply to other
mechanisms of fragment navigation, such as the location.href setter or location.assign().
Location-object navigate this to
copyURL.
Unlike the equivalent API for the a and area elements,
the hash setter does not special case the empty string, to
remain compatible with deployed scripts.
The assign(url) method steps are:
If this's relevant Document is null, then
return.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
Let urlRecord be the result of encoding-parsing a URL given url, relative to the entry settings object.
If urlRecord is failure, then throw a "SyntaxError"
DOMException.
Location-object navigate this to
urlRecord.
The replace(url) method steps are:
If this's relevant Document is null, then
return.
Let urlRecord be the result of encoding-parsing a URL given url, relative to the entry settings object.
If urlRecord is failure, then throw a "SyntaxError"
DOMException.
Location-object navigate this to
urlRecord given "replace".
The replace() method intentionally has
no security check.
The reload() method
steps are:
Let document be this's relevant
Document.
If document is null, then return.
If document's origin is not
same origin-domain with the entry settings object's origin, then throw a
"SecurityError" DOMException.
Reload document's node navigable.
A Location object has an associated empty DOMStringList which is a
DOMStringList object whose associated list is an empty list.
This object cannot carry state across navigations because it is only returned when
there is no relevant Document, in which case it's not possible to
navigate, and it's not possible to return to a non-null relevant
Document.
The ancestorOrigins getter steps are:
If this's relevant Document is null, then return
this's empty
DOMStringList.
If this's relevant Document's origin is not same origin-domain with the
entry settings object's origin, then throw a
"SecurityError" DOMException.
Assert: this's relevant Document's ancestor origins list is not
null.
Otherwise, return this's relevant Document's ancestor origins list.
As explained earlier, the Location exotic object
requires additional logic beyond IDL for security purposes. The Location object must
use the ordinary internal methods except where it is explicitly specified otherwise below.
Also, every Location object has a [[DefaultProperties]] internal slot
representing its own properties at time of its creation.
If IsPlatformObjectSameOrigin(this) is true, then return ! OrdinaryGetPrototypeOf(this).
Return null.
Return ! SetImmutablePrototype(this, V).
If IsPlatformObjectSameOrigin(this) is true:
Let desc be OrdinaryGetOwnProperty(this, P).
If the value of the [[DefaultProperties]] internal slot of this contains P, then set desc.[[Configurable]] to true.
Return desc.
Let property be CrossOriginGetOwnPropertyHelper(this, P).
If property is not undefined, then return property.
Return ? CrossOriginPropertyFallback(P).
If IsPlatformObjectSameOrigin(this) is true:
If the value of the [[DefaultProperties]] internal slot of this contains P, then return false.
Return ? OrdinaryDefineOwnProperty(this, P, Desc).
Throw a "SecurityError" DOMException.
If IsPlatformObjectSameOrigin(this) is true, then return ? OrdinaryGet(this, P, Receiver).
Return ? CrossOriginGet(this, P, Receiver).
If IsPlatformObjectSameOrigin(this) is true, then return ? OrdinarySet(this, P, V, Receiver).
Return ? CrossOriginSet(this, P, V, Receiver).
If IsPlatformObjectSameOrigin(this) is true, then return ? OrdinaryDelete(this, P).
Throw a "SecurityError" DOMException.
If IsPlatformObjectSameOrigin(this) is true, then return OrdinaryOwnPropertyKeys(this).
Return CrossOriginOwnPropertyKeys(this).
History interfaceSupport in all current engines.
Support in all current engines.
enum ScrollRestoration { " auto " , " manual " };
[Exposed =Window ]
interface History {
readonly attribute unsigned long length ;
attribute ScrollRestoration scrollRestoration ;
readonly attribute any state ;
undefined go (optional long delta = 0);
undefined back ();
undefined forward ();
undefined pushState (any data , DOMString unused , optional USVString ? url = null );
undefined replaceState (any data , DOMString unused , optional USVString ? url = null );
};
history.lengthSupport in all current engines.
Returns the number of overall session history entries for the current traversable navigable.
history.scrollRestorationSupport in all current engines.
Returns the scroll restoration mode of the active session history entry.
history.scrollRestoration = valueSet the scroll restoration mode of the active session history entry to value.
history.stateSupport in all current engines.
Returns the classic history API state of the active session history entry, deserialized into a JavaScript value.
history.go()Reloads the current page.
history.go(delta)Support in all current engines.
Goes back or forward the specified number of steps in the overall session history entries list for the current traversable navigable.
A zero delta will reload the current page.
If the delta is out of range, does nothing.
history.back()Support in all current engines.
Goes back one step in the overall session history entries list for the current traversable navigable.
If there is no previous page, does nothing.
history.forward()Support in all current engines.
Goes forward one step in the overall session history entries list for the current traversable navigable.
If there is no next page, does nothing.
history.pushState(data, "")Support in all current engines.
Adds a new entry into session history with its classic history API state set to a serialization of data. The active history entry's URL will be copied over and used for the new entry's URL.
(The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.)
history.pushState(data, "", url)Adds a new entry into session history with its classic history API state set to a serialization of data, and with its URL set to url.
If the current Document cannot have
its URL rewritten to url, a "SecurityError"
DOMException will be thrown.
(The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.)
history.replaceState(data, "")Support in all current engines.
Updates the classic history API state of the active session history entry to a structured clone of data.
(The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.)
history.replaceState(data, "", url)Updates the classic history API state of the active session history entry to a structured clone of data, and its URL to url.
If the current Document cannot have
its URL rewritten to url, a "SecurityError"
DOMException will be thrown.
(The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.)
A Document has a history object, a
History object.
The history getter steps
are to return this's associated
Document's history object.
Each History object has state,
initially null.
Each History object has a length, a
non-negative integer, initially 0.
Each History object has an index, a
non-negative integer, initially 0.
Although the index is not directly exposed, it can be inferred from changes to the length during synchronous navigations. In fact, that is what it's used for.
The length getter
steps are:
If this's relevant global object's associated Document is not fully
active, then throw a "SecurityError"
DOMException.
The scrollRestoration getter steps are:
If this's relevant global object's associated Document is not fully
active, then throw a "SecurityError"
DOMException.
Return this's relevant global object's navigable's active session history entry's scroll restoration mode.
The scrollRestoration setter steps
are:
If this's relevant global object's associated Document is not fully
active, then throw a "SecurityError"
DOMException.
Set this's relevant global object's navigable's active session history entry's scroll restoration mode to the given value.
The state getter
steps are:
If this's relevant global object's associated Document is not fully
active, then throw a "SecurityError"
DOMException.
The go(delta)
method steps are to delta traverse this given delta.
The back() method steps
are to delta traverse this given −1.
The forward() method
steps are to delta traverse this given +1.
To delta traverse a History object history given an integer
delta:
Let document be history's relevant global object's
associated Document.
If document is not fully active, then throw a
"SecurityError" DOMException.
If history's relevant global object's navigable's allowed to perform a navigation or history update returns blocked, then return.
If delta is 0, then reload document's node navigable, and return.
Traverse the history by a delta given document's node navigable's traversable navigable, delta, and with sourceDocument set to document.
The pushState(data,
unused, url) method steps are to run the shared history
push/replace state steps given this, data, url, and
"push".
The replaceState(data, unused,
url) method steps are to run the shared history push/replace state
steps given this, data, url, and "replace".
The shared history push/replace state steps, given a History
history, a value data, a scalar value string-or-null
url, and a history handling behavior historyHandling, are:
Let document be history's relevant global object's
associated Document.
If document is not fully active, then throw a
"SecurityError" DOMException.
Let serializedData be StructuredSerializeForStorage(data). Rethrow any exceptions.
Let newURL be document's URL.
If url is not null or the empty string:
Set newURL to the result of encoding-parsing a URL given url, relative to the relevant settings object of history.
If newURL is failure, then throw a "SecurityError"
DOMException.
If document cannot have its URL
rewritten to newURL, then throw a "SecurityError"
DOMException.
The special case for the empty string here is historical, and leads to
different resulting URLs when comparing code such as location.href = ""
(which performs URL parsing on the empty string) versus history.pushState(null, "", "") (which bypasses it).
If history's relevant global object's navigable's allowed to perform a navigation or history update returns blocked, then return.
Let navigation be history's relevant global object's navigation API.
Let continue be the result of firing a push/replace/reload navigate event at
navigation with navigationType set to
historyHandling, isSameDocument set
to true, destinationURL set to
newURL, and classicHistoryAPIState set to
serializedData.
If continue is false, then return.
Run the URL and history update steps given document and newURL, with serializedData set to serializedData and historyHandling set to historyHandling.
User agents may limit the number of state objects added to the session history per page. If a
page hits the implementation-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 Document document can have its URL rewritten to a
URL targetURL if the following algorithm returns true:
Let documentURL be document's URL.
If targetURL and documentURL differ in their scheme, username, password, host, or port components, then return false.
If targetURL's scheme is an HTTP(S) scheme, then return true.
Differences in path, query, and fragment are allowed for http: and https: URLs.
If targetURL's scheme is "file":
If targetURL and documentURL differ in their path component, then return false.
Return true.
Differences in query and fragment are allowed for file:
URLs.
If targetURL and documentURL differ in their path component or query components, then return false.
Only differences in fragment are allowed for other types of URLs.
Return true.
| document's URL | targetURL | can have its URL rewritten |
|---|---|---|
https://example.com/home
| https://example.com/home#about
| ✅ |
https://example.com/home
| https://example.com/home?page=shop
| ✅ |
https://example.com/home
| https://example.com/shop
| ✅ |
https://example.com/home
| https://user:pass@example.com/home
| ❌ |
https://example.com/home
| http://example.com/home
| ❌ |
file:///path/to/x
| file:///path/to/x#hash
| ✅ |
file:///path/to/x
| file:///path/to/x?search
| ✅ |
file:///path/to/x
| file:///path/to/y
| ❌ |
about:blank
| about:blank#hash
| ✅ |
about:blank
| about:blank?search
| ❌ |
about:blank
| about:srcdoc
| ❌ |
data:text/html,foo
| data:text/html,foo#hash
| ✅ |
data:text/html,foo
| data:text/html,foo?search
| ❌ |
data:text/html,foo
| data:text/html,bar
| ❌ |
data:text/html,foo
| data:bar
| ❌ |
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43
| blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43#hash
| ✅ |
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43
| blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43?search
| ❌ |
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43
| blob:https://example.com/anything
| ❌ |
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43
| blob:path
| ❌ |
Note how only the URL of the Document
matters, and not its origin. They can mismatch in
cases like about:blank Documents with inherited origins, in sandboxed
iframes, or when the document.domain
setter has been used.
Consider a game where the user can navigate along a line, such that the user is always at some coordinate, and such that the user can bookmark the page corresponding to a particular coordinate, to return to it later.
A static page implementing the x=5 position in such a game could look like the following:
<!DOCTYPE HTML>
<!-- this is https://example.com/line?x=5 -->
< html lang = "en" >
< 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 -->
< html lang = "en" >
< title > Line Game - 5</ title >
< p > You are at coordinate < span id = "coord" > 5</ span > on the line.</ p >
< p >
< a href = "?x=6" onclick = "go(1); return false;" > Advance to 6</ a > or
< a href = "?x=4" onclick = "go(-1); return false;" > retreat to 4</ a > ?
</ p >
< script >
var currentPage = 5 ; // prefilled by server
function go( d) {
setupPage( currentPage + d);
history. pushState( currentPage, "" , '?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.
Most applications want to use the same scroll restoration mode value for all of
their history entries. To achieve this they can set the 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 >
This section is non-normative.
The navigation API, provided by the global navigation
property, provides a modern and web application-focused way of managing navigations and history entries. It is a successor to the classic location and history APIs.
One ability the API provides is inspecting session history entries. For example, the following will display the entries' URLs in an ordered list:
const ol = document. createElement( "ol" );
ol. start = 0 ; // so that the list items' ordinal values match up with the entry indices
for ( const entry of navigation. entries()) {
const li = document. createElement( "li" );
if ( entry. index < navigation. currentEntry. index) {
li. className = "backward" ;
} else if ( entry. index > navigation. currentEntry. index) {
li. className = "forward" ;
} else {
li. className = "current" ;
}
li. textContent = entry. url;
ol. append( li);
}
The navigation.entries() array contains NavigationHistoryEntry instances, which have other useful properties in addition to the url and index properties shown here. Note that the array only contains NavigationHistoryEntry objects that represent the current navigable, and thus its contents are not impacted by navigations inside navigable containers such as iframes, or by navigations of the parent navigable in cases where the navigation API is itself being used inside an iframe. Additionally, it only contains NavigationHistoryEntry objects representing same-origin session history entries, meaning that if the user has visited other origins before or after the current one, there will not be corresponding NavigationHistoryEntrys.
The navigation API can also be used to navigate, reload, or traverse through the history:
< button onclick = "navigation.reload()" > Reload</ button >
< input type = "url" id = "navigationURL" >
< button onclick = "navigation.navigate(navigationURL.value)" > Navigate</ button >
< button id = "backButton" onclick = "navigation.back()" > Back</ button >
< button id = "forwardButton" onclick = "navigation.forward()" > Forward</ button >
< select id = "traversalDestinations" ></ select >
< button id = "goButton" onclick = "navigation.traverseTo(traversalDestinations.value)" > Traverse To</ button >
< script >
backButton. disabled = ! navigation. canGoBack;
forwardButton. disabled = ! navigation. canGoForward;
for ( const entry of navigation. entries()) {
traversalDestinations. append( new Option( entry. url, entry. key));
}
</ script >
Note that traversals are again limited to same-origin destinations, meaning that, for example, navigation.canGoBack will be false if the previous session history entry is for a page from another origin.
The most powerful part of the navigation API is the navigate event, which fires whenever almost any navigation or traversal occurs in the current navigable:
navigation. onnavigate = event => {
console. log( event. navigationType); // "push", "replace", "reload", or "traverse"
console. log( event. destination. url);
console. log( event. userInitiated);
// ... and other useful properties
};
(The event will not fire for location bar-initiated navigations, or navigations initiated from other windows, when the destination of the navigation is a new document.)
Much of the time, the event's cancelable property will be true, meaning this event can be canceled using preventDefault():
navigation. onnavigate = event => {
if ( event. cancelable && isDisallowedURL( event. destination. url)) {
alert( `Please don't go to ${ event. destination. url} !` );
event. preventDefault();
}
};
The cancelable property will be false for some "traverse" navigations, such as those taking place inside child navigables, those crossing to new origins, or when the user attempts to traverse again shortly after a previous call to preventDefault() prevented them from doing so.
The NavigateEvent's intercept() method allows intercepting a navigation and converting it into a same-document navigation:
navigation. addEventListener( "navigate" , e => {
// Some navigations, e.g. cross-origin navigations, we cannot intercept.
// Let the browser handle those normally.
if ( ! e. canIntercept) {
return ;
}
// Similarly, don't intercept fragment navigations or downloads.
if ( e. hashChange || e. downloadRequest !== null ) {
return ;
}
const url = new URL( event. destination. url);
if ( url. pathname. startsWith( "/articles/" )) {
e. intercept({
async handler() {
// The URL has already changed, so show a placeholder while
// fetching the new content, such as a spinner or loading page.
renderArticlePagePlaceholder();
// Fetch the new content and display when ready.
const articleContent = await getArticleContent( url. pathname, { signal: e. signal });
renderArticlePage( articleContent);
}
});
}
});
Note that the handler function can return a promise to represent the asynchronous progress, and success or failure, of the navigation. While the promise is still pending, browser UI can treat the navigation as ongoing (e.g., by presenting a loading spinner). Other parts of the navigation API are also sensitive to these promises, such as the return value of navigation.navigate():
const { committed, finished } = await navigation. navigate( "/articles/the-navigation-api-is-cool" );
// The committed promise will fulfill once the URL has changed, which happens
// immediately (as long as the NavigateEvent wasn't canceled).
await committed;
// The finished promise will fulfill once the Promise returned by handler() has
// fulfilled, which happens once the article is downloaded and rendered. (Or,
// it will reject, if handler() fails along the way).
await finished;
Navigation interface[Exposed =Window ]
interface Navigation : EventTarget {
sequence <NavigationHistoryEntry > entries ();
readonly attribute NavigationHistoryEntry ? currentEntry ;
undefined updateCurrentEntry (NavigationUpdateCurrentEntryOptions options );
readonly attribute NavigationTransition ? transition ;
readonly attribute NavigationActivation ? activation ;
readonly attribute boolean canGoBack ;
readonly attribute boolean canGoForward ;
NavigationResult navigate (USVString url , optional NavigationNavigateOptions options = {});
NavigationResult reload (optional NavigationReloadOptions options = {});
NavigationResult traverseTo (DOMString key , optional NavigationOptions options = {});
NavigationResult back (optional NavigationOptions options = {});
NavigationResult forward (optional NavigationOptions options = {});
attribute EventHandler onnavigate ;
attribute EventHandler onnavigatesuccess ;
attribute EventHandler onnavigateerror ;
attribute EventHandler oncurrententrychange ;
};
dictionary NavigationUpdateCurrentEntryOptions {
required any state ;
};
dictionary NavigationOptions {
any info ;
};
dictionary NavigationNavigateOptions : NavigationOptions {
any state ;
NavigationHistoryBehavior history = "auto";
};
dictionary NavigationReloadOptions : NavigationOptions {
any state ;
};
dictionary NavigationResult {
Promise <NavigationHistoryEntry > committed ;
Promise <NavigationHistoryEntry > finished ;
};
enum NavigationHistoryBehavior {
" auto " ,
" push " ,
" replace "
};
Each Window has an associated navigation
API, which is a Navigation object. Upon creation of the Window
object, its navigation API must be set to a
new Navigation object created in the Window object's relevant realm.
The navigation getter
steps are to return this's navigation
API.
The following are the event handlers (and their corresponding event handler event types) that must be supported,
as event handler IDL attributes, by all objects implementing the
Navigation interface:
| Event handler | Event handler event type |
|---|---|
onnavigate
| navigate
|
onnavigatesuccess
| navigatesuccess
|
onnavigateerror
| navigateerror
|
oncurrententrychange
| currententrychange
|
Each Navigation has an associated entry
list, a list of NavigationHistoryEntry objects, initially
empty.
Each Navigation has an associated current entry index, an integer, initially
−1.
The current entry of a Navigation
navigation is the result of running the following steps:
If navigation has entries and events disabled, then return null.
Assert: navigation's current entry index is not −1.
Return navigation's entry list[navigation's current entry index].
A Navigation navigation has entries and events disabled if
the following steps return true:
Let document be navigation's relevant global object's
associated Document.
If document is not fully active, then return true.
If document's is initial about:blank is true, then
return true.
Return false.
To get the navigation API entry
index of a session history entry she within a
Navigation navigation:
Let index be 0.
For each nhe of navigation's entry list:
If nhe's session history entry is equal to she, then return index.
Increment index by 1.
Return −1.
A key type used throughout the navigation API is the NavigationType
enumeration:
enum NavigationType {
" push " ,
" replace " ,
" reload " ,
" traverse "
};
This captures the main web developer-visible types of "navigations", which (as noted elsewhere) do not exactly correspond to this standard's singular navigate algorithm. The meaning of each value is the following:
push"push", or to
history.pushState().replace"replace", or
to history.replaceState().reload"traverse"The value space of the NavigationType enumeration is a superset of
the value space of the specification-internal history handling behavior type. Several
parts of this standard make use of this overlap, by passing in a history handling
behavior to an algorithm that expects a NavigationType.
To initialize the navigation API entries for a new document given a
Navigation navigation, a list of session history entries newSHEs, and a session history
entry initialSHE:
Assert: navigation's entry list is empty.
Assert: navigation's current entry index is −1.
If navigation has entries and events disabled, then return.
For each newSHE of newSHEs:
Let newNHE be a new NavigationHistoryEntry created
in the relevant realm of
navigation.
Set newNHE's session history entry to newSHE.
Append newNHE to navigation's entry list.
newSHEs will have originally come from getting session history entries for the navigation API, and thus each newSHE will be contiguous same origin with initialSHE.
Set navigation's current entry index to the result of getting the navigation API entry index of initialSHE within navigation.
To update the navigation API entries for reactivation given a
Navigation navigation, a list of session history entries newSHEs, and a session history
entry reactivatedSHE:
If navigation has entries and events disabled, then return.
Let newNHEs be a new empty list.
Let oldNHEs be a clone of navigation's entry list.
For each newSHE of newSHEs:
Let newNHE be null.
If oldNHEs contains a
NavigationHistoryEntry matchingOldNHE whose session history entry is newSHE:
Set newNHE to matchingOldNHE.
Remove matchingOldNHE from oldNHEs.
Otherwise:
Set newNHE to a new NavigationHistoryEntry
created in the relevant realm of
navigation.
Set newNHE's session history entry to newSHE.
Append newNHE to newNHEs.
newSHEs will have originally come from getting session history entries for the navigation API, and thus each newSHE will be contiguous same origin with reactivatedSHE.
By the end of this loop, all NavigationHistoryEntrys that remain in
oldNHEs represent session history entries
which have been disposed while the Document was in bfcache.
Set navigation's entry list to newNHEs.
Set navigation's current entry index to the result of getting the navigation API entry index of reactivatedSHE within navigation.
Queue a global task on the navigation and traversal task source given navigation's relevant global object to run the following steps:
For each disposedNHE of oldNHEs:
Fire an event named dispose at disposedNHE.
We delay these steps by a task to ensure that dispose
events will fire after the pageshow event. This ensures
that pageshow is the first event a page receives upon
reactivation.
(However, the rest of this algorithm runs before the pageshow event fires. This ensures that navigation.entries() and navigation.currentEntry will have correctly-updated
values during any pageshow event handlers.)
To update the navigation API entries for a same-document navigation given a
Navigation navigation, a session history entry
destinationSHE, and a NavigationType navigationType:
If navigation has entries and events disabled, then return.
Let oldCurrentNHE be the current entry of navigation.
Let disposedNHEs be a new empty list.
If navigationType is "traverse":
Set navigation's current entry index to the result of getting the navigation API entry index of destinationSHE within navigation.
Assert: navigation's current entry index is not −1.
This algorithm is only called for same-document traversals. Cross-document traversals will instead call either initialize the navigation API entries for a new document or update the navigation API entries for reactivation.
Otherwise, if navigationType is "push":
Set navigation's current entry index to navigation's current entry index + 1.
Let i be navigation's current entry index.
While i < navigation's entry list's size:
Append navigation's entry list[i] to disposedNHEs.
Set i to i + 1.
Remove all items in disposedNHEs from navigation's entry list.
Otherwise, if navigationType is "replace":
Append oldCurrentNHE to disposedNHEs.
If navigationType is "push" or
"replace":
Let newNHE be a new NavigationHistoryEntry created
in the relevant realm of
navigation.
Set newNHE's session history entry to destinationSHE.
Set navigation's entry list[navigation's current entry index] to newNHE.
If navigation's ongoing API method tracker is non-null, then notify about the committed-to entry given navigation's ongoing API method tracker and the current entry of navigation.
It is important to do this before firing the dispose or currententrychange events, since event handlers could
start another navigation, or otherwise change the value of navigation's ongoing
API method tracker.
Let navigateEvent be navigation's ongoing navigate event.
Let apiMethodTracker be navigation's ongoing API method tracker.
Prepare to run script given navigation's relevant settings object.
See the discussion for other navigation API events to understand why