1. 7.11 Browsing the web
      1. 7.11.1 Navigating across documents
      2. 7.11.2 Page load processing model for HTML files
      3. 7.11.3 Page load processing model for XML files
      4. 7.11.4 Page load processing model for text files
      5. 7.11.5 Page load processing model for multipart/x-mixed-replace resources
      6. 7.11.6 Page load processing model for media
      7. 7.11.7 Page load processing model for content that uses plugins
      8. 7.11.8 Page load processing model for inline content that doesn't have a DOM
      9. 7.11.9 Navigating to a fragment
      10. 7.11.10 History traversal
        1. 7.11.10.1 Persisted history entry state
        2. 7.11.10.2 The PopStateEvent interface
        3. 7.11.10.3 The HashChangeEvent interface
        4. 7.11.10.4 The PageTransitionEvent interface
      11. 7.11.11 Loading documents
      12. 7.11.12 Unloading documents
        1. 7.11.12.1 The BeforeUnloadEvent interface
      13. 7.11.13 Aborting a document load
      14. 7.11.14 The `X-Frame-Options` header
      15. 7.11.15 The `Refresh` header

7.11 Browsing the web

Certain actions cause the browsing context to navigate to a new resource. A user agent may provide various ways for the user to explicitly cause a browsing context to navigate, in addition to those defined in this specification.

For example, following a hyperlink, form submission, and the window.open() and location.assign() methods can all cause a browsing context to navigate.

A resource has a URL, but that might not be the only information necessary to identify it. For example, a form submission that uses HTTP POST would also have the HTTP method and payload. Similarly, an iframe srcdoc document needs to know the data it is to use.

Much of the navigation process is concerned with determining how to create a new Document, which ultimately happens in the create and initialize a Document object algorithm. The parameters to this algorithm are tracked via a navigation params struct, which has the following items:

id
a navigation id
request
null or a request that started the navigation
response
a response that ultimately was navigated to (potentially a network error)
origin
an origin to use for the new Document
policy container
a policy container to use for the new Document
final sandboxing flag set
a sandboxing flag set to impose on the new Document
cross-origin opener policy
a cross-origin opener policy to use for the new Document
COOP enforcement result
a cross-origin opener policy enforcement result, used for reporting and potentially for causing a browsing context group switch
reserved environment
null or an environment reserved for the new Document
browsing context
the browsing context to be navigated (or discarded, if a browsing context group switch occurs)
history handling
a history handling behavior
has cross-origin redirects
a boolean
unsafe start time
a number, representing a value of the unsafe shared current time when the navigation has started

Once a navigation params struct is created, this standard does not mutate any of its items. They are only passed onward to other algorithms.

After Document creation, the session history gets updated. A history handling behavior is used to track the desired type of session history update throughout the navigation process. It is one of the following:

"default"
A regular navigation which adds a new entry to the session history.
"entry update"
A navigation to an existing session history entry to recreate that entry's document, which was previously discarded.
"reload"
A navigation intended to reload the current page and replace the current session history entry.
"replace"
A non-reload navigation that will replace the current session history entry.

Navigation always involves source browsing context, which is the browsing context which was responsible for starting the navigation.

As explained in issue #1130 the use of a browsing context as source might not be the correct architecture.

A navigation has a navigation id, which is a unique string.

To navigate a browsing context browsingContext to a resource resource, with an optional boolean exceptionsEnabled (default false), an optional history handling behavior historyHandling (default "default"), an optional policy container-or-null historyPolicyContainer (default null), an optional string navigationType (default "other"), and an optional navigation id navigationId (default null):

  1. Let unsafeNavigationStartTime be the unsafe shared current time.

  2. If resource is a URL, then set resource to a new request whose URL is resource.

  3. If resource is a request and historyHandling is "reload", then set resource's reload-navigation flag.

  4. If navigationId is null:

    1. historyHandling is "reload", and browingContext's active document's navigation id is not null, let navigationId be browingContext's active document's navigation id. Otherwise let navigation id be the result of generating a random UUID. [UUID]

  5. If browsingContext's active document's unload counter is greater than 0, then invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is resource's url, and return.

  6. If historyHandling is "default", resource is a request, and either resource's URL equals browsingContext's active document's URL or resource's URL's scheme is "javascript", then set historyHandling to "replace".

  7. Let incumbentNavigationOrigin be the origin of the incumbent settings object, or if no script was involved, the origin of the node document of the element that initiated the navigation.

  8. Let initiatorPolicyContainer be a clone of the source browsing context's active document's policy container.

  9. If resource is a request, then set resource's policy container to initiatorPolicyContainer.

  10. Cancel any preexisting but not yet mature attempt to navigate browsingContext, including canceling any instances of the fetch algorithm started by those attempts. If one of those attempts has already created and initialized a new Document object, abort that Document also. (Navigation attempts that have matured already have session history entries, and are therefore handled during the update the session history with the new page algorithm, later.)

  11. Let unloadPromptResult be the result of calling prompt to unload with the active document of browsingContext.

    If this instance of the navigation algorithm gets canceled while this step is running, the prompt to unload algorithm must nonetheless be run to completion.

  12. Switch on unloadPromptResult:

    "no-prompt"
    Do nothing.
    "confirm"
    Set unsafeNavigationStartTime to the unsafe shared current time.
    "refuse"
    Return a new WebDriver BiDi navigation status whose id is navigationId and status is "canceled".
  13. Abort the active document of browsingContext.

  14. If browsingContext is a child browsing context, then put it in the delaying load events mode.

    The user agent must take this child browsing context out of the delaying load events mode when this navigation algorithm later matures, or when it terminates (whether due to having run all the steps, or being canceled, or being aborted), whichever happens first.

  15. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and browsingContext's container.

  16. Let allowedToDownload be the result of running the allowed to download algorithm given the source browsing context and browsingContext.

  17. Let hasTransientActivation be true if the source browsing context's active window has transient activation; otherwise false.

  18. Let navigationStatus be

  19. Invoke WebDriver BiDi navigation started with browsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "pending".

  20. Return, and continue running these steps in parallel.

  21. This is the step that attempts to obtain resource, if necessary. Jump to the first appropriate substep:

    If resource is a response
    1. Assert: browsingContext is not a top-level browsing context.

    2. Let finalSandboxFlags be the union of browsingContext's sandboxing flags and resource's forced sandboxing flag set.

    3. Let responseOrigin be the result of determining the origin given browsingContext, resource's url, finalSandboxFlags, and incumbentNavigationOrigin.

    4. Let coop be a new cross-origin opener policy.

    5. Let coopEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is false, would need a browsing context group switch due to report-only is false, url is resource's url, origin is responseOrigin, cross-origin opener policy is coop, and current context is navigation source is false.

    6. Let policyContainer be the result of determining navigation params policy container given resource's url, historyPolicyContainer, initiatorPolicyContainer, browsingContext's parent browsing context's active document's policy container, and null.

    7. Let navigationParams be a new navigation params whose id is navigationId, request is null, response is resource, origin is responseOrigin, policy container is policyContainer, final sandboxing flag set is finalSandboxFlags, cross-origin opener policy is coop, COOP enforcement result is coopEnforcementResult, reserved environment is null, browsing context is browsingContext, history handling is historyHandling, unsafe start time is unsafeNavigationStartTime, and has cross-origin redirects is false.

    8. Run process a navigate response with navigationType, allowedToDownload, hasTransientActivation, and navigationParams.

    If resource is a request whose URL's scheme is "javascript"

    Queue a global task on the DOM manipulation task source given browsingContext's active window to run these steps:

    1. Let response be the result of executing a javascript: URL request given resource, browsingContext, and incumbentNavigationOrigin.

    2. Let finalSandboxFlags be the union of browsingContext's sandboxing flags and response's forced sandboxing flag set.

    3. Let coopEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is false, would need a browsing context group switch due to report-only is false, url is resource's URL, origin is browsingContext's active document's origin, cross-origin opener policy is browsingContext's active document's cross-origin opener policy, and current context is navigation source is false.

    4. Let navigationParams be a new navigation params whose id is navigationId, request is resource, response is response, origin is browsingContext's active document's origin, policy container is browsingContext's active document's policy container, final sandboxing flag set is finalSandboxFlags, cross-origin opener policy is browsingContext's active document's cross-origin opener policy, COOP enforcement result is coopEnforcementResult, reserved environment is null, browsing context is browsingContext, history handling is historyHandling, unsafe start time is unsafeNavigationStartTime, and has cross-origin redirects is false.

    5. Run process a navigate response with navigationType, allowedToDownload, hasTransientActivation, and navigationParams.

    So for example a javascript: URL in an href attribute of an a element would only be evaluated when the link was followed, while such a URL in the src attribute of an iframe element would be evaluated in the context of the iframe's nested browsing context when the iframe is being set up. Once evaluated, its return value (if it was a string) would replace that browsing context's active document, thus also changing the corresponding Window object.

    If resource is a request whose URL's scheme is a fetch scheme

    Run process a navigate fetch given navigationId, resource, the source browsing context, browsingContext, navigationType, sandboxFlags, historyPolicyContainer, initiatorPolicyContainer, allowedToDownload, hasTransientActivation, incumbentNavigationOrigin, historyHandling, and unsafeNavigationStartTime.

    Otherwise, resource is a request whose URL's scheme is neither "javascript" nor a fetch scheme

    Run process a navigate URL scheme given resource's URL, browsingContext, sandboxFlags, and hasTransientActivation.

To process a navigate fetch, given a navigation id navigationId, request request, two browsing contexts sourceBrowsingContext and browsingContext, a string navigationType, a sandboxing flag set sandboxFlags, two policy containers historyPolicyContainer and initiatorPolicyContainer, a boolean allowedToDownload, a boolean hasTransientActivation, an origin incumbentNavigationOrigin, a history handling behavior historyHandling, and a number unsafeNavigationStartTime:

  1. Let response be null.

  2. Set request's client to sourceBrowsingContext's active document's relevant settings object, destination to "document", mode to "navigate", credentials mode to "include", use-URL-credentials flag, redirect mode to "manual", and replaces client id to browsingContext's active document's relevant settings object's id.

  3. If hasTransientActivation is true, then set request's user-activation to true.

  4. If browsingContext's container is non-null:

    1. If the browsingContext's container has a browsing context scope origin, then set request's origin to that browsing context scope origin.

    2. Set request's destination to browsingContext's container's local name.

  5. Let responseOrigin be null.

  6. Let currentContextIsSource be the result of whether browsingContext's active document is same origin with sourceBrowsingContext's active document.

  7. Let coopEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is false, would need a browsing context group switch due to report-only is false, url is browsingContext's active document's url, origin is browsingContext's active document's origin, cross-origin opener policy is browsingContext's active document's cross-origin opener policy, and current context is navigation source is currentContextIsSource.

  8. Let finalSandboxFlags be an empty sandboxing flag set.

  9. Let responseCOOP be a new cross-origin opener policy.

  10. Let locationURL be null.

  11. Let currentURL be request's current URL.

  12. Let hasCrossOriginRedirects be false.

  13. While true:

    1. If locationURL is non-null, then:

      1. If locationURL's origin is not the same as currentURL's origin, then set hasCrossOriginRedirects to true.

      2. Set currentURL to locationURL.

    2. If request's reserved client is not null and currentURL's origin is not the same as request's reserved client's creation URL's origin, then:

      1. Run the environment discarding steps for request's reserved client.

      2. Set request's reserved client to null.

    3. If request's reserved client is null, then:

      1. Let topLevelCreationURL be currentURL.

      2. Let topLevelOrigin be null.

      3. If browsingContext is not a top-level browsing context, then:

        1. Let parentEnvironment be browsingContext's container's relevant settings object.

        2. Set topLevelCreationURL to parentEnvironment's top-level creation URL and topLevelOrigin to parentEnvironment's top-level origin.

      4. Set request's reserved client to a new environment whose id is a unique opaque string, target browsing context is browsingContext, creation URL is currentURL, top-level creation URL is topLevelCreationURL, and top-level origin is topLevelOrigin.

        The created environment's active service worker is set in the Handle Fetch algorithm during the fetch if the request URL matches a service worker registration. [SW]

    4. If the result of Should navigation request of type be blocked by Content Security Policy? given request and navigationType is "Blocked", then set response to a network error and break. [CSP]

    5. Otherwise:

      1. If response is null, fetch request.

      2. Otherwise, perform HTTP-redirect fetch using request and response.

      3. Wait for the task on the networking task source to process response and set response to the result.

      4. Set finalSandboxFlags to the union of browsingContext's sandboxing flags and response's forced sandboxing flag set.

      5. Set responseOrigin to the result of determining the origin given browsingContext, request's URL, finalSandboxFlags, and incumbentNavigationOrigin.

      6. If browsingContext is a top-level browsing context, then:

        1. Set responseCOOP to the result of obtaining a cross-origin opener policy given response and request's reserved client.

        2. Set coopEnforcementResult to the result of enforcing the response's cross-origin opener policy given browsingContext, request's URL, responseOrigin, responseCOOP, coopEnforcementResult and request's referrer.

        3. If sandboxFlags is not empty and responseCOOP's value is not "unsafe-none", then set response to an appropriate network error and break.

          This results in a network error as one cannot simultaneously provide a clean slate to a response using cross-origin opener policy and sandbox the result of navigating to that response.

      7. If response is not a network error, browsingContext is a child browsing context, and the result of performing a cross-origin resource policy check with browsingContext's container document's origin, browsingContext's container document's relevant settings object, request's destination, response, and true is blocked, then set response to a network error and break.

        Here we're running the cross-origin resource policy check against the parent browsing context rather than sourceBrowsingContext. This is because we care about the same-originness of the embedded content against the parent context, not the navigation source.

      8. Set locationURL to response's location URL given currentURL's fragment.

      9. If locationURL is not a URL whose scheme is an HTTP(S) scheme, then break.

        Navigation handles redirects manually as navigation is the only place in the web platform that cares for redirects to mailto: URLs and such.

    By the end of this loop we will be in one of these scenarios:

    • response is a network error.

    • locationURL is failure, because of an unparseable `Location` header.

    • locationURL is null, because we successfully fetched a non-network error HTTP(S) response with no `Location` header.

    • locationURL is a URL with a non-HTTP(S) scheme.

  14. If locationURL is failure, then set response to a network error.

  15. Otherwise, if locationURL is a URL whose scheme is a fetch scheme or "javascript", then set response to a network error.

  16. Otherwise, if locationURL is a URL, then process a navigate URL scheme given locationURL, browsingContext, sandboxFlags, and hasTransientActivation, and return.

  17. Let responsePolicyContainer be the result of creating a policy container from a fetch response given response and request's reserved client.

  18. Let resultPolicyContainer be the result of determining navigation params policy container given response's URL, historyPolicyContainer, initiatorPolicyContainer, null, and responsePolicyContainer.

  19. Let navigationParams be a new navigation params whose id is navigationId, request is request, response is response, origin is responseOrigin, policy container is resultPolicyContainer, final sandboxing flag set is finalSandboxFlags, cross-origin opener policy is responseCOOP, COOP enforcement result is coopEnforcementResult, reserved environment is request's reserved client, browsing context is browsingContext, history handling is historyHandling, unsafe start time is unsafeNavigationStartTime, and has cross-origin redirects is hasCrossOriginRedirects.

  20. Run process a navigate response with navigationType, allowedToDownload, hasTransientActivation, and navigationParams.

To process a navigate response, given a string navigationType, a boolean allowedToDownload, a boolean hasTransientActivation, and a navigation params navigationParams:

  1. Let response be navigationParams's response.

  2. Let browsingContext be navigationParams's browsing context.

  3. Let failure be false.

  4. If response is a network error, then set failure to true.

    Otherwise, if the result of Should navigation response to navigation request of type in target be blocked by Content Security Policy? given navigationParams's request, response, navigationParams's policy container's CSP list, navigationType, and browsingContext is "Blocked", then set failure to true. [CSP]

    Otherwise, if navigationParams's reserved environment is non-null and the result of checking a navigation response's adherence to its embedder policy given response, browsingContext, and navigationParams's policy container's embedder policy is false, then set failure to true.

    Otherwise, if the result of checking a navigation response's adherence to `X-Frame-Options` given response, browsingContext, and navigationParams's origin is false, then set failure to true.

  5. If failure is true, then:

    1. Display the inline content with an appropriate error shown to the user given browsingContext.

    2. Run the environment discarding steps for navigationParams's reserved environment.

    3. Invoke WebDriver BiDi navigation failed with browsingContext and a new WebDriver BiDi navigation status whose id is navigationParams's id, status is "canceled", and url is response's URL.

    4. Return.

    This is where the network errors defined and propagated by Fetch, such as DNS or TLS errors, end up being displayed to users. [FETCH]

  6. If response's status is 204 or 205, then return.

  7. If response has a `Content-Disposition` header specifying the attachment disposition type, then:

    1. If allowedToDownload is true, then handle response as a download.

    2. Invoke WebDriver BiDi download started with browsingContext and a new WebDriver BiDi navigation status whose id is navigationParams's id, status is "complete", and url is response's URL.

    3. Return.

  8. Let type be the computed type of response.

  9. If the user agent has been configured to process resources of the given type using some mechanism other than rendering the content in a browsing context, then skip this step. Otherwise, if the type is one of the following types, jump to the appropriate entry in the following list, and process response as described there:

    an HTML MIME type
    Follow the steps given in the HTML document section providing navigationParams. Once the steps have completed, return.
    an XML MIME type that is not an explicitly supported XML MIME type
    Follow the steps given in the XML document section providing navigationParams and type. Once the steps have completed, return.
    a JavaScript MIME type
    a JSON MIME type that is not an explicitly supported JSON MIME type
    "text/css"
    "text/plain"
    "text/vtt"
    Follow the steps given in the plain text file section providing navigationParams and type. Once the steps have completed, return.
    "multipart/x-mixed-replace"
    Follow the steps given in the multipart/x-mixed-replace section providing navigationParams. Once the steps have completed, return.
    A supported image, video, or audio type
    Follow the steps given in the media section providing navigationParams and type. Once the steps have completed, return.
    "application/pdf"
    "text/pdf"

    If the user agent's PDF viewer supported is true, then either follow the steps given in the plugin section providing navigationParams and type, or display the inline content given browsingContext. Once the steps have completed, return.

    See issue #6003 for discussion on picking one of these two behaviors to standardize.

    Otherwise, proceed onward.

    An explicitly supported XML MIME type is an XML MIME type for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in browsingContext, or a separate application), or one for which the user agent has dedicated processing rules (e.g., a web browser with a built-in Atom feed viewer would be said to explicitly support the application/atom+xml MIME type), or one for which the user agent has a dedicated handler.

    An explicitly supported JSON MIME type is a JSON MIME type for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in browsingContext, or a separate application), or one for which the user agent has dedicated processing rules, or one for which the user agent has a dedicated handler.

  10. Otherwise, the document's type is such that the resource will not affect browsingContext, e.g., because the resource is to be handed to an external application or because it is an unknown type that will be processed as a download. Hand-off to external software given response, browsingContext, navigationParams's final sandboxing flag set, and hasTransientActivation.

To process a navigate URL scheme, given a URL url, a browsing context browsingContext, a sandboxing flag set sandboxFlags, and a boolean hasTransientActivation:

  1. If url is to be handled using a mechanism that does not affect browsingContext, e.g., because url's scheme is handled externally, then hand-off to external software given url, browsingContext, sandboxFlags, and hasTransientActivation.

  2. Otherwise, url is to be handled by displaying some sort of inline content, e.g., an error message because the specified scheme is not one of the supported protocols, or an inline prompt to allow the user to select a registered handler for the given scheme. Display the inline content given browsingContext.

    In the case of a registered handler being used, navigate will be invoked with a new URL.

To hand-off to external software given a URL or response resource, a browsing context browsingContext, a sandboxing flag set sandboxFlags, and a boolean hasTransientActivation, user agents should:

  1. If browsingContext is not a top-level browsing context, and none of:

    hold, then return without invoking the external software package.

    Navigation inside an iframe toward external software can be seen by users as a new popup or a new top-level navigation. Therefore, we enforcing sandbox flags appropriately.

  2. Perform the appropriate handoff of resource while attempting to mitigate the risk that this is an attempt to exploit the target software. For example, user agents could prompt the user to confirm that the source browsing context's active document's origin is to be allowed to invoke the external software in question. In particular, if hasTransientActivation is false, then the user agent should not invoke the external software package without prior user confirmation.

    For example, there could be a vulnerability in the target software's URL handler which a hostile page would attempt to exploit by tricking a user into clicking a link.

To execute a javascript: URL request, given a request request, a browsing context browsingContext, and an origin initiatorOrigin:

  1. Let response be a response whose status is 204.

  2. If both of the following are true:

    then:

    1. Let urlString be the result of running the URL serializer on request's URL.

    2. Let encodedScriptSource be the result of removing the leading "javascript:" from urlString.

    3. Let scriptSource be the UTF-8 decoding of the percent-decoding of encodedScriptSource.

    4. Append browsingContext's active document's URL to request's URL list.

    5. Let settings be browsingContext's active document's relevant settings object.

    6. Let baseURL be settings's API base URL.

    7. Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.

    8. Let evaluationStatus be the result of running the classic script script.

    9. Let result be undefined if evaluationStatus is an abrupt completion or evaluationStatus.[[Value]] is empty, or evaluationStatus.[[Value]] otherwise.

    10. If Type(result) is String, then set response to a response whose header list is « (`Content-Type`, `text/html;charset=utf-8`) », and whose body is the result of UTF-8 encoding result.

      The encoding to UTF-8 means that unpaired surrogates will not roundtrip, once the HTML parser decodes the response body.

  3. Return response.

In addition to the specific issues linked above, javascript: URLs have a dedicated label on the issue tracker documenting various problems with their specification.


Some of the sections below, to which the above algorithm defers in certain cases, use the following steps to create and initialize a Document object, given a type type, content type contentType, and navigation params navigationParams:

  1. Let browsingContext be the result of the obtaining a browsing context to use for a navigation response given navigationParams's browsing context, navigationParams's final sandboxing flag set, navigationParams's cross-origin opener policy, and navigationParams's COOP enforcement result.

  2. Let permissionsPolicy be the result of creating a permissions policy from a response given browsingContext, 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 browsingContext'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.

  3. Let creationURL be navigationParams's response's URL.

  4. If navigationParams's request is non-null, then set creationURL to navigationParams's request's current URL.

  5. If browsingContext is still on its initial about:blank Document, and navigationParams's history handling is "replace", and browsingContext's active document's origin is same origin-domain with navigationParams's origin, then do nothing.

    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.

  6. Otherwise:

    1. Let oacHeader be the result of getting a structured field value given `Origin-Agent-Cluster` and "item" from response's header list.

    2. Let requestsOAC be true if oacHeader is not null and oacHeader[0] is the boolean true; otherwise false.

    3. If navigationParams's reserved environment is a non-secure context, then set requestsOAC to false.

    4. Let agent be the result of obtaining a similar-origin window agent given navigationParams's origin, browsingContext's group, and requestsOAC.

    5. Let realm execution context be the result of creating a new JavaScript 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.

    6. Let topLevelCreationURL be creationURL.

    7. Let topLevelOrigin be navigationParams's origin.

    8. If browsingContext is not a top-level browsing context, then:

      1. Let parentEnvironment be browsingContext's container's relevant settings object.

      2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.

      3. Set topLevelOrigin to parentEnvironment's top-level origin.

    9. Set up a window environment settings object with creationURL, realm execution context, 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.

  7. Let loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling coarsen time with navigationParams's unsafe start time and document's relevant settings object's cross-origin isolated capability.

  8. Let document be a new Document, whose type is type, content type is contentType, origin is navigationParams's origin, policy container is navigationParams's policy container, permissions policy is permissionsPolicy, active sandboxing flag set is navigationParams's final sandboxing flag set, and cross-origin opener policy is navigationParams's cross-origin opener policy, load timing info is loadTimingInfo, and navigation id is navigationParams's id.

    The new Window's associated Document is set to document later, when the caller of this algorithm updates the session history with the new page. That algorithm sets the active document as part of its larger role of synchronizing the Window, Document, browsing context, and session history.

  9. Set document's URL to creationURL.

  10. Set document's current document readiness to "loading".

  11. Run CSP initialization for a Document given document. [CSP]

  12. If navigationParams's request is non-null, then:

    1. Set document's referrer to the empty string.

    2. Let referrer be navigationParams's request's referrer.

    3. 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.

  13. Let historyHandling be navigationParams's history handling.

  14. Let navigationType be the result of switching on navigationParams's history handling:

    "default"
    "replace"
    "navigate"
    "reload"
    "reload"
    "entry update"
    "back_forward"
  15. Let redirectCount be 0 if navigationParams's has cross-origin redirects is true; otherwise navigationParams's request's redirect count.

  16. Create the navigation timing entry for document, with navigationParams's response's timing info, redirectCount, navigationType, and navigationParams's response's service worker timing info.

  17. If navigationParams's response has a `Refresh` header, then:

    1. Let value be the isomorphic decoding of the value of the header.

    2. 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.

  18. Return document.

In this example, the child document is not allowed to use PaymentRequest, despite being same origin-domain at the time the child document tries to use it. At the time the child document is initialized, only the parent document has set document.domain, and the child document has not.

<!-- https://foo.example.com/a.html -->
<!doctype html>
<script>
document.domain = 'example.com';
</script>
<iframe src=b.html></iframe>
<!-- https://bar.example.com/b.html -->
<!doctype html>
<script>
document.domain = 'example.com'; // This happens after the document is initialized
new PaymentRequest(); // Not allowed to use
</script>

In this example, the child document is allowed to use PaymentRequest, despite not being same origin-domain at the time the child document tries to use it. At the time the child document is initialized, none of the documents have set document.domain yet so same origin-domain falls back to a normal same origin check.

<!-- https://example.com/a.html -->
<!doctype html>
<iframe src=b.html></iframe>
<!-- The child document is now initialized, before the script below is run. -->
<script>
document.domain = 'example.com';
</script>
<!-- https://example.com/b.html -->
<!doctype html>
<script>
new PaymentRequest(); // Allowed to use
</script>

Some of the sections below, to which the above algorithm defers in certain cases, require the user agent to update the session history with the new page, given some navigation params navigationParams and a Document newDocument. When a user agent is required to do this, it must queue a global task on the networking task source, given the relevant global object of the Document object of the current entry (not the new one), to run the following steps:

  1. Let sessionHistory be navigationParams's browsing context's session history.

  2. Let unloadTimingInfo be a new document unload timing info.

  3. Let previousDocument be sessionHistory's current entry's document.

  4. Unload previousDocument with unloadTimingInfo.

    If this instance of the navigation algorithm is canceled while this step is running the unload a document algorithm, then the unload a document algorithm must be allowed to run to completion, but this instance of the navigation algorithm must not run beyond this step. (In particular, for instance, the cancelation of this algorithm does not abort any event dispatch or script execution occurring as part of unloading the document or its descendants.)

  5. If navigationParams's has cross-origin redirects is false, and newDocument's origin is the same as previousDocument's origin, then set newDocument's previous document unload timing to unloadTimingInfo.

  6. Switch on navigationParams's history handling:

    "entry update"
    "reload"
    1. Let oldDocument be sessionHistory's current entry's document.

    2. For each entry of sessionHistory: if entry's document is oldDocument, then set entry's document to newDocument.

    3. Traverse the history to sessionHistory's current entry with historyHandling set to navigationParams's history handling.

    "replace"
    1. Let newEntry be a new session history entry whose URL is newDocument's URL and document is newDocument.

      Some browsers copy over the serialized state sessionHistory's current entry in cases where its URL equals that of newDocument, but this is inconsistent. See issue #6213 for more discussion on this.

    2. If newDocument's URL requires storing the policy container in history, set newEntry's policy container to navigationParams's policy container.

    3. Insert newEntry into sessionHistory after its current entry.

    4. Traverse the history to newEntry with historyHandling set to "replace".

    "default"
    1. Remove all the entries in sessionHistory after its current entry. (If the current entry is the last entry in the session history, then no entries are removed.)

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

    2. Let newEntry be a new session history entry whose URL is newDocument's URL and document is newDocument.

    3. If newDocument's URL requires storing the policy container in history, then set newEntry's policy container to navigationParams's policy container.

    4. Append newEntry to sessionHistory.

    5. Traverse the history to newEntry.

  7. The navigation algorithm has now matured.

  8. Try to scroll to the fragment for newDocument.

To try to scroll to the fragment for a Document document, perform the following steps in parallel:

  1. Wait for an implementation-defined amount of time. (This is intended to allow the user agent to optimize the user experience in the face of performance concerns.)

  2. Queue a global task on the networking task source given document's relevant global object to run these steps:

    1. If document has no parser, or its parser has stopped parsing, or the user agent has reason to believe the user is no longer interested in scrolling to the fragment, then abort these steps.

    2. Scroll to the fragment given in document's URL. If this does not find an indicated part of the document, then try to scroll to the fragment for document.

7.11.2 Page load processing model for HTML files

When an HTML document is to be loaded, given navigation params navigationParams, the user agent must queue a task on the networking task source to:

  1. Let document be the result of creating and initializing a Document object given "html", "text/html", and navigationParams.

  2. Create an HTML parser and associate it with the document. Each task that the networking task source places on the task queue while fetching runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

    The input byte stream converts bytes into characters for use in the tokenizer. This process relies, in part, on character encoding information found in the real Content-Type metadata of the resource; the computed type is not used for this purpose.

When no more bytes are available, the user agent must queue a global task on the networking task source given the newly-created Document's relevant global object for the parser to process the implied EOF character, which eventually causes a load event to be fired.

After creating the Document object, but before any script execution, certainly before the parser stops, the user agent must update the session history with the new page given navigationParams and the newly-created Document.

7.11.3 Page load processing model for XML files

When faced with displaying an XML file inline, provided navigation params navigationParams and a string type, user agents must follow the requirements defined in XML and Namespaces in XML, XML Media Types, DOM, and other relevant specifications to create and initialize a Document object document, given "xml", type, and navigationParams. They must also create a corresponding XML parser. [XML] [XMLNS] [RFC7303] [DOM]

At the time of writing, the XML specification community had not actually yet specified how XML and the DOM interact.

The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification, are the ones that must be used when determining the character encoding according to the rules given in the above specifications. Once the character encoding is established, the document's character encoding must be set to that character encoding.

Then, with document, the user agent must update the session history with the new page given navigationParams and document. User agents may do this before the complete document has been parsed (thus achieving incremental rendering), and must do this before any scripts are to be executed.

Once parsing is complete, the user agent must set document's navigation id to null.

For HTML documents this is reset when parsing is complete, after firing the load event.

Error messages from the parse process (e.g., XML namespace well-formedness errors) may be reported inline by mutating the Document.

7.11.4 Page load processing model for text files

When a plain text document is to be loaded, provided navigation params navigationParams and a string type, the user agent must queue a task on the networking task source to:

  1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParams.

  2. Set document's parser cannot change the mode flag to true.

  3. Set document's mode to "no-quirks".

  4. Create an HTML parser and associate it with the document. Act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, and switch the HTML parser's tokenizer to the PLAINTEXT state. Each task that the networking task source places on the task queue while fetching runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

The rules for how to convert the bytes of the plain text document into actual characters, and the rules for actually rendering the text to the user, are defined by the specifications for the computed MIME type of the resource (i.e., type).

The document's character encoding must be set to the character encoding used to decode the document.

When no more bytes are available, the user agent must queue a global task on the networking task source given the newly-created Document's relevant global object for the parser to process the implied EOF character, which eventually causes a load event to be fired.

After creating the Document object, but potentially before the page has finished parsing, the user agent must update the session history with the new page given navigationParams and the newly-created Document.

User agents may add content to the head element of the Document, e.g., linking to a style sheet, providing script, or giving the document a title.

In particular, if the user agent supports the Format=Flowed feature of RFC 3676 then the user agent would need to apply extra styling to cause the text to wrap correctly and to handle the quoting feature. This could be performed using, e.g., a CSS extension.

7.11.5 Page load processing model for multipart/x-mixed-replace resources

When a resource with the type multipart/x-mixed-replace is to be loaded in a browsing context, the user agent must parse the resource using the rules for multipart types. [RFC2046]

This algorithm is passed navigation params, but it's unclear how exactly to use them.

For each body part obtained from the resource, the user agent must run process a navigate response using the new body part and the same browsing context, with history handling set to "replace" if a previous body part from the same resource resulted in a creating and initializing a Document object, and otherwise using the same setup as the navigate attempt that caused this section to be invoked in the first place.

For the purposes of algorithms processing these body parts as if they were complete stand-alone resources, the user agent must act as if there were no more bytes for those resources whenever the boundary following the body part is reached.

Thus, load events (and for that matter unload events) do fire for each body part loaded.

7.11.6 Page load processing model for media

When an image, video, or audio resource is to be loaded, provided navigation params navigationParams and a string type, the user agent should:

  1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParams.

  2. Set document's mode to "no-quirks".

  3. Append an html element to document.

  4. Append a head element to the html element.

  5. Append a body element to the html element.

  6. Append an element host element for the media, as described below, to the body element.

  7. Set the appropriate attribute of the element host element, as described below, to the address of the image, video, or audio resource.

The element host element to create for the media is the element given in the table below in the second cell of the row whose first cell describes the media. The appropriate attribute to set is the one given by the third cell in that same row.

Type of media Element for the media Appropriate attribute
Image img src
Video video src
Audio audio src

Then, the user agent must act as if it had stopped parsing.

After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page given navigationParams and the newly-created Document.

User agents may add content to the head element of the Document, or attributes to the element host element, e.g., to link to a style sheet, to provide a script, to give the document a title, or to make the media autoplay.

7.11.7 Page load processing model for content that uses plugins

When a resource that requires an external resource to be rendered is to be loaded, provided navigation params navigationParams and a string type, the user agent should:

  1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParmas.

  2. Set document's mode to "no-quirks".

  3. Mark document as being a plugin document

  4. Append an html element to document.

  5. Append a head element to the html element.

  6. Append a body element to the html element.

  7. Append an embed to the body element.

  8. Set the src attribute of the embed element to the address of the resource.

The term plugin document is used by Content Security Policy as part of the mechanism that ensures iframes can't be used to evade plugin-types directives. [CSP]

Then, the user agent must act as if it had stopped parsing.

After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page given navigationParams and the newly-created Document.

User agents may add content to the head element of the Document, or attributes to the embed element, e.g. to link to a style sheet or to give the document a title.

If the Document's active sandboxing flag set has its sandboxed plugins browsing context flag set, the synthesized embed element will fail to render the content.

7.11.8 Page load processing model for inline content that doesn't have a DOM

When the user agent is to display a user agent page inline, provided a browsing context browsingContext, the user agent should:

  1. Let navigationParams be a new navigation params whose request is null, response is null, origin is a new opaque origin, final sandboxing flag set is an empty set, cross-origin opener policy is a new cross-origin opener policy, COOP enforcement result is a new cross-origin opener policy enforcement result, reserved environment is null, unsafe start time is the unsafe shared current time, and browsing context is browsingContext.

    The algorithm called in the next step is not prepared to deal with a null response. Probably we should synthesize one instead.

  2. Let document be the result of creating and initializing a Document object given "html", "text/html", and navigationParams.

  3. Set document's mode to "no-quirks".

  4. Either associate document with a custom rendering that is not rendered using the normal Document rendering rules, or mutate document until it represents the content the user agent wants to render.

Once the page has been set up, the user agent must act as if it had stopped parsing.

After creating the Document object, but potentially before the page has been completely set up, the user agent must update the session history with the new page given navigationParams and the newly-created Document.

7.11.9 Navigating to a fragment

To navigate to a fragment given a browsing context browsingContext, a URL url, a history handling behavior historyHandling, and a navigation id navigationId:

  1. If historyHandling is not "replace", then remove all the entries in browsingContext's session history after the current entry. (If the current entry is the last entry in the session history, then no entries are removed.)

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

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

  3. Append a new session history entry to the session history whose URL is url, document is the current entry's document, policy container is the current entry's policy-container and scroll restoration mode is the current entry's scroll restoration mode.

  4. Traverse the history to the new entry, with historyHandling set to historyHandling and with nonBlockingEvents set to true. This will scroll to the fragment given in what is now the document's URL.

  5. Invoke WebDriver BiDi fragment navigated with browsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "complete".

If the scrolling fails because the relevant ID has not yet been parsed, then the original navigation algorithm will take care of the scrolling instead, as the last few steps of its update the session history with the new page algorithm.


When the user agent is required to scroll to the fragment and the indicated part of the document, if any, is being rendered, the user agent must either change the scrolling position of the document using the following algorithm, or perform some other action such that the indicated part of the document is brought to the user's attention. If there is no indicated part, or if the indicated part is not being rendered, then the user agent must do nothing. The aforementioned algorithm is as follows:

  1. If there is no indicated part of the document, set the Document's target element to null.

  2. If the indicated part of the document is the top of the document, then:

    1. Set the Document's target element to null.

    2. Scroll to the beginning of the document for the Document. [CSSOMVIEW]

  3. Otherwise:

    1. Let target be element that is the indicated part of the document.

    2. Set the Document's target element to target.

    3. Run the ancestor details revealing algorithm on target.

    4. Scroll target into view, with behavior set to "auto", block set to "start", and inline set to "nearest". [CSSOMVIEW]

    5. Run the focusing steps for target, with the Document's viewport as the fallback target.

    6. Move the sequential focus navigation starting point to target.

The indicated part of the document is the one that the fragment, if any, identifies. The semantics of the fragment in terms of mapping it to a node is defined by the specification that defines the MIME type used by the Document (for example, the processing of fragments for XML MIME types is the responsibility of RFC7303). [RFC7303]

There is also a target element for each Document, which is used in defining the :target pseudo-class and is updated by the above algorithm. It is initially null.

For HTML documents (and HTML MIME types), the following processing model must be followed to determine what the indicated part of the document is.

  1. Let fragment be the document's URL's fragment.

  2. If fragment is the empty string, then the indicated part of the document is the top of the document; return.

  3. If find a potential indicated element with fragment returns non-null, then the return value is the indicated part of the document; return.

  4. Let fragmentBytes be the result of percent-decoding fragment.

  5. Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes.

  6. If find a potential indicated element with decodedFragment returns non-null, then the return value is the indicated part of the document; return.

  7. If decodedFragment is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; return.

  8. There is no indicated part of the document.

To find a potential indicated element given a string fragment, run these steps:

  1. If there is an element in the document tree that has an ID equal to fragment, then return the first such element in tree order.

  2. If there is an a element in the document tree that has a name attribute whose value is equal to fragment, then return the first such element in tree order.

  3. Return null.

7.11.10 History traversal

To traverse the history to a session history entry entry, with an optional history handling behavior historyHandling (default "default"), an optional boolean nonBlockingEvents (default false), and an optional boolean explicitHistoryNavigation (default false):

This algorithm is not just invoked when explicitly going back or forwards in the session history — it is also invoked in other situations, for example when navigating a browsing context, as part of updating the session history with the new page.

  1. If entry's document is null, then:

    1. Assert: historyHandling is "default".

    2. Let request be a new request whose URL is entry's URL.

    3. If explicitHistoryNavigation is true, then set request's history-navigation flag.

    4. Navigate the browsing context to request with historyHandling set to "entry update" and with historyPolicyContainer set to entry's policy container. The navigation must be done using the same source browsing context as was used the first time entry was created.

      The "navigate" algorithm reinvokes this "traverse" algorithm to complete the traversal, at which point entry's document is non-null.

      If the resource was obtained using a non-idempotent action, for example a POST form submission, or if the resource is no longer available, for example because the computer is now offline and the page wasn't cached, navigating to it again might not be possible. In this case, the navigation will result in a different page than previously; for example, it might be an error message explaining the problem or offering to resubmit the form.

    5. Return.

  2. Save persisted state to the current entry.

  3. Let newDocument be entry's document.

  4. If newDocument is different than the current entry's document, or historyHandling is "entry update" or "reload", then:

    1. If newDocument's suspended timer handles is not empty:

      1. Assert: newDocument's suspension time is not zero.

      2. Let suspendDuration be the current high resolution time minus newDocument's suspension time.

      3. Let activeTimers be newDocument's relevant global object's map of active timers.

      4. For each handle in newDocument's suspended timer handles, if activeTimers[handle] exists, then increase activeTimers[handle] by suspendDuration.

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

    3. If newDocument's origin is not same origin with the current entry's document's origin, then:

      1. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the active document and that are contiguous with the current entry.

      2. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to the current browsing context name.

      3. If the browsing context is a top-level browsing context, but not an auxiliary browsing context whose disowned is false, then set the browsing context's name to the empty string.

    4. Set the active document of the browsing context to newDocument.

    5. If entry's browsing context name is not null, then:

      1. Set the browsing context's name to entry's browsing context name.

      2. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the new active document's origin and that are contiguous with entry.

      3. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to null.

    6. If newDocument has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.

    7. If newDocument's current document readiness "complete", then queue a global task on the DOM manipulation task source given newDocument's relevant global object to run the following steps:

      1. If newDocument's page showing flag is true, then abort these steps.

      2. Set newDocument's page showing flag to true.

      3. Update the visibility state of newDocument to "hidden".

      4. Fire a page transition event named pageshow at newDocument's relevant global object with true.

  5. Set newDocument's URL to entry's URL.

  6. Set newDocument's is initial about:blank to false.

    The spec currently allows keeping the initial about:blank Document in session history, but this is probably a bug: see issue #6491 (and especially this comment). If we fix that then we can convert this step into an assert that newDocument's is initial about:blank is false, i.e., an assert that we never traverse back to the initial about:blank Document.

  7. Let hashChanged be false, and let oldURL and newURL be null.

  8. If entry's URL's fragment is not identical to the current entry's URL's fragment, and entry's document equals the current entry's document, then set hashChanged to true, set oldURL to the current entry's URL, and set newURL to entry's URL.

  9. If historyHandling is "replace", then remove the entry immediately before entry in the session history.

  10. If entry's persisted user state is null, and its URL's fragment is non-null, then scroll to the fragment.

  11. Set the current entry to entry.

  12. Let targetRealm be the current Realm Record.

  13. Let state be null.

  14. If entry's serialized state is not null, then set state to StructuredDeserialize(entry's serialized state, targetRealm). If this throws an exception, catch it and ignore the exception.

  15. Set newDocument's History object's state to state.

  16. Let stateChanged be true if newDocument has a latest entry, and that entry is not entry; otherwise let it be false.

  17. Set newDocument's latest entry to entry.

  18. If nonBlockingEvents is false, then run the following steps immediately. Otherwise, queue a global task on the DOM manipulation task source given newDocument's relevant global object to run the following steps instead.

    1. If stateChanged is true, then fire an event named popstate at newDocument's relevant global object, using PopStateEvent, with the state attribute initialized to state.

    2. Restore persisted state from entry.

    3. If hashChanged is true, then fire an event named hashchange at the browsing context's active window, using HashChangeEvent, with the oldURL attribute initialized to oldURL and the newURL attribute initialized to newURL.

7.11.10.1 Persisted history entry state

To save persisted state to a session history entry entry:

  1. Set the scroll position data of entry to contain the scroll positions for all of entry's document's restorable scrollable regions.

  2. Optionally, update entry's persisted user state to reflect any state that the user agent wishes to persist, such as the values of form fields.

To restore persisted state from a session history entry entry:

  1. If entry's scroll restoration mode is "auto", then the user agent may use entry's scroll position data to restore the scroll positions of entry's document's restorable scrollable regions.

    The user agent not restoring scroll positions does not imply that scroll positions will be left at any particular value (e.g., (0,0)). The actual scroll position depends on the navigation type and the user agent's particular caching strategy. So web applications cannot assume any particular scroll position but rather are urged to set it to what they want it to be.

  2. Optionally, update other aspects of entry's document and its rendering, for instance values of form fields, that the user agent had previously recorded in entry's persisted user state.

    This can even include updating the dir attribute of textarea elements or input elements whose type attribute is in either the Text state or the Search state, if the persisted state includes the directionality of user input in such controls.

    Restoring the value of form controls as part of this process does not fire any input or change events, but can trigger the formStateRestoreCallback of form-associated custom elements.


The restorable scrollable regions of a Document document are document's viewport, and all of document's scrollable regions excepting any child browsing contexts of document.

Child browsing context scroll restoration is handled by the history entry for those browsing contexts' Documents.

7.11.10.2 The PopStateEvent interface

PopStateEvent

Support in all current engines.

Firefox4+Safari6+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS6+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
[Exposed=Window]
interface PopStateEvent : Event {
  constructor(DOMString type, optional PopStateEventInit eventInitDict = {});

  readonly attribute any state;
};

dictionary PopStateEventInit : EventInit {
  any state = null;
};
event.state

Returns a copy of the information that was provided to pushState() or replaceState().

The state attribute must return the value it was initialized to. It represents the context information for the event, or null, if the state represented is the initial state of the Document.

7.11.10.3 The HashChangeEvent interface

HashChangeEvent

Support in all current engines.

Firefox3.6+Safari5+Chrome8+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
[Exposed=Window]
interface HashChangeEvent : Event {
  constructor(DOMString type, optional HashChangeEventInit eventInitDict = {});

  readonly attribute USVString oldURL;
  readonly attribute USVString newURL;
};

dictionary HashChangeEventInit : EventInit {
  USVString oldURL = "";
  USVString newURL = "";
};
event.oldURL

HashChangeEvent/oldURL

Support in all current engines.

Firefox6+Safari5.1+Chrome8+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox AndroidYesSafari iOS6+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the URL of the session history entry that was previously current.

event.newURL

HashChangeEvent/newURL

Support in all current engines.

Firefox6+Safari5.1+Chrome8+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox AndroidYesSafari iOS6+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the URL of the session history entry that is now current.

The oldURL attribute must return the value it was initialized to. It represents context information for the event, specifically the URL of the session history entry that was traversed from.

The newURL attribute must return the value it was initialized to. It represents context information for the event, specifically the URL of the session history entry that was traversed to.

7.11.10.4 The PageTransitionEvent interface

PageTransitionEvent

Support in all current engines.

Firefox1.5+Safari5+Chrome4+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
[Exposed=Window]
interface PageTransitionEvent : Event {
  constructor(DOMString type, optional PageTransitionEventInit eventInitDict = {});

  readonly attribute boolean persisted;
};

dictionary PageTransitionEventInit : EventInit {
  boolean persisted = false;
};
event.persisted

PageTransitionEvent/persisted

Support in all current engines.

Firefox11+Safari5+Chrome4+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android14+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+

For the pageshow event, returns false if the page is newly being loaded (and the load event will fire). Otherwise, returns true.

For the pagehide event, returns false if the page is going away for the last time. Otherwise, returns true, meaning that the page might be reused if the user navigates back to this page (if the Document's salvageable state stays true).

Things that can cause the page to be unsalvageable include:

The persisted attribute must return the value it was initialized to. It represents the context information for the event.

To fire a page transition event named eventName at a Window window with a boolean persisted, fire an event named eventName at window, using PageTransitionEvent, with the persisted attribute initialized to persisted, the cancelable attribute intialized to true, the bubbles attribute initialized to true, and legacy target override flag set.

The values for cancelable and bubbles don't make any sense, since canceling the event does nothing and it's not possible to bubble past the Window object. They are set to true for historical reasons.

7.11.11 Loading documents

A Document has a completely loaded time (a time or null), which is initially null.

A Document is considered completely loaded if its completely loaded time is non-null.

To completely finish loading a Document document:

  1. Assert: document's browsing context is non-null.

  2. Set document's completely loaded time to the current time.

  3. Let container be document's browsing context's container.

    This will be null in the case where document is the initial about:blank Document in a frame or iframe, since at the point of browsing context creation which calls this algorithm, the container relationship has not yet been established. (That happens in a subsequent step of create a new nested browsing context.)

    The consequence of this is that the following steps do nothing, i.e., we do not fire an asynchronous load event on the container element for such cases. Instead, a synchronous load event is fired in a special initial-insertion case in the shared attribute processing steps for iframe and frame elements.

  4. If container is an iframe element, then queue an element task on the DOM manipulation task source given container to run the iframe load event steps given container.

  5. Otherwise, if container is non-null, then queue an element task on the DOM manipulation task source given container to fire an event named load at container.

7.11.12 Unloading documents

A Document has a salvageable state, which must initially be true, and a page showing flag, which must initially be false. The page showing flag is used to ensure that scripts receive pageshow and pagehide events in a consistent manner (e.g. that they never receive two pagehide events in a row without an intervening pageshow, or vice versa).

A Document has a DOMHighResTimeStamp suspension time, initially 0.

A Document has a list of suspended timer handles, initially empty.

Event loops have a termination nesting level counter, which must initially be 0.

Document objects have an unload counter, which is used to ignore certain operations while the below algorithms run. Initially, the counter must be set to zero.

To prompt to unload, given a Document object document and optionally a recursiveFlag, run these steps:

  1. Increase the event loop's termination nesting level by 1.

  2. Increase the document's unload counter by 1.

  3. Let event be the result of creating an event using BeforeUnloadEvent.

  4. Initialize event's type attribute to beforeunload and its cancelable attribute true.

  5. Dispatch event at document's relevant global object.

  6. Decrease the event loop's termination nesting level by 1.

  7. Let result be "no-prompt".

  8. If all of the following are true:

    then the user agent may ask the user to confirm that they wish to unload the document.

    The message shown to the user is not customizable, but instead determined by the user agent. In particular, the actual value of the returnValue attribute is ignored.

    The user agent is encouraged to avoid asking the user for confirmation if it judges that doing so would be annoying, deceptive, or pointless.

    If the user agent asks the user for confirmation, it must pause while waiting for the user's response.

    If the user confirmed the page navigation, then set result to "confirm"; otherwise return "refuse".

  9. If the recursiveFlag is not set, then:

    1. Let descendants be the list of the descendant browsing contexts of document.

    2. For each browsingContext in descendants:

      1. Let internalResult be the result of calling prompt to unload for browsingContext's active document with the recursiveFlag set.

      2. If internalResult is "refuse", then return internalResult.

      3. Otherwise, if internalResult is "confirm", set result to internalResult.

  10. Decrease the document's unload counter by 1.

  11. Return result.

To unload a Document document, given an optional recursiveFlag and a document unload timing info-or-null unloadTimingInfo (default null):

  1. Increase the event loop's termination nesting level by one.

  2. Increase document's unload counter by 1.

  3. If the user agent does not intend to keep document alive in a session history entry (such that it can be reused later on history traversal), set document's salvageable state to false.

  4. If document's page showing flag is true:

    1. Set document's page showing flag to false.

    2. Fire a page transition event named pagehide at document's relevant global object with document's salvageable state.

    3. Update the visibility state of newDocument to "hidden".

  5. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event start time to the current high resolution time given document's relevant global object.

  6. If document's salvageable state is false, then fire an event named unload at document's relevant global object, with legacy target override flag set.

  7. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event end time to the current high resolution time given document's relevant global object.

  8. Decrease the event loop's termination nesting level by one.

  9. Set document's suspension time to the current high resolution time.

  10. Set document's suspended timer handles to the result of getting the keys for the map of active timers.

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

  12. If the recursiveFlag is not set, then:

    1. Let descendants be the list of the descendant browsing contexts of document.

    2. For each browsingContext in descendants:

      1. Unload the active document of browsingContext with the recursiveFlag set.

      2. If the salvageable state of the active document of browsingContext is false, then set the salvageable state of document to false also.

    3. If document's salvageable state is false, then discarddocument.

  13. Decrease document's unload counter by 1.

This specification defines the following unloading document cleanup steps. Other specifications can define more. Given a Document document:

  1. Let window be document's relevant global object.

  2. For each WebSocket object webSocket whose relevant global object is window, make disappear webSocket.

    If this affected any WebSocket objects, then set document's salvageable state to false.

  3. If document's salvageable state is false, then:

    1. For each EventSource object eventSource whose relevant global object is equal to window, forcibly close eventSource.

    2. Clear window's map of active timers.

7.11.12.1 The BeforeUnloadEvent interface

BeforeUnloadEvent

Support in all current engines.

Firefox1.5+Safari7+Chrome30+
Opera17+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS7+Chrome Android30+WebView Android37+Samsung Internet3.0+Opera Android18+
[Exposed=Window]
interface BeforeUnloadEvent : Event {
  attribute DOMString returnValue;
};

There are no BeforeUnloadEvent-specific initialization methods.

The BeforeUnloadEvent interface is a legacy interface which allows prompting to unload to be controlled not only by canceling the event, but by setting the returnValue attribute to a value besides the empty string. Authors should use the preventDefault() method, or other means of canceling events, instead of using returnValue.

The returnValue attribute controls the process of prompting to unload. When the event is created, the attribute must be set to the empty string. On getting, it must return the last value it was set to. On setting, the attribute must be set to the new value.

This attribute is a DOMString only for historical reasons. Any value besides the empty string will be treated as a request to ask the user for confirmation.

7.11.13 Aborting a document load

To abort a Document document:

  1. Abort the active documents of every child browsing context. If this results in any of those Document objects having their salvageable state set to false, then set document's salvageable state to false also.

  2. Cancel any instances of the fetch algorithm in the context of document, discarding any tasks queued for them, and discarding any further data received from the network for them. If this resulted in any instances of the fetch algorithm being canceled or any queued tasks or any network data getting discarded, then set document's salvageable state to false.

  3. If document's navigation id is non-null, then:

    1. Invoke WebDriver BiDi navigation aborted with document's browsing context, and new WebDriver BiDi navigation status whose whose id is document's navigation id, status is "canceled", and url is document's URL.

    2. Set document's navigation id to null.

  4. If document has an active parser, then:

    1. Set document's active parser was aborted to true.

    2. Abort that parser.

    3. Set document's salvageable state to false.

User agents may allow users to explicitly invoke the stop document loading for a Document.

To stop document loading given a Document object document, run these steps:

  1. Let browsingContext be document's browsing context.

  2. If browsingContext's active document is not document, then return.

  3. If there is an existing attempt to navigate browsingContext and document's unload counter is 0, then cancel that navigation.

  4. Abort document.

7.11.14 The `X-Frame-Options` header

The `X-Frame-Options` HTTP response header is a legacy way of controlling whether and how a Document may be loaded inside of a child browsing context. It is obsoleted by the frame-ancestors CSP directive, which provides more granular control over the same situations. It was originally defined in HTTP Header Field X-Frame-Options, but the definition and processing model here supersedes that document. [CSP] [RFC7034]

In particular, HTTP Header Field X-Frame-Options specified an `ALLOW-FROM` variant of the header, but that is not to be implemented.

Per the below processing model, if both a CSP frame-ancestors directive and an `X-Frame-Options` header are used in the same response, then `X-Frame-Options` is ignored.

For web developers and conformance checkers, its value ABNF is:

X-Frame-Options = "DENY" / "SAMEORIGIN"

To check a navigation response's adherence to `X-Frame-Options`, given navigationParams navigationParams, a browsing context browsingContext, and an origin destinationOrigin:

  1. If browsingContext is not a child browsing context, then return true.

  2. For each policy of navigationParams's policy container's CSP list:

    1. If policy's disposition is not "enforce", then continue.

    2. If policy's directive set contains a frame-ancestors directive, then return true.

  3. Let rawXFrameOptions be the result of getting, decoding, and splitting `X-Frame-Options` from navigationParams's response's header list.

  4. Let xFrameOptions be a new set.

  5. For each value of rawXFrameOptions, append value, converted to ASCII lowercase, to xFrameOptions.

  6. If xFrameOptions's size is greater than 1, and xFrameOptions contains any of "deny", "allowall", or "sameorigin", then return false.

    The intention here is to block any attempts at applying `X-Frame-Options` which were trying to do something valid, but appear confused.

    This is the only impact of the legacy `ALLOWALL` value on the processing model.

  7. If xFrameOptions's size is greater than 1, then return true.

    This means it contains multiple invalid values, which we treat the same way as if the header was omitted entirely.

  8. If xFrameOptions[0] is "deny", then return false.

  9. If xFrameOptions[0] is "sameorigin", then:

    1. Let containerDocument be browsingContext's container document.

    2. While containerDocument is not null:

      1. If containerDocument's origin is not same origin with destinationOrigin, then return false.

      2. Let containerBC be containerDocument's browsing context.

      3. Set containerDocument to containerBC's container document, if containerBC is non-null; otherwise, null.

  10. Return true.

    If we've reached this point then we have a lone invalid value (which could potentially be one the legacy `ALLOWALL` or `ALLOW-FROM` forms). These are treated as if the header were omitted entirely.


The following table illustrates the processing of various values for the header, including non-conformant ones:

`X-Frame-Options`ValidResult
`DENY`embedding disallowed
`SAMEORIGIN`same-origin embedding allowed
`INVALID`embedding allowed
`ALLOWALL`embedding allowed
`ALLOW-FROM=https://example.com/`embedding allowed (from anywhere)

The following table illustrates how various non-conformant cases involving multiple values are processed:

`X-Frame-Options`Result
`SAMEORIGIN, SAMEORIGIN`same-origin embedding allowed
`SAMEORIGIN, DENY`embedding disallowed
`SAMEORIGIN,`embedding disallowed
`SAMEORIGIN, ALLOWALL`embedding disallowed
`SAMEORIGIN, INVALID`embedding disallowed
`ALLOWALL, INVALID`embedding disallowed
`ALLOWALL,`embedding disallowed
`INVALID, INVALID`embedding allowed

The same results are obtained whether the values are delivered in a single header whose value is comma-delimited, or in multiple headers.

7.11.15 The `Refresh` header

The `Refresh` HTTP response header is the HTTP-equivalent to a meta element with an http-equiv attribute in the Refresh state. It takes the same value and works largely the same. Its processing model is detailed in create and initialize a Document object.