Document objectenum DocumentReadyState { "loading" , "interactive" , "complete" };
enum DocumentVisibilityState { "visible" , "hidden" };
typedef (HTMLScriptElement or SVGScriptElement ) HTMLOrSVGScriptElement ;
[LegacyOverrideBuiltIns ]
partial interface Document {
static Document parseHTMLUnsafe ((TrustedHTML or DOMString ) html , optional ParseHTMLUnsafeOptions options = {});
static Document parseHTML (DOMString html , optional SetHTMLOptions options = {});
// resource metadata management
[PutForwards =href , LegacyUnforgeable ] readonly attribute Location ? location ;
attribute USVString domain ;
readonly attribute USVString referrer ;
attribute USVString cookie ;
readonly attribute DOMString lastModified ;
readonly attribute DocumentReadyState readyState ;
// DOM tree accessors
getter object (DOMString name );
[CEReactions ] attribute DOMString title ;
[CEReactions ] attribute DOMString dir ;
[CEReactions ] attribute HTMLElement ? body ;
readonly attribute HTMLHeadElement ? head ;
[SameObject ] readonly attribute HTMLCollection images ;
[SameObject ] readonly attribute HTMLCollection embeds ;
[SameObject ] readonly attribute HTMLCollection plugins ;
[SameObject ] readonly attribute HTMLCollection links ;
[SameObject ] readonly attribute HTMLCollection forms ;
[SameObject ] readonly attribute HTMLCollection scripts ;
NodeList getElementsByName (DOMString elementName );
readonly attribute HTMLOrSVGScriptElement ? currentScript ; // classic scripts in a document tree only
// dynamic markup insertion
[CEReactions ] Document open (optional DOMString unused1 , optional DOMString unused2 ); // both arguments are ignored
WindowProxy ? open (USVString url , DOMString name , DOMString features );
[CEReactions ] undefined close ();
[CEReactions ] undefined write ((TrustedHTML or DOMString )... text );
[CEReactions ] undefined writeln ((TrustedHTML or DOMString )... text );
// user interaction
readonly attribute WindowProxy ? defaultView ;
boolean hasFocus ();
[CEReactions ] attribute DOMString designMode ;
[CEReactions ] boolean execCommand (DOMString commandId , optional boolean showUI = false , optional DOMString value = "");
boolean queryCommandEnabled (DOMString commandId );
boolean queryCommandIndeterm (DOMString commandId );
boolean queryCommandState (DOMString commandId );
boolean queryCommandSupported (DOMString commandId );
DOMString queryCommandValue (DOMString commandId );
readonly attribute boolean hidden ;
readonly attribute DocumentVisibilityState visibilityState ;
// special event handler IDL attributes that only apply to Document objects
[LegacyLenientThis ] attribute EventHandler onreadystatechange ;
attribute EventHandler onvisibilitychange ;
// also has obsolete members
};
Document includes GlobalEventHandlers ;
Each Document has an is initial about:blank, which is a
boolean, initially false.
Each Document has an open dialogs list, which is a list of
dialog elements, initially empty.
Interfaces declared with constructor operations that are annotated with the [HTMLConstructor] extended attribute have the following
overridden constructor steps:
If NewTarget is equal to the active function
object, then throw a TypeError.
This can occur when a custom element is defined using an element interface as its constructor:
customElements. define( "bad-1" , HTMLButtonElement);
new HTMLButtonElement(); // (1)
document. createElement( "bad-1" ); // (2)
In this case, during the execution of HTMLButtonElement (either explicitly, as
in (1), or implicitly, as in (2)), both the active function object and
NewTarget are HTMLButtonElement. If this check was not present, it
would be possible to create an instance of HTMLButtonElement whose local name was
bad-1.
Let registry be null.
If the surrounding agent's active custom element constructor map[NewTarget] exists, then set registry to the surrounding agent's active custom element constructor map[NewTarget].
Otherwise, set registry to the current global object's associated Document's custom element registry.
Let definition be the item in registry's custom element
definition set with constructor equal to
NewTarget. If there is no such item, then throw a TypeError.
Since there can be no item in registry's custom element definition set with a constructor of undefined, this step also prevents HTML element constructors from being called as functions (since in that case NewTarget will be undefined).
Let isValue be null.
If definition's local name is equal to definition's name (i.e., definition is for an autonomous custom element):
If the active function object is not HTMLElement, then throw a
TypeError.
This can occur when a custom element is defined to not extend any local names, but
inherits from a non-HTMLElement class:
customElements. define( "bad-2" , class Bad2 extends HTMLParagraphElement {});
In this case, during the (implicit) super() call that occurs when
constructing an instance of Bad2, the active function
object is HTMLParagraphElement, not HTMLElement.
Otherwise (i.e., if definition is for a customized built-in element):
Let valid local names be the list of local names for elements defined in this specification or in other applicable specifications that use the active function object as their element interface.
If valid local names does not contain definition's local name, then throw a
TypeError.
This can occur when a custom element is defined to extend a given local name but inherits from the wrong class:
customElements. define( "bad-3" , class Bad3 extends HTMLQuoteElement {}, { extends : "p" });
In this case, during the (implicit) super() call that occurs when
constructing an instance of Bad3, valid local names is the
list containing q and blockquote, but definition's local name is p,
which is not in that list.
Set isValue to definition's name.
If definition's construction stack is empty:
Let element be the result of internally creating a new object implementing the interface to which the active function object corresponds, given the current realm and NewTarget.
Set element's node document to the current global
object's associated
Document.
Set element's namespace to the HTML namespace.
Set element's namespace prefix to null.
Set element's local name to definition's local name.
Set element's custom element registry to registry.
Set element's custom element state to "custom".
Set element's custom element definition to definition.
Set element's is value to isValue.
Return element.
This occurs when author script constructs a new custom element directly, e.g.,
via new MyCustomElement().
If prototype is not an Object:
Let realm be ? GetFunctionRealm(NewTarget).
Set prototype to the interface prototype object of realm whose interface is the same as the interface of the active function object.
The realm of the active function object might not be realm, so we are using the more general concept of "the same interface" across realms; we are not looking for equality of interface objects. This fallback behavior, including using the realm of NewTarget and looking up the appropriate prototype there, is designed to match analogous behavior for the JavaScript built-ins and Web IDL's internally create a new object implementing the interface algorithm.
Let element be the last entry in definition's construction stack.
If element is an already
constructed marker, then throw a TypeError.
This can occur when the author code inside the custom element
constructor non-conformantly creates another
instance of the class being constructed, before calling super():
let doSillyThing = true ;
class DontDoThis extends HTMLElement {
constructor() {
if ( doSillyThing) {
doSillyThing = false ;
new DontDoThis();
// Now the construction stack will contain an already constructed marker.
}
// This will then fail with a TypeError:
super ();
}
}
This can also occur when author code inside the custom element constructor non-conformantly calls super()
twice, since per the JavaScript specification, this actually executes the superclass
constructor (i.e. this algorithm) twice, before throwing an error:
class DontDoThisEither extends HTMLElement {
constructor() {
super ();
// This will throw, but not until it has already called into the HTMLElement constructor
super ();
}
}
Perform ? element.[[SetPrototypeOf]](prototype).
Replace the last entry in definition's construction stack with an already constructed marker.
Return element.
This step is normally reached when upgrading a custom element; the existing element is
returned, so that the super() call inside the custom element
constructor assigns that existing element to this.
The rendered text fragment for a string input given a
Document document is the result of running the following steps:
Let fragment be the result of creating a document fragment given document.
Let position be a position variable for input, initially pointing at the start of input.
Let text be the empty string.
While position is not past the end of input:
Collect a sequence of code points that are not U+000A LF or U+000D CR from input given position, and set text to the result.
If text is not the empty string, then append a new Text node whose data is text and node document is
document to fragment.
While position is not past the end of input, and the code point at position is either U+000A LF or U+000D CR:
If the code point at position is U+000D CR and the next code point is U+000A LF, then advance position to the next code point in input.
Advance position to the next code point in input.
Append the result of creating an element given document, "br",
and the HTML namespace to fragment.
Return fragment.
When the user agent is to update the image data of an img element
element, optionally with the restart animation flag set, optionally with the
maybe omit events flag set, it must run the following steps:
If element's node document is not fully active:
Continue running this algorithm in parallel.
Wait until element's node document is fully active.
If another instance of this algorithm for element was started after this instance (even if it aborted and is no longer running), then return.
Queue a microtask to continue this algorithm.
If the user agent cannot support images, or its support for images has been disabled, then abort the image request for the current request and the pending request, set the current request's state to unavailable, set the pending request to null, and return.
Let previousURL be the current request's current URL.
Let selected source be null and selected pixel density be undefined.
If element does not use srcset or
picture and it has a src attribute
specified whose value is not the empty string, then set selected source to the value
of element's src attribute and set selected
pixel density to 1.0.
Set element's last selected source to selected source.
If selected source is not null:
Let urlString be the result of encoding-parsing-and-serializing a URL given selected source, relative to element's node document.
If urlString is failure, then abort this inner set of steps.
Let key be a tuple consisting of urlString, element's
crossorigin attribute's mode, and, if that
mode is not No CORS, element's
node document's origin.
If the list of available images contains an entry for key:
Set the ignore higher-layer caching flag for that entry.
Abort the image request for the current request and the pending request.
Set the pending request to null.
Set the current request to a new image request whose image data is that of the entry and whose state is completely available.
Prepare the current request for presentation given element.
Set the current request's current pixel density to selected pixel density.
Queue an element task on the DOM manipulation task source given element and the following steps:
If restart animation is set, then restart the animation.
Set the current request's current URL to urlString.
If maybe omit events is not set or previousURL is not equal to
urlString, then fire an event named
load at element.
Abort the update the image data algorithm.
Queue a microtask to perform the rest of this algorithm, allowing the task that invoked this algorithm to continue.
If another instance of this algorithm for element was started after this instance (even if it aborted and is no longer running), then return.
Only the last instance takes effect, to avoid multiple requests when, for
example, the src, srcset,
and crossorigin attributes are all set in
succession.
Let selected source and selected pixel density be the URL and pixel density that results from selecting an image source, respectively.
If selected source is null:
Set the current request's state to broken, abort the image request for the current request and the pending request, and set the pending request to null.
Queue an element task on the DOM manipulation task source given element and the following steps:
Change the current request's current URL to the empty string.
If all of the following are true:
element has a src attribute or it
uses srcset or
picture; and
maybe omit events is not set or previousURL is not the empty string,
then fire an event named error at element.
Return.
Let urlString be the result of encoding-parsing-and-serializing a URL given selected source, relative to element's node document.
If urlString is failure:
Abort the image request for the current request and the pending request.
Set the current request's state to broken.
Set the pending request to null.
Queue an element task on the DOM manipulation task source given element and the following steps:
Change the current request's current URL to selected source.
If maybe omit events is not set or previousURL is not equal to
selected source, then fire an event
named error at element.
Return.
If the pending request is not null and urlString is the same as the pending request's current URL, then return.
If urlString is the same as the current request's current URL and the current request's state is partially available:
Abort the image request for the pending request.
If restart animation is set, then queue an element task on the DOM manipulation task source given element to restart the animation.
Return.
Abort the image request for the pending request.
Set image request to a new image request whose current URL is urlString.
If the current request's state is unavailable or broken, then set the current request to image request. Otherwise, set the pending request to image request.
Let request be the result of creating a potential-CORS request given urlString, "image", and the current state of element's crossorigin content attribute.
Set request's client to element's node document's relevant settings object.
If element uses srcset or
picture, set request's initiator to "imageset".
Set request's referrer
policy to the current state of element's referrerpolicy attribute.
Set request's priority to the current state of element's
fetchpriority attribute.
Let delay load event be true if the img's lazy loading
attribute is in the Eager state, or if
scripting is disabled for the img, and
false otherwise.
If the will lazy load element steps given the img return true:
Set the img's lazy load resumption steps to the rest of this
algorithm starting with the step labeled fetch the image.
Start intersection-observing a lazy loading element for element.
Return.
Fetch the image: Fetch request. Return from this algorithm, and run the remaining steps as part of the fetch's processResponse for the response response.
The resource obtained in this fashion, if any, is image request's image data. It can be either CORS-same-origin or
CORS-cross-origin; this affects the image's interaction with other APIs (e.g.,
when used on a canvas).
When delay load event is true, fetching the image must delay the load event of element's node document until the task that is queued by the networking task source once the resource has been fetched (defined below) has been run.
This, unfortunately, can be used to perform a rudimentary port scan of the user's local network (especially in conjunction with scripting, though scripting isn't actually necessary to carry out such an attack). User agents may implement cross-origin access control policies that are stricter than those described above to mitigate this attack, but unfortunately such policies are typically not compatible with existing web content.
As soon as possible, jump to the first applicable entry from the following list:
multipart/x-mixed-replaceThe next task that is queued by the networking task source while the image is being fetched must run the following steps:
If image request is the pending request and at least one body part has been completely decoded, abort the image request for the current request, and upgrade the pending request to the current request.
Otherwise, if image request is the pending request and the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, abort the image request for the current request, upgrade the pending request to the current request, and set the current request's state to broken.
Otherwise, if image request is the current request, its state is unavailable, and the user agent is able to determine image request's image's width and height, set the current request's state to partially available.
Otherwise, if image request is the current request, its state is unavailable, and the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, set the current request's state to broken.
Each task that is queued by the networking task source while the image is being fetched must update the presentation of the image, but as each new body part comes in, if the user agent is able to determine the image's width and height, it must prepare element's current request for presentation given element and replace the previous image. Once one body part has been completely decoded, perform the following steps:
Set element's current request's state to completely available.
If maybe omit events is not set or previousURL is not equal to
urlString, then queue an element task on the DOM manipulation task source
given element to fire an event
named load at element.
The next task that is queued by the networking task source while the image is being fetched must run the following steps:
If the user agent is able to determine image request's image's width and height, and image request is the pending request, set image request's state to partially available.
Otherwise, if the user agent is able to determine image request's image's width and height, and image request is the current request, prepare image request for presentation given element and set image request's state to partially available.
Otherwise, if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, and image request is the pending request:
Abort the image request for the current request and the pending request.
Set the current request's state to broken.
Fire an event named error at element.
Otherwise, if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, and image request is the current request:
Abort the image request for image request.
If maybe omit events is not set or previousURL is not equal to
urlString, then fire an event named
error at element.
That task, and each subsequent task that is queued by the networking task source while the image is being fetched, must, if image request is the current request, update the presentation of the image appropriately (e.g., if the image is a progressive JPEG, each packet can improve the resolution of the image).
Furthermore, the last task that is queued by the networking task source once the resource has been fetched must additionally run these steps:
If image request is the pending request, abort the image request for the current request, upgrade the pending request to the current request, and prepare image request for presentation given element.
Set image request to the completely available state.
Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.
If maybe omit events is not set or previousURL is not equal to
urlString, then fire an event named
load at element.
The image data is not in a supported file format; the user agent must set image
request's state to broken, abort the image request for the current
request and the pending request, upgrade the pending request to the
current request if image request is the pending request, and
then, if maybe omit events is not set or previousURL is not equal to
urlString, queue an element task on the DOM manipulation task
source given element to fire an
event named error at element.
To show a modal dialog given a dialog element subject and an
Element or null source:
If subject has an open attribute and
is modal of subject is true, then return.
If subject has an open attribute, then
throw an "InvalidStateError" DOMException.
If subject's node document is not fully active, then
throw an "InvalidStateError" DOMException.
If subject is not connected, then throw an
"InvalidStateError" DOMException.
If subject is in the popover showing
state, then throw an "InvalidStateError"
DOMException.
If the result of firing an event named beforetoggle, using ToggleEvent, with the cancelable attribute initialized to true, the oldState attribute initialized to "closed", the newState
attribute initialized to "open", and the source attribute initialized to source at
subject is false, then return.
If subject has an open attribute,
then return.
If subject is not connected, then return.
If subject is in the popover showing state, then return.
Queue a dialog toggle event task given subject, "closed", "open", and source.
Add an open attribute to subject, whose
value is the empty string.
Assert: subject's close watcher is not null.
Set is modal of subject to true.
Set subject's node document to be blocked by the modal dialog subject.
This will cause the focused area of the document to become inert (unless that currently focused area is a shadow-including descendant of subject). In such cases, the focused area of the document will soon be reset to the viewport. In a couple steps we will attempt to find a better candidate to focus.
If subject's node document's top layer does not already contain subject, then add an element to the top layer given subject.
Set subject's previously focused element to the focused element.
Let document be subject's node document.
Let hideUntil be the result of running topmost popover ancestor given subject, null, and false.
Run hide popovers until given document, hideUntil, false, and true.
Run the dialog focusing steps given subject.
The dialog setup steps, given a dialog element subject, are
as follows:
Assert: subject's node document's open dialogs list does not contain subject.
Add subject to subject's node document's open dialogs list.
Set the dialog close watcher with subject.
A sandboxing flag set is a set of zero or more of the following flags, which are used to restrict the abilities that potentially untrusted resources have:
This flag prevents content from navigating browsing contexts other than the sandboxed browsing context itself (or browsing contexts further nested inside it), auxiliary browsing contexts (which are protected by the sandboxed auxiliary navigation browsing context flag defined next), and the top-level browsing context (which is protected by the sandboxed top-level navigation without user activation browsing context flag and sandboxed top-level navigation with user activation browsing context flag defined below).
If the sandboxed auxiliary navigation browsing context flag is not set, then in certain cases the restrictions nonetheless allow popups (new top-level browsing contexts) to be opened. These browsing contexts always have one permitted sandboxed navigator, set when the browsing context is created, which allows the browsing context that created them to actually navigate them. (Otherwise, the sandboxed navigation browsing context flag would prevent them from being navigated even if they were opened.)
This flag prevents content from creating new auxiliary browsing
contexts, e.g. using the target attribute or
the window.open() method.
This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context. It is consulted only when the sandboxed browsing context's active window does not have transient activation.
When the sandboxed top-level navigation without user activation browsing context flag is not set, content can navigate its top-level browsing context, but other browsing contexts are still protected by the sandboxed navigation browsing context flag and possibly the sandboxed auxiliary navigation browsing context flag.
This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context. It is consulted only when the sandboxed browsing context's active window has transient activation.
As with the sandboxed top-level navigation without user activation browsing context flag, this flag only affects the top-level browsing context; if it is not set, other browsing contexts might still be protected by other flags.
This flag forces content into an opaque origin, thus preventing it from accessing other content from the same origin.
This flag also prevents script from reading from or writing to the
document.cookie IDL attribute, and blocks access
to localStorage.
This flag blocks form submission.
This flag disables the Pointer Lock API. [POINTERLOCK]
This flag blocks script execution.
This flag blocks features that trigger automatically, such as automatically playing a video or automatically focusing a form control.
document.domain
browsing context flagThis flag prevents content from using the
document.domain setter.
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.
This flag prevents content from using any of the following features to produce modal dialogs:
This flag disables the ability to lock the screen orientation. [SCREENORIENTATION]
This flag disables the Presentation API. [PRESENTATION]
This flag prevents content from initiating or instantiating downloads, whether through downloading hyperlinks or through navigation that gets handled as a download.
This flag prevents navigations toward non fetch schemes from being handed off to external software.
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.
A navigable presents a Document to the user via its active session history entry. Each navigable has:
An id, a new unique internal value.
A parent, a navigable or null.
A current session history entry, a session history entry.
This can only be modified within the session history traversal queue of the parent traversable navigable.
An active session history entry, a session history entry.
This can only be modified from the event loop of the active session history entry's document.
An is closing boolean, initially false.
This is only ever set to true for top-level traversable navigables.
An is delaying load
events boolean, initially false.
This is only ever set to true in cases where the navigable's parent is non-null.
An allowed to perform a navigation or history update algorithm, which is implementation-defined and returns either allowed or blocked.
For example, this can return blocked if invoked too many times times within a certain timespan.
To initialize the navigable navigable navigable, given a document state documentState and an optional navigable-or-null parent (default null):
Let entry be a new session history entry, with
The caller of this algorithm is responsible for initializing entry's
step; it will be left as "pending" until
that is complete.
Set navigable's current session history entry to entry.
Set navigable's active session history entry to entry.
Set navigable's parent to parent.
Set the initial visibility state of documentState's document to navigable's traversable navigable's system visibility state.
To create a new browsing context and document, given null or a Document
object creator, null or an element embedder, and a browsing context
group group:
Let browsingContext be a new browsing context.
Let unsafeContextCreationTime be the unsafe shared current time.
Let creatorOrigin be null.
Let creatorBaseURL be null.
If creator is non-null:
Set creatorOrigin to creator's origin.
Set creatorBaseURL to creator's document base URL.
Set browsingContext's virtual browsing context group ID to creator's browsing context's top-level browsing context's virtual browsing context group ID.
Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedder.
Let origin be the result of determining the
origin given about:blank, sandboxFlags, and
creatorOrigin.
Let permissionsPolicy be the result of creating a permissions policy given embedder and origin. [PERMISSIONSPOLICY]
Let agent be the result of obtaining a similar-origin window agent given origin, group, and false.
Let realm execution context be the result of creating a new realm given agent and the following customizations:
For the global object, create a new Window object.
For the global this binding, use browsingContext's
WindowProxy object.
Let topLevelCreationURL be about:blank if embedder is
null; otherwise embedder's relevant settings object's top-level
creation URL.
Let topLevelOrigin be origin if embedder is null; otherwise embedder's relevant settings object's top-level origin.
Set up a window environment settings object with about:blank,
realm execution context, null, topLevelCreationURL, and
topLevelOrigin.
Let loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling coarsen time with unsafeContextCreationTime and the new environment settings object's cross-origin isolated capability.
Let document be a new Document, with:
html"text/html"quirks"about:blankCustomElementRegistry objectLet iframeReferrerPolicy be the result of determining the
iframe element referrer policy given embedder.
Set document's internal ancestor origin objects list to the result of running the internal ancestor origin objects list creation steps given document and iframeReferrerPolicy.
Set document's ancestor origins list to the result of running the ancestor origins list creation steps given document.
If creator is non-null:
Set document's referrer to the serialization of creator's URL.
Set document's policy container to a clone of creator's policy container.
If creator's origin is same origin with creator's relevant settings object's top-level origin, then set document's opener policy to creator's browsing context's top-level browsing context's active document's opener policy.
Assert: document's URL
and document's relevant settings object's creation URL are
about:blank.
Mark document as ready for post-load tasks.
Populate with html/head/body given
document.
Make active document.
Completely finish loading document.
Return browsingContext and document.
To navigate to a fragment given a navigable
navigable, a URL url, a history handling behavior
historyHandling, a user navigation involvement userInvolvement,
an Element-or-null sourceElement, a serialized state-or-null
navigationAPIState, and a navigation ID navigationId:
Let navigation be navigable's active window's navigation API.
Let destinationNavigationAPIState be navigable's active session history entry's navigation API state.
If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState.
Let continue be the result of firing a push/replace/reload navigate event at
navigation with navigationType set to
historyHandling, isSameDocument set
to true, userInvolvement set to
userInvolvement, sourceElement set
to sourceElement, destinationURL
set to url, and navigationAPIState set to
destinationNavigationAPIState.
If continue is false:
If navigation's ongoing navigate
event is not null, then set the ongoing navigation of navigable
to navigationId.
This makes intercepted hash navigations cancelable by browser UI or window.stop().
Return.
Let historyEntry be a new session history entry, with
For navigations performed with navigation.navigate(), the value provided by the state option is used for the new navigation API state. (This will set it to the
serialization of undefined, if no value is provided for that option.) For other fragment
navigations, including user-initiated ones, the navigation API state is carried over from the previous
entry.
The classic history API state is never carried over.
Let entryToReplace be navigable's active session history entry if
historyHandling is "replace",
otherwise null.
If entryToReplace is non-null, then set historyEntry's navigation API key to entryToReplace's navigation API key.
Let history be navigable's active document's history object.
Let scriptHistoryIndex be history's index.
Let scriptHistoryLength be history's length.
If historyHandling is "push":
Set history's state to null.
Increment scriptHistoryIndex.
Set scriptHistoryLength to scriptHistoryIndex + 1.
Set navigable's active document's URL to url.
Set navigable's active session history entry to historyEntry.
Update document for history step application given navigable's active document, historyEntry, true, scriptHistoryIndex, scriptHistoryLength, and historyHandling.
This algorithm will be called twice as a result of a single fragment
navigation: once synchronously, where best-guess values scriptHistoryIndex and
scriptHistoryLength are set, history.state
is nulled out, and various events are fired; and once asynchronously, where the final values for
index and length are set, history.state remains
untouched, and no events are fired.
Scroll to the fragment given navigable's active document.
If the scrolling fails because the Document is new and the
relevant ID has not yet been parsed, then the second
asynchronous call to update document for history step application will take
care of scrolling.
Let traversable be navigable's traversable navigable.
Append the following session history synchronous navigation steps involving navigable to traversable:
Finalize a same-document navigation given traversable, navigable, historyEntry, entryToReplace, historyHandling, and userInvolvement.
Invoke WebDriver BiDi fragment navigated with navigable and a
new WebDriver BiDi navigation status whose id is navigationId, url is url, and status is "complete".
To reload a navigable navigable given an optional
serialized state-or-null navigationAPIState (default null), an
optional user navigation involvement userInvolvement (default "none"), and an optional navigation API method
tracker-or-null apiMethodTracker
(default null):
If userInvolvement is not "browser UI":
Let navigation be navigable's active window's navigation API.
Let destinationNavigationAPIState be navigable's active session history entry's navigation API state.
If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState.
Let continue be the result of firing a push/replace/reload navigate
event at navigation with navigationType set to "reload", isSameDocument set to false, userInvolvement set to
userInvolvement, destinationURL
set to navigable's active session history
entry's URL, navigationAPIState set to
destinationNavigationAPIState, and apiMethodTracker set to
apiMethodTracker.
If continue is false, then return.
Set navigable's active session history entry's document state's reload pending to true.
Let traversable be navigable's traversable navigable.
Append the following session history traversal steps to traversable:
Apply the reload history step to traversable given userInvolvement.
The URL and history update steps, given a Document
document, a URL newURL, an optional serialized
state-or-null serializedData (default
null), and an optional history handling behavior historyHandling (default "replace"), are:
Let navigable be document's node navigable.
Let activeEntry be navigable's active session history entry.
Let newEntry be a new session history entry, with
If document's is initial about:blank is true, then set
historyHandling to "replace".
This means that pushState() on an
initial about:blank
Document behaves as a replaceState() call.
Let entryToReplace be activeEntry if historyHandling is
"replace", otherwise null.
If entryToReplace is non-null, then set newEntry's navigation API key to entryToReplace's navigation API key.
If historyHandling is "push":
Increment document's history object's index.
Set document's history object's length to its index + 1.
These are temporary best-guess values for immediate synchronous access.
If serializedData is not null, then restore the history object state given document and newEntry.
Set the URL given document to newURL.
Since this is neither a navigation nor a history traversal, it does not cause a hashchange event to be fired.
Set document's latest entry to newEntry.
Set navigable's active session history entry to newEntry.
Update the navigation API entries for a same-document navigation given document's relevant global object's navigation API, newEntry, and historyHandling.
Let traversable be navigable's traversable navigable.
Append the following session history synchronous navigation steps involving navigable to traversable:
Finalize a same-document navigation given traversable,
navigable, newEntry, entryToReplace,
historyHandling, and "none".
Invoke WebDriver BiDi history updated with navigable.
To activate history entry session history entry entry for navigable navigable:
Save persisted state to the navigable's active session history entry.
Let newDocument be entry's document.
Assert: newDocument's is initial
about:blank is false, i.e., we never traverse back to the initial about:blank Document because it
always gets replaced when we navigate away from
it.
Set navigable's active session history entry to entry.
Make active newDocument.
Set the initial visibility state of newDocument to navigable's traversable navigable's system visibility state.
To make document unsalvageable, given a Document
document and a string reason:
Let details be a new not restored reason details whose reason is reason.
Append details to document's bfcache blocking details.
Set document's salvageable state to false.
When loading a document using one of the below algorithms, we use the
following steps to create and initialize a Document object,
given a type type, content type contentType, and
navigation params navigationParams:
Document objects are also created when creating a new browsing
context and document; such initial
about:blank Document are never created by this algorithm. Also,
browsing context-less Document objects can
be created via various APIs, such as document.implementation.createHTMLDocument().
Let browsingContext be the result of obtaining a browsing context to use for a navigation response given navigationParams.
This can result in a browsing context
group switch, in which case browsingContext will be a newly-created browsing context instead
of being navigationParams's navigable's active browsing
context. In such a case, the created Window, Document, and
agent will not end up being used; because the created Document's
origin is opaque, we will end up creating a new agent
and Window later in this algorithm to
go along with the new Document.
Let permissionsPolicy be the result of creating a permissions policy from a response given navigationParams's navigable's container, navigationParams's origin, and navigationParams's response. [PERMISSIONSPOLICY]
The creating a permissions policy from a response algorithm makes use of the
passed origin. If document.domain has
been used for navigationParams's navigable's container document, then its origin cannot be same origin-domain with
the passed origin, because these steps run before the document is created, so it
cannot itself yet have used document.domain. Note
that this means that Permissions Policy checks are less permissive compared to doing a
same origin check instead.
See below for some examples of this in action.
If navigationParams's request is non-null, then set creationURL to navigationParams's request's current URL.
Let window be null.
If browsingContext's active document's is initial
about:blank is true, and browsingContext's active
document's origin is same
origin-domain with navigationParams's origin, then set window to
browsingContext's active window.
This means that both the initial
about:blank Document, and the new Document that
is about to be created, will share the same Window object.
Otherwise:
Let oacHeader be the result of getting a structured field value
given `Origin-Agent-Cluster` and "item" from
navigationParams's response's
header list.
Let requestsOAC be true if oacHeader is not null and oacHeader[0] is the boolean true; otherwise false.
If navigationParams's reserved environment is a non-secure context, then set requestsOAC to false.
Let agent be the result of obtaining a similar-origin window agent given navigationParams's origin, browsingContext's group, and requestsOAC.
Let realmExecutionContext be the result of creating a new realm given agent and the following customizations:
For the global object, create a new Window object.
For the global this binding, use browsingContext's
WindowProxy object.
Set window to the global object of realmExecutionContext's Realm component.
Let topLevelCreationURL be creationURL.
Let topLevelOrigin be navigationParams's origin.
If navigable's container is not null:
Let parentEnvironment be navigable's container's relevant settings object.
Set topLevelCreationURL to parentEnvironment's top-level creation URL.
Set topLevelOrigin to parentEnvironment's top-level origin.
Set up a window environment settings object with creationURL, realmExecutionContext, navigationParams's reserved environment, topLevelCreationURL, and topLevelOrigin.
This is the usual case, where the new Document we're about to
create gets a new Window to go along with it.
Let loadTimingInfo be a new document load timing info with its navigation start time set to navigationParams's response's timing info's start time.
Let document be a new Document, with
same-origin"; otherwise falseloading"CustomElementRegistry objectSet window's associated
Document to document.
Set document's internal ancestor origin objects
list to the result of running the internal ancestor origin objects list creation
steps given document and navigationParams's iframe element referrer
policy.
Set document's ancestor origins list to the result of running the ancestor origins list creation steps given document.
Run CSP initialization for a Document given
document. [CSP]
If navigationParams's request is non-null:
Set document's referrer to the empty string.
If referrer is a URL record, then set document's referrer to the serialization of referrer.
Per Fetch, referrer will be either a URL
record or "no-referrer" at this point.
If navigationParams's fetch controller is not null:
Let fullTimingInfo be the result of extracting the full timing info from navigationParams's fetch controller.
Let redirectCount be 0.
If navigationParams's response's redirect taint is "same-origin", or all of the following are true:
navigationParams's request's client is null, or navigationParams's
request's referrer is not "no-referrer", and
navigation TAO check given navigationParams's response and navigationParams's origin returns success,
then set redirectCount to navigationParams's request's redirect count.
Create the navigation timing entry for document, given fullTimingInfo, redirectCount, navigationTimingType, navigationParams's response's service worker timing info, and navigationParams's response's body info.
Create the navigation timing entry for document, with navigationParams's response's timing info, redirectCount, navigationParams's navigation timing type, and navigationParams's response's service worker timing info.
If navigationParams's response
has a `Refresh` header:
Let value be the isomorphic decoding of the value of the header.
Run the shared declarative refresh steps with document and value.
We do not currently have a spec for how to handle multiple `Refresh`
headers. This is tracked as issue #2900.
If navigationParams's commit early hints is not null, then call navigationParams's commit early hints with document.
Process link headers given document,
navigationParams's response, and
"pre-media".
If navigationParams's navigable
is a top-level traversable, then process the `Speculation-Rules`
header given document and navigationParams's response.
This is conditional because speculative loads are only considered for top-level traversables, so it would be wasteful to fetch these rules otherwise.
Potentially free deferred fetch quota for document.
Return document.
A Document has a salvageable state, which must initially be
true, and a page showing boolean, which is initially false. The page
showing boolean 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).
To unload a Document
oldDocument, given an optional Document newDocument:
Assert: this is running as part of a task queued on oldDocument's relevant agent's event loop.
Let unloadTimingInfo be a new document unload timing info.
If newDocument is not given, then set unloadTimingInfo to null.
In this case there is no new document that needs to know about how long it took oldDocument to unload.
Otherwise, if newDocument's event loop is not oldDocument's event loop, then the user agent may be unloading oldDocument in parallel. In that case, the user agent should set unloadTimingInfo to null.
In this case newDocument's loading is not impacted by how long it takes to unload oldDocument, so it would be meaningless to communicate that timing info.
Let intendToKeepInBfcache be true if the user agent intends to keep oldDocument alive in a session history entry, such that it can later be used for history traversal.
This must be false if oldDocument is not salvageable, or if there are any descendants of oldDocument which the user agent does not intend to keep alive in the same way (including due to their lack of salvageability).
Let eventLoop be oldDocument's relevant agent's event loop.
Increase eventLoop's termination nesting level by 1.
Increase oldDocument's unload counter by 1.
If intendToKeepInBfcache is false, then set oldDocument's salvageable state to false.
If oldDocument's page showing is true:
Set oldDocument's page showing to false.
Fire a page transition event named pagehide at oldDocument's relevant global
object with oldDocument's salvageable state.
Update the visibility state of oldDocument to
"hidden".
If unloadTimingInfo is not null, then set unloadTimingInfo's unload event start time to the current high resolution time given newDocument's relevant global object, coarsened given oldDocument's relevant settings object's cross-origin isolated capability.
If oldDocument's salvageable
state is false, then fire an event named unload at oldDocument's relevant global
object, with legacy target override flag set.
If unloadTimingInfo is not null, then set unloadTimingInfo's unload event end time to the current high resolution time given newDocument's relevant global object, coarsened given oldDocument's relevant settings object's cross-origin isolated capability.
Decrease eventLoop's termination nesting level by 1.
Set oldDocument's suspension time to the current high resolution time given document's relevant global object.
Set oldDocument's suspended timer handles to the result of getting the keys for the map of active timers.
Set oldDocument's has been scrolled by the user to false.
Run any unloading document cleanup steps for oldDocument that are defined by this specification and other applicable specifications.
If oldDocument's node navigable is a top-level traversable, build not restored reasons for a top-level traversable and its descendants given oldDocument's node navigable.
If oldDocument's salvageable state is false, then destroy oldDocument.
Decrease oldDocument's unload counter by 1.
If newDocument is given, newDocument's was created via cross-origin redirects is false, and newDocument's origin is the same as oldDocument's origin, then set newDocument's previous document unload timing to unloadTimingInfo.
To destroy a
Document document:
Assert: this is running as part of a task queued on document's relevant agent's event loop.
Abort document.
Set document's salvageable state to false.
Let ports be the list of MessagePorts whose relevant global
object's associated Document is
document.
For each port in ports, disentangle port.
Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.
Remove any tasks whose document is document from any task queue (without running those tasks).
Set document's browsing context to null.
Set document's node navigable's active session history entry's document state's document to null.
Remove document from the
owner set of each WorkerGlobalScope object whose set contains document.
For each workletGlobalScope in document's worklet global scopes, terminate workletGlobalScope.
To abort a document and its descendants given a Document
document:
Assert: this is running as part of a task queued on document's relevant agent's event loop.
Let descendantNavigables be document's descendant navigables.
For each descendantNavigable of descendantNavigables in what order?, queue a global task on the navigation and traversal task source given descendantNavigable's active window to perform the following steps:
Abort descendantNavigable's active document.
If descendantNavigable's active document's salvageable is false, then set document's salvageable to false.
Abort document.
The document open steps, given a document, are as follows:
If document is an XML document, then throw
an "InvalidStateError" DOMException.
If document's throw-on-dynamic-markup-insertion counter is greater
than 0, then throw an "InvalidStateError"
DOMException.
Let entryDocument be the entry global object's associated Document.
If document's origin is not
same origin to entryDocument's origin, then throw a
"SecurityError" DOMException.
If document has an active parser whose script nesting level is greater than 0, then return document.
This basically causes document.open() to
be ignored when it's called in an inline script found during parsing, while still letting it
have an effect when called from a non-parser task such as a timer callback or event handler.
Similarly, if document's unload counter is greater than 0, then return document.
This basically causes document.open() to
be ignored when it's called from a beforeunload, pagehide, or unload event
handler while the Document is being unloaded.
If document's active parser was aborted is true, then return document.
This notably causes document.open() to
be ignored if it is called after a navigation has started, but
only during the initial parse. See issue
#4723 for more background.
If document's node navigable is non-null and document's node navigable's ongoing navigation is a navigation ID, then stop loading document's node navigable.
For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.
If document is the associated
Document of document's relevant global object, then
erase all event listeners and handlers given document's relevant
global object.
Replace all with null within document.
If document is fully active:
Let newURL be a copy of entryDocument's URL.
If entryDocument is not document, then set newURL's fragment to null.
Run the URL and history update steps with document and newURL.
Set document's is initial about:blank to
false.
If document's iframe load in progress flag is set, then set document's mute iframe load flag.
Set document to no-quirks mode.
Create an HTML parser whose allow declarative shadow roots is
document's allow
declarative shadow roots, and associate it with document. This is a
script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for
an explicit call to document.close() before emitting an
end-of-file token). The encoding confidence is
irrelevant.
Set the insertion point to point at just before the end of the input stream (which at this point will be empty).
Update the current document readiness of document to "loading".
This causes a readystatechange
event to fire, but the event is actually unobservable to author code, because of the previous
step which erased all event listeners and
handlers that could observe it.
Return document.
When an XML parser creates a Node object, its node document
must be set to the node document of
the node into which the newly created node is to be inserted.
The dialog cleanup steps, given a dialog element subject,
are as follows:
Remove subject from subject's node document's open dialogs list.
If subject's close watcher is not null:
Destroy subject's close watcher.
Set subject's close watcher to null.