1. 7.11 7.4 Browsing the web Navigation and session history
      1. 7.11.1 7.4.1 Navigating across documents Session history
        1. 7.11.2 7.4.1.1 Page load processing model for HTML files Session history entries
        2. 7.11.3 7.4.1.2 Page load processing model for XML files Document state
        3. 7.11.4 7.4.1.3 Page load processing model for text files Centralized modifications of session history
        4. 7.11.5 7.4.1.4 Page load processing model for multipart/x-mixed-replace resources Low-level operations on session history
      2. 7.11.6 7.4.2 Page load processing model for media Navigation
        1. 7.11.7 7.4.2.1 Page load processing model for content that uses plugins Supporting concepts
        2. 7.11.8 7.4.2.2 Page load processing model for inline content that doesn't have a DOM Beginning navigation
        3. 7.4.2.3 Ending navigation
          1. 7.4.2.3.1 Cross-document navigations
          2. 7.11.9 7.4.2.3.2 Navigating to a fragment Fragment navigations
          3. 7.11.10 7.4.2.3.3 History traversal Non-fetch schemes and external software
        4. 7.11.10.1 7.4.2.4 Persisted Preventing navigation
      3. 7.4.3 Reloading and traversing
      4. 7.4.4 Non-fragment synchronous "navigations"
      5. 7.4.5 Populating a session history entry state
        1. 7.11.10.2 7.4.5.1 The PopStateEvent interface usual case
        2. 7.11.10.3 7.4.5.2 The HashChangeEvent javascript: interface URL special case
      6. 7.11.10.4 7.4.6 The PageTransitionEvent interface Applying the history step
        1. 7.11.11 7.4.6.1 Loading documents Updating the traversable
        2. 7.11.12 7.4.6.2 Unloading documents Updating the document
        3. 7.4.6.3 Scrolling to a fragment
        4. 7.11.12.1 7.4.6.4 Persisted history entry state

Welcome to the dragon's maw. Navigation, session history, and the traversal through that session history are some of the most complex parts of this standard.

The BeforeUnloadEvent basic concept may not seem so difficult:

You can see some of the intertwined complexity peeking through here, in how traversal can cause a navigation (i.e., a network fetch to a stored URL), and how a navigation necessarily needs to interface with the session history list to ensure that when it finishes the user is looking at the right thing. But the real problems come in with the various edge cases and interacting web platform features:

In what follows, we have attempted to guide the reader through these complexities by appropriately cordoning them off into labeled sections and algorithms, and giving appropriate words of introduction where possible. Nevertheless, if you wish to truly understand navigation and session history, the usual advice will be invaluable.

7.11.13 7.4.1 Aborting Session history

7.4.1.1 Session history entries

A session history entry is a struct with the following items :

To get a session history entry 's document , return its document state 's document .


Serialized state is a serialization (via StructuredSerializeForStorage ) of an object representing a user interface state. We sometimes informally refer to "state objects", which are the objects representing user interface state supplied by the author, or alternately the objects created by deserializing (via StructuredDeserialize ) serialized state.

Pages can add serialized state to the session history. These are then deserialized and returned to the script when the user (or script) goes back in the history, thus enabling authors to use the "navigation" metaphor even in one-page applications.

Serialized state is intended to be used for two main purposes: first, storing a preparsed description of the state in the URL so that in the simple case an author doesn't have to do the parsing (though one would still need the parsing for handling URLs passed around by users, so it's only a minor optimization). Second, so that the author can store state that one wouldn't store in the URL because it only applies to the current Document instance and it would have to be reconstructed if a new Document were opened.

An example of the latter would be something like keeping track of the precise coordinate from which a popup div was made to animate, so that if the user goes back, it can be made to animate to the same location. Or alternatively, it could be used to keep a pointer into a cache of data that would be fetched from the server based on the information in the URL , so that when going back and forward, the information doesn't have to be fetched again.


A scroll restoration mode indicates whether the user agent should restore the persisted scroll position (if any) when traversing to an entry . A scroll restoration mode is one of the following:

" auto "
The user agent is responsible for restoring the scroll position upon navigation.
" manual "
The page is responsible for restoring the scroll position and the user agent does not attempt to do so automatically
7.11.14 7.4.1.2 Document state

Document state holds state inside a session history entry regarding how to present and, if necessary, recreate, a Document . It has:

User agents may destroy the documents of document states with non-null documents , as long as the Document is not fully active .

Apart from that restriction, this standard does not specify when user agents should destroy the document stored in a document state , versus keeping it cached.


A POST resource has:


A nested history has:

This will later contain ways to identify a nested navigable across reloads.



Several contiguous entries in a session history can share the same document state . This can occur when the initial entry is reached via normal navigation , and the following entry is added via history.pushState() . Or it can occur via navigation to a fragment .

All entries that share the same document state (and that are therefore merely different states of one particular document) are contiguous by construction.


A Document has a latest entry , a session history entry or null.

This is the entry that was most recently represented by a given Document . A single Document can represent many session history entries over time, as many contiguous session history entries can share the same document state as explained above.

7.11.15 7.4.1.3 Centralized modifications of session history

To maintain a single source of truth, all modifications to a traversable navigable 's session history entries need to be synchronized. This is especially important due to how session history is influenced by all of the descendant navigables , and thus by multiple event loops . To accomplish this, we use the session history traversal parallel queue structure.

A session history traversal parallel queue is very similar to a parallel queue . It has an algorithm set , an ordered set .

The ` items in a session history traversal parallel queue 's algorithm set are either algorithm steps, or synchronous navigation steps , which are a particular brand of algorithm steps involving a target navigable (a navigable ).

To append session history traversal steps to a traversable navigable traversable given algorithm steps steps , append steps to traversable 's session history traversal queue 's algorithm set .

To append session history synchronous navigation steps to a traversable navigable traversable given algorithm steps steps and a navigable targetNavigable , append steps as synchronous navigation steps targeting target navigable targetNavigable to traversable 's session history traversal queue 's algorithm set .

To start a new session history traversal parallel queue :

  1. Let sessionHistoryTraversalQueue be a new session history traversal parallel queue .

  2. Run the following steps in parallel :

    1. While true:

      1. If sessionHistoryTraversalQueue 's algorithm set is empty, then continue .

      2. Let steps be the result of dequeuing from sessionHistoryTraversalQueue 's algorithm set .

      3. Run steps .

  3. Return sessionHistoryTraversalQueue .

Synchronous navigation steps are tagged in the algorithm set to allow them to conditionally "jump the queue". This is handled within apply the history step .

Imagine the joint session history depicted by this Jake diagram :

0 1
Refresh top ` header /a /b

And the following code runs at the top level:

history.back();
location.href
=
'#foo';

The desired result is:

0 1 2
top /a /b /b#foo

This isn't straightforward, as the sync navigation wins the race in terms of being observable, whereas the traversal wins the race in terms of queuing steps on the session history traversal parallel queue . To achieve this result, the following happens:

  1. history.back() appends steps intended to traverse by a delta of −1.

  2. location.href = '#foo' synchronously changes the active session history entry entry to a newly-created one, with the URL /b#foo , and appends synchronous steps to notify the central source of truth about that new entry. Note that this does not yet update the current session history entry , current session history step , or the session history entries list; those updates cannot be done synchronously, and instead must be done as part of the queued steps.

  3. On the session history traversal parallel queue , the steps queued by history.back() run:

    1. The target history step is determined to be 0: the current session history step (i.e., 1) plus the intended delta of −1.

    2. We enter the main apply the history step algorithm.

      The entry at step 0, for the /a URL, has its document populated .

      Meanwhile, the queue is checked for synchronous navigation steps . The steps queued by the location.href setter now run, and block the traversal from performing effects beyond document population (such as, unloading documents and switching active history entries) until they are finished. Those steps cause the following to happen:

      1. The entry with URL /b#foo is added, with its step determined to be 2: the current session history step (i.e., 1) plus 1.

      2. We fully switch to that newly added entry, including a nested call to apply the history step . This ultimately results in updating the document by dispatching events like hashchange .

      Only once that is all complete, and the /a history entry has been fully populated with a document , do we move on with applying the history step given the target step of 0.

      At this point, the Document with URL /b#foo unloads , and we finish moving to our target history step 0, which makes the entry with URL /1 become the active session history entry and 0 become the current session history step .

Here is another more complex example, involving races between populating two different iframe s, and a synchronous navigation once one of those iframes loads. We start with this setup:

0 1 2
top /t
frames[0] /i-0-a /i-0-b
frames[1] /i-1-a /i-1-b

and then call history.go(-2) . The following then occurs:

  1. history.go(-2) appends steps intended to traverse by a delta of −2. Once those steps run:

    1. The target step is determined to be 2 + (−2) = 0.

    2. In parallel, the fetches are made to populate the two iframes, fetching /i-0-a and /i-1-a respectively.

      Meanwhile, the queue is checked for synchronous navigation steps . There aren't any right now.

    3. In the fetch race, the fetch for /i-0-a wins. We proceed onward to finish all of apply the history step 's work for how the traversal impacts the frames[0] navigable , including updating its active session history entry to the entry with URL /i-0-a .

    4. Before the fetch for /i-1-a finishes, we reach the point where scripts may run for the newly-created document in the frames[0] navigable 's active document . Some such script does run:

      
      location.href
      =
      '#foo'
      
      

      This synchronously changes the frames[0] navigable's active session history entry entry to a newly-created one, with the URL /i-0-a#foo , and appends synchronous steps to notify the central source of truth about that new entry.

      Unlike in the previous example , these synchronous steps do not "jump the queue" and update the traversable before we finish the fetch for /i-1-a . This is because the navigable in question, frames[0] , has already been altered as part of the traversal, so we know that with the current session history step being 2, adding the new entry as a step 3 doesn't make sense.

    5. One the fetch for /i-1-a finally finishes, we proceed to finish updating the frames[1] navigable for the traversal, including updating its active session history entry to the entry with URL /i-1-a .

    6. Now that both navigables have finished processing the traversal, we update the current session history step to the target step of 0.

  2. Now we can process the steps that were queued for the synchronous navigation:

    1. The /i-0-a#foo entry is added, with its step determined to be 1: the current session history step (i.e., 0) plus 1. This also clears existing forward history .

    2. We fully switch to that newly added entry, including calling apply the history step . This ultimately results in updating the document by dispatching events like hashchange , as well as updating the current session history step to the target step of 1.

The end result is:

0 1
top /t
frames[0] /i-0-a /i-0-a#foo
frames[1] /i-1-a
7.11 7.4.1.4 Browsing Low-level operations on session history

This section contains a miscellaneous grab-bag of operations that we perform throughout the web standard when manipulating session history. The best way to get a sense of what they do is to look at their call sites.

To get session history entries for a navigable , navigable :

  1. Let traversable be navigable 's traversable navigable .

  2. Assert: This is running within traversable 's session history traversal queue .

  3. If navigable is traversable , return traversable 's session history entries .

  4. Let docStates be an empty ordered set of document states .

  5. For each entry of traversable 's session history entries , append entry 's document state to docStates .

  6. For each docState of docStates :

    1. For each nestedHistory of docState 's nested histories :

      1. If nestedHistory 's id equals navigable 's id , return nestedHistory 's entries .

      2. For each entry of nestedHistory 's entries , append entry 's document state to docStates .

  7. Assert: This step is not reached.

To clear the forward session history of a traversable navigable navigable :

  1. Assert: This is running within navigable 's session history traversal queue .

  2. Let step be the navigable 's current session history step .

  3. Let entryLists be the ordered set « navigable 's session history entries ».

  4. For each entryList of entryLists :

    1. Remove every session history entry from entryList that has a step greater than step .

    2. For each entry of entryList :

      1. For each nestedHistory of entry 's document state 's nested histories , append nestedHistory 's entries list to entryLists .

To get all used history steps that are part of traversable navigable traversable :

  1. Assert: This is running within traversable 's session history traversal queue .

  2. Let steps be an empty ordered set of non-negative integers.

  3. Let entryLists be the ordered set « traversable 's session history entries ».

  4. For each entryList of entryLists :

    1. For each entry of entryList :

      1. Append entry 's step to steps .

      2. For each nestedHistory of entry 's document state 's nested histories , append nestedHistory 's entries list to entryLists .

  5. Return steps , sorted .

To apply pending history changes to a traversable navigable traversable with optional boolean checkForUserCancelation (default false):

  1. Let targetStep be traversable 's current session history step .

  2. Apply the history step targetStep to traversable with checkForUserCancelation set to checkForUserCancelation .

Certain actions cause the browsing context a navigable 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 navigation.

Although in this standard the word "navigation" refers specifically to navigate. the navigate algorithm, this doesn't always line up with web developer or user perceptions. For example:

A resource has a URL,

Before we can jump into the navigation algorithm itself, we need to establish several important structures that uses HTTP POST would also have it uses.

The source snapshot params struct is used to capture data from a Document initiating a navigation. It is snapshotted at the HTTP method beginning of a navigation and payload. Similarly, used throughout the navigation's lifetime. It has the following items :

has transient activation
a boolean
sandboxing flags
a sandboxing flag set
allows downloading
a boolean
fetch client
an iframe srcdoc environment settings object , only to be used as a request client
origin
an origin
source policy container
a policy container

To snapshot source snapshot params given a Document document sourceDocument , return a new source snapshot params needs to know with

has transient activation
true if sourceDocument 's relevant global object has transient activation ; otherwise false
sandboxing flags
sourceDocument 's active sandboxing flag set
allows downloading
false if sourceDocument 's active sandboxing flag set has the sandboxed downloads browsing context flag set; otherwise true
fetch client
sourceDocument 's relevant settings object
origin
sourceDocument 's origin
source policy container
sourceDocument 's policy container

The target snapshot params struct is used to capture data from a navigable being navigated. Like source snapshot params , it is snapshotted at the beginning of a navigation and used throughout the navigation's lifetime. It has the following items :

sandboxing flags
a sandboxing flag set

To snapshot target snapshot params given a navigable targetNavigable , return a new target snapshot params with sandboxing flags set to use. the result of determining the creation sandboxing flags given targetNavigable 's active browsing context and targetNavigable 's container .


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 that algorithm are tracked via a navigation params struct , which has the following items :

id
null or a navigation id 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 navigable
the browsing context navigable to be navigated (or discarded, if a browsing context group switch occurs)
history handling navigation timing type
a history handling behavior NavigationTimingType used for creating the navigation timing entry for the new Document
has cross-origin redirects
a boolean
process response end of body
an algorithm expecting a response
commit early hints
null or an algorithm accepting a Document , once it has been created

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


A navigation ID is a UUID string generated during navigation. It is used to interface with the WebDriver BiDi specification as well as to track the ongoing navigation . [WEBDRIVERBIDI]


After Document creation, the relevant traversable navigable 's 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 push "
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 will clear the current forward session history entry .
" replace "
A non-reload navigation that will replace the current active 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
7.4.2.2 Beginning navigation

Each navigable has a an ongoing navigation id , which is a unique string. navigation ID , " traversal ", or null, initially null. It is used to track navigation aborting and to prevent any navigations from taking place during traversal .

To navigate a browsing context navigable browsingContext navigable to a resource URL resource url using a Document sourceDocument , with an optional POST resource or string documentResource (default null), an optional response response (default null), an optional boolean exceptionsEnabled (default false), an optional history handling behavior historyHandling (default " default push "), an optional policy container -or-null historyPolicyContainer (default null), an optional string navigationType cspNavigationType (default " other "), an optional navigation id referrer policy navigationId referrerPolicy (default null), the empty string), and an optional processResponseEndOfBody , which is an algorithm receiving a response (default an algorithm that does nothing):

  1. If resource is a URL , then set Let resource sourceSnapshotParams to a new request whose URL be the result of snapshotting source snapshot params is given resource sourceDocument .

  2. If Let navigationId is null: be the result of generating a random UUID . [UUID]

  3. historyHandling is " reload If the surrounding agent ", and is equal to browsingContext navigable 's active document 's relevant agent , then continue these steps. Otherwise, queue a global task on the navigation id and traversal task source is not null, let given navigationId navigable be 's active window to continue these steps.

    We do this because we are about to look at a lot of properties of browsingContext navigable 's active document 's navigation id , which are in theory only accessible over in the appropriate event loop . Otherwise let navigation id (But, we do not want to unconditionally queue a task, since — for example — same-event-loop fragment navigations need to take effect synchronously.)

    Another implementation strategy would be to replicate the result of generating relevant information across event loops, or into a random UUID . [UUID] canonical "browser process", so that it can be consulted without queueing a task. This could give different results than what we specify here in edge cases, where the relevant properties have changed over in the target event loop but not yet been replicated. Further testing is needed to determine which of these strategies best matches browser behavior, in such racy edge cases.

  4. If browsingContext navigable '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.

  5. Let If incumbentNavigationOrigin navigable be the origin of the incumbent settings object , or if no script was involved, the origin 's parent of the node document is non-null, then set navigable 's is delaying load events of the element that initiated the navigation . to true.

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

  7. If resource is a request , then set Let resource targetSnapshotParams 's policy container be the result of snapshotting target snapshot params to given initiatorPolicyContainer navigable .

  8. Cancel any preexisting but not yet mature Invoke WebDriver BiDi navigation started attempt to navigate with browsingContext targetBrowsingContext , including canceling any instances of the fetch algorithm started by those attempts. If one of those attempts has already created and initialized a new WebDriver BiDi navigation status whose id is navigationId , url is url , and status is " pending ".

  9. If navigable 's ongoing navigation is " Document traversal object , abort ", then:

    1. Invoke WebDriver BiDi navigation failed that with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId , status is " Document canceled also. (Navigation ", and url is url .

    2. Return.

    Any attempts to navigate a navigable that have matured is currently traversing already have session history entries, and are therefore handled during the update ignored.

  10. Set navigable 's ongoing navigation to navigationId .

    This will have the session history with effect of aborting other ongoing navigations of navigable , since at certain points during navigation changes to the new page ongoing navigation algorithm, later.) will cause further work to be abandoned.

  11. In parallel , run these steps:

    1. Let unloadPromptResult be the result of calling prompt to unload checking if unloading is user-canceled with the for navigable 's 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. 's inclusive descendant navigables .

    2. If unloadPromptResult is " refuse ", then return or navigable 's ongoing navigation is no longer navigationId , then:

      1. Invoke WebDriver BiDi navigation failed with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId and , status is " canceled ". ", and url is url .

      2. Abort these steps.

    3. Queue a global task on the navigation and traversal task source given navigable 's active document window to abort of browsingContext . navigable 's active document .

    4. If Let browsingContext documentState is be a child browsing context , then put it in the delaying load events mode . new document state with

      The user agent must take this child browsing context
      request referrer policy out of the delaying load events mode
      referrerPolicy
      resource when this navigation
      documentResource
      navigable target name algorithm
      navigable 's target name

      The navigable target name can get cleared under various conditions later matures , or when it terminates (whether due to having run all in the steps, or being canceled, or being aborted), whichever happens first. navigation process, before the document state is finalized.

    5. Let If sandboxFlags url be the result of determining the creation sandboxing flags is about:blank given , then set browsingContext documentState and 's origin to browsingContext sourceSnapshotParams 's container origin .

    6. Let Otherwise, if allowedToDownload url be the result of running the allowed to download is about:srcdoc algorithm given the source browsing context , then set documentState 's origin and to browsingContext . navigable 's parent 's active document 's origin .

    7. Let hasTransientActivation historyEntry be true if a new session history entry , with its URL set to url and its document state set to documentState .

    8. If url 's scheme is " javascript ", then queue a global task on the DOM manipulation task source browsing context given navigable 's active window has transient activation ; otherwise false. to run these steps:

      1. Invoke WebDriver BiDi navigation started Populate a history entry's document by evaluating a javascript: URL with for browsingContext historyEntry , given navigable , sourceSnapshotParams , cspNavigationType , and url .

      2. Queue a new WebDriver BiDi navigation status task on the navigable 's traversable whose id 's session history traversal queue is to finalize a cross-document navigation with navigationId navigable , url is resource 's url , historyHandling , and status historyEntry .

      3. Return.

      So for example a javascript: URL is " in an pending href ". attribute of an Return, and continue running these steps a element would only be evaluated when the link was followed , while such a URL in parallel . This is the step src attribute of an iframe element would be evaluated in the context of the iframe 's nested navigable 's active window when the iframe is being set up. Once evaluated, its return value (if it was a string) would replace that attempts to obtain resource , if necessary. Jump to navigable 's active document , thus also changing the first appropriate substep: corresponding Window object.

    9. Let navigationParams be null.

    10. If resource response is non-null:

      The navigate algorithm is only supplied with a response as part of the object and embed processing models, or for processing parts of multipart/x-mixed-replace responses after the initial response.

      1. Assert: Let browsingContext policyContainer is not be the result of determining navigation params policy container given response 's URL , null, a top-level browsing context . clone of the sourceDocument 's policy container , navigable 's container document 's policy container , and null.

      2. Let finalSandboxFlags be the union of browsingContext targetSnapshotParams 's sandboxing flags and resource policyContainer 's forced CSP list 's CSP-derived sandboxing flag set flags .

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

      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 response 's url URL , origin is responseOrigin , cross-origin opener policy is coop , and current context is navigation source is false.

      6. Let Set policyContainer navigationParams be the result of determining to a new navigation params , with

        id
        navigationId
        request
        null
        response
        response
        origin
        responseOrigin
        policy container
        policyContainer
        final sandboxing flag set
        finalSandboxFlags
        cross-origin opener policy
        coop
        COOP enforcement result
        coopEnforcementResult
        reserved environment
        null
        navigable
        navigable
        navigation timing type
        " navigate "
        has cross-origin redirects
        false
        process response end of body
        processResponseEndOfBody
        commit early hints
        null
    11. Attempt to populate the history entry's document for historyEntry , given resource navigable , " navigate ", sourceSnapshotParams , targetSnapshotParams , navigationId , navigationParams , cspNavigationType , with allowPOST set to true, processResponseEndOfBody set to processResponseEndOfBody , and completionSteps set to the following steps:

      1. Queue a task on the navigable 's url , traversable 's session history traversal queue to finalize a cross-document navigation given historyPolicyContainer navigable , initiatorPolicyContainer historyHandling , and browsingContext historyEntry .

7.4.2.3 Ending navigation

Although a cross-document navigation will first foray into populating a session history entry with a Document , all navigations that don't get aborted will ultimately end up calling into one of the below algorithms.

7.4.2.3.1 Cross-document navigations

To finalize a cross-document navigation given a navigable navigable , history handling behavior historyHandling , and session history entry historyEntry :

  1. Set navigable 's is delaying load events to false.

  2. If historyEntry 's document is null, then return.

    This means that attempting to populate the history entry's document ended up not creating a document, as a result of e.g., the navigation being canceled by a subsequent navigation, a 204 No Content response, etc.

  3. Assert: This algorithm is running on navigable 's traversable navigable's session history traversal queue .

  4. If all of the following are true:

    then set historyEntry 's document state 's navigable target name to the empty string.

  5. Let entryToReplace be navigable 's active session history entry if historyHandling is " replace ", otherwise null.

  6. Let traversable be navigable 's traversable navigable .

  7. Let targetStep be null.

  8. Let targetEntries be the result of getting session history entries for navigable .

  9. If entryToReplace is null, then:

    1. Clear the forward session history of traversable .

    2. Set targetStep to traversable 's current session history step + 1.

    3. Set historyEntry 's step to targetStep .

    4. Append historyEntry to targetEntries .

    Otherwise:

    1. Replace entryToReplace with historyEntry in targetEntries .

    2. Set historyEntry 's step to entryToReplace 's step .

    3. Set targetStep to traversable 's current session history step .

  10. Apply the history step targetStep to traversable .

7.4.2.3.2 Fragment navigations

To navigate to a fragment given a navigable navigable , a URL url , a history handling behavior historyHandling , and a navigation ID navigationId :

  1. Let historyEntry be a new session history entry , with

    URL
    url
    document state
    navigable 's active session history entry 's document state
    serialized state
    StructuredSerializeForStorage (null)
    scroll restoration mode
    navigable 's active session history entry 's scroll restoration mode
  2. Let entryToReplace be navigable 's active session history entry if historyHandling is " replace ", otherwise null.

  3. Let navigationParams history be navigable 's active document 's history object .

  4. Let scriptHistoryIndex be history 's index .

  5. Let scriptHistoryLength be history 's length .

  6. If historyHandling is " push ", then:

    1. Set history 's state to null.

    2. Increment scriptHistoryIndex .

    3. Set scriptHistoryLength to scriptHistoryIndex + 1.

  7. Set navigable 's active session history entry to historyEntry .

  8. Update document for history step application given navigable 's active document , historyEntry , true, scriptHistoryIndex , and scriptHistoryLength .

    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.

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

  10. Let traversable be navigable 's traversable navigable .

  11. Append the following session history synchronous navigation steps involving navigable to traversable :

    1. Finalize a same-document navigation params given traversable , navigable , historyEntry , and entryToReplace .

    2. Invoke WebDriver BiDi fragment navigated with navigable 's active browsing context and a new WebDriver BiDi navigation status whose id is navigationId , request url is null, response resource 's url , and status is " complete ".

To finalize a same-document navigation given a traversable navigable resource traversable , origin a navigable targetNavigable , a session history entry targetEntry , and session history entry -or-null entryToReplace :

This is used by both fragment navigations and by the URL and history update steps , which are the only synchronous updates to session history. By virtue of being synchronous, those algorithms are performed outside of the top-level traversable 's session history traversal queue . This puts them out of sync with the top-level traversable 's current session history step , so this algorithm is used to resolve conflicts due to race conditions.

  1. Assert: this algorithm is running on responseOrigin traversable 's session history traversal queue .

  2. If targetNavigable 's active session history entry is not targetEntry , policy container then return.

  3. Let targetStep be null.

  4. Let targetEntries be the result of getting session history entries for targetNavigable .

  5. If entryToReplace is null, then:

    1. Clear the forward session history of policyContainer traversable .

    2. Set targetStep to traversable 's current session history step + 1.

    3. Set targetEntry 's step to targetStep .

    4. Append targetEntry to targetEntries .

    Otherwise:

    1. Replace entryToReplace with targetEntry in targetEntries .

    2. Set targetEntry 's step to entryToReplace 's step .

    3. Set targetStep to traversable 's current session history step .

  6. Apply the history step targetStep to traversable .

    This is done even for " replace " navigations, as it resolves race conditions across multiple synchronous navigations.

7.4.2.3.3 Non-fetch schemes and external software

To attempt to create a URL scheme document , given a URL url , final a navigable navigable , a sandboxing flag set sandboxFlags , a navigation ID navigationId , a NavigationTimingType navTimingType , and a source snapshot params sourceSnapshotParams :

  1. If url is to be handled using a mechanism that does not affect finalSandboxFlags navigable , cross-origin opener policy e.g., because url 's scheme is handled externally, then:

    1. Hand-off to external software given coop url , COOP enforcement navigable , sandboxFlags , and sourceSnapshotParams .

    2. Return null.

  2. Handle url 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. Return the result of displaying the inline content is given coopEnforcementResult navigable , reserved environment navigationId , and navTimingType .

    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 navigable navigable , a sandboxing flag set sandboxFlags , and a source snapshot params sourceSnapshotParams , user agents should:

  1. If all of the following conditions 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. That's why its is allowed in sandboxed iframe only when one of body allow-popups , allow-top-navigation , allow-top-navigation-by-user-activation , or allow-top-navigation-to-custom-protocols is specified.

  2. Perform the appropriate handoff of processResponseEndOfBody , 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 sourceSnapshotParams 's origin is to be allowed to invoke the external software in question. In particular, if sourceSnapshotParams 's has cross-origin redirects transient activation is false, and commit early hints 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.

7.4.2.4 Preventing navigation is null.

Run A couple of scenarios can intervene early in the navigation process and put the whole thing to a halt. This can be especially exciting when multiple navigables are navigating at the same time, due to a session history traversal.

A navigable source is allowed by sandboxing to navigate response a second navigable with navigationType target , given a source snapshot params allowedToDownload sourceSnapshotParams , if the following steps return true:

  1. If hasTransientActivation source is target , then return true.

  2. If source is an ancestor of target , then return true.

  3. If target is an ancestor of source , then:

    1. If target is not a top-level traversable , then return true.

    2. If sourceSnapshotParams 's has transient activation is true, and navigationParams . sourceSnapshotParams 's sandboxing flags 's sandboxed top-level navigation with user activation browsing context flag is set, then return false.

    3. If sourceSnapshotParams 's has transient activation is false, and sourceSnapshotParams 's sandboxing flags 's sandboxed top-level navigation without user activation browsing context flag is set, then return false.

    4. Return true.

  4. If resource target is a request top-level traversable :

    1. If source is the one permitted sandboxed navigator whose URL of target , then return true.

    2. If sourceSnapshotParams 's sandboxing flags 's scheme sandboxed navigation browsing context flag is " set, then return false.

    3. javascript

      Return true.

  5. If sourceSnapshotParams 's sandboxing flags 's sandboxed navigation browsing context flag is set, then return false.

  6. "

    Return true.

Queue To check if unloading is user-canceled for list of navigables navigables :

  1. Let documents be the active document of each item in navigables .

  2. Let unloadPromptShown be false.

  3. Let unloadPromptCanceled be false.

  4. Let totalTasks be the size of documents .

  5. Let completedTasks be 0.

  6. For each document of documents , queue a global task on the DOM manipulation navigation and traversal task source given browsingContext document 's active window relevant global object to run these the steps:

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

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

    3. Let response event be the result of executing a javascript: URL request creating an event given resource , using BeforeUnloadEvent .

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

    5. Let Dispatch finalSandboxFlags event be at document 's relevant global object .

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

    7. If all of the following are true:

      then:

      1. Set resource unloadPromptShown to true.

      2. Invoke WebDriver BiDi user prompt opened with document 's URL relevant global object , origin " beforeunload ", and "".

      3. Ask the user to confirm that they wish to unload the document, and pause while waiting for the user's response.

        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.

      4. If the user did not confirm the page navigation, set browsingContext unloadPromptCanceled 's active to true.

      5. Invoke WebDriver BiDi user prompt closed with document 's relevant global object and true if unloadPromptCanceled is false or false otherwise.

    8. Decrease the document 's origin , cross-origin opener policy unload counter by 1.

    9. Increment completedTasks .

  7. Wait for completedTasks to be totalTasks .

  8. If unloadPromptCanceled is true, then return " refuse ".

  9. If browsingContext unloadPromptShown is true, then return " confirm ".

  10. Return " no-prompt ".

7.4.3 Reloading and traversing

To reload a navigable navigable :

  1. Set navigable 's active session history entry 's document state 's cross-origin opener policy , and current context is navigation source reload pending is false. to true.

  2. Let navigationParams traversable be a new navigation params navigable 's traversable navigable .

  3. Append the following session history traversal steps whose id to traversable :

    1. Apply pending history changes is to navigationId , request traversable with true.

      It is intentional that the resulting call to apply the history step does not pass sourceSnapshotParams or initiatorToCheck . Reloading is always treated as if it were done by resource , response navigable itself, even in cases like parent.location.reload() .

To traverse the history by a delta given a traversable navigable is response traversable , origin an integer delta , and an optional Document sourceDocument :

  1. Let sourceSnapshotParams and initiatorToCheck be null.

  2. If sourceDocument is given, then:

    1. Set browsingContext sourceSnapshotParams to the result of snapshotting source snapshot params given sourceDocument .

    2. Set initiatorToCheck to sourceDocument 's active document node navigable .

  3. Append the following session history traversal steps to traversable :

    1. Let allSteps be the result of getting all used history steps for traversable .

    2. Let currentStepIndex be the index of traversable 's origin current session history step within allSteps .

    3. Let targetStepIndex be currentStepIndex plus delta .

    4. If allSteps [ targetStepIndex ] does not exist , policy container then abort these steps.

    5. Apply the history step is browsingContext allSteps 's [ targetStepIndex ] to traversable , with checkForUserCancelation set to true, sourceSnapshotParams set to sourceSnapshotParams , and initiatorToCheck set to initiatorToCheck .

Apart from the navigate algorithm, session history entries can be pushed or replaced via one more mechanism, the URL and history update steps . The most well-known callers of these steps are the history.replaceState() and history.pushState() APIs, but various other parts of the standard also need to perform updates to the active history entry , and they use these steps to do so.

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:

  1. Let navigable be document 's policy container node navigable .

  2. Let activeEntry be navigable 's active session history entry .

  3. Let newEntry be a new session history entry , final sandboxing flag set with

    URL is
    finalSandboxFlags , cross-origin opener policy newURL
    serialized state
    if serializedData is not null, browsingContext serializedData ; otherwise activeEntry 's active serialized state
    document state
    activeEntry 's cross-origin opener policy , COOP enforcement result document state is
    scroll restoration mode
    coopEnforcementResult , reserved environment activeEntry 's scroll restoration mode
    persisted user state
    activeEntry 's persisted user state
  4. If document 's is null, browsing context initial about:blank is true, then set browsingContext , history handling historyHandling to " replace is ".

    This means that pushState() on an initial about:blank Document behaves as a replaceState() call.

  5. Let entryToReplace be activeEntry if historyHandling , process response end of body is " replace ", otherwise null.

  6. If historyHandling is " push ", then:

    1. Increment processResponseEndOfBody , has cross-origin redirects document 's history object 's index .

    2. Set document 's history object 's length to its index + 1.

    These are temporary best-guess values for immediate synchronous access.

  7. If serializedData is false, not null, then restore the history object state given document and commit early hints newEntry .

  8. Set document 's URL to newURL .

    Since this is null. neither a navigation nor a history traversal , it does not cause a hashchange event to be fired.

  9. Run process Set document 's latest entry to newEntry .

  10. Set navigable 's active session history entry to newEntry .

  11. Let traversable be navigable 's traversable navigable .

  12. Append the following session history synchronous navigation steps involving navigable to traversable :

    1. Finalize a navigate response same-document navigation with given navigationType traversable , allowedToDownload navigable , hasTransientActivation newEntry , and navigationParams entryToReplace .

    So for example

Although both fragment navigation and the URL and history update steps perform synchronous history updates, only fragment navigation contains a javascript: synchronous call to update document for history step application . The URL and history update steps in instead perform a few select updates inside the above algorithm, omitting others. This is somewhat of an unfortunate historical accident, and generally leads to web-developer sadness about the inconsistency. For example, this means that href popstate attribute of an events fire for fragment navigations, but not for a history.pushState() element would only be evaluated when calls.

7.4.5 Populating a session history entry

As explained in the link was followed overview , while such both navigation and traversal involve creating a session history entry and then attempting to populate its document member, so that it can be presented inside the navigable .

This process breaks down into two high-level cases: the usual case , and the javascript: URL special case . The usual case involves either using an already-given response , using the srcdoc resource stored in the session history entry , or fetching . The src javascript: attribute case bypasses most of the usual machinery and instead assembles enough information to immediately load an HTML document . Both cases have several failure modes, which can either result in doing nothing (leaving the navigable on its currently- active iframe Document element would be evaluated ) or can result in populating the context of the iframe session history entry with an error document .

7.4.5.1 The usual case 's nested browsing context when

To attempt to populate the history entry's document for a session history entry entry , given a navigable navigable , a iframe NavigationTimingType is being set up. Once evaluated, its return value (if it was navTimingType , a string) would replace that browsing context source snapshot params sourceSnapshotParams , a target snapshot params targetSnapshotParams , an optional navigation ID -or-null navigationId (default null), an optional navigation params -or-null navigationParams (default null), an optional string cspNavigationType (default " other "), an optional boolean allowPOST (default false), optional algorithm steps processResponseEndOfBody (default an empty algorithm), and optional algorithm steps completionSteps (default an empty algorithm):

  1. Assert: if navigationParams is non-null, then navigationParams 's response is non-null.

  2. Let currentBrowsingContext be navigable 's active document , thus also changing the corresponding browsing context .

  3. Window

    Let documentResource be entry 's document state object. 's resource .

  4. If navigationParams is null, then:

    1. If resource documentResource is a request whose URL string, then set navigationParams to the result of creating navigation params from a srcdoc resource given entry , navigable , targetSnapshotParams , navigationId , navTimingType , and processResponseEndOfBody .

    2. Otherwise, if both of the following are true:

      Run process a navigate fetch then set navigationParams to the result of creating navigation params by fetching given entry , navigable , sourceSnapshotParams , targetSnapshotParams , cspNavigationType , navigationId , resource navTimingType , and processResponseEndOfBody .

  5. Queue a global task on the networking task source browsing context , given browsingContext , navigable 's active window , to run these steps:

    1. If navigationType navigable 's ongoing navigation no longer equals navigationId , then run sandboxFlags completionSteps and return.

    2. Let failure be false.

    3. If navigationParams is null and entry 's URL is not a fetch scheme , then set entry 's document state 's document to the result of running attempt to create a URL scheme document given entry 's URL , navigable , historyPolicyContainer targetSnapshotParams 's sandboxing flags , navigationId , initiatorPolicyContainer navTimingType , and allowedToDownload sourceSnapshotParams .

      The entry 's URL might have been changed within the previous step of this algorithm following an HTTP redirect.

    4. Otherwise, if navigationParams is null, then set failure to true.

    5. 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 , navigationParams 's response , navigationParams 's policy container 's CSP list , cspNavigationType , and hasTransientActivation currentBrowsingContext is " Blocked ", then set failure to true. [CSP]

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

    7. Otherwise, if the result of checking a navigation response's adherence to ` X-Frame-Options ` given navigationParams 's response , navigable , historyHandling navigationParams 's policy container 's CSP list , and navigationParams 's origin is false, then set failure to true.

    8. If failure is true, then:

      1. Set entry 's document state 's document to the result of creating a document for inline content that doesn't have a DOM , given navigable , null, and processResponseEndOfBody navTimingType . Otherwise, The inline content should indicate to the user the sort of error that occurred.

      2. Set resource entry 's document state 's document 's salvageable to false.

      3. If navigationParams is not null, then:

        1. Run processResponseEndOfBody given navigationParams 's response .

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

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

    9. Otherwise, if navigationParams 's response 's scheme status is neither " 204 or 205, then:

        javascript
      1. Run processResponseEndOfBody given navigationParams 's response .

      2. Run completionSteps .

      3. Return.

    10. Otherwise:

      1. Let document be the result of loading a navigate URL scheme document given resource navigationParams and sourceSnapshotParams .

      2. If document is null, then run completionSteps and return.

      3. Set entry 's URL , document state 's document to browsingContext , document .

      4. Set sandboxFlags , entry 's document state 's origin to document 's origin .

    11. If entry 's document state 's request referrer is " client ", then set it to request 's referrer .

      This ensures that if we traverse back entry and have to refetch, we use the same referrer , instead of deriving the referrer from the fetch client.

    12. If hasTransientActivation entry 's document state 's document is not null, then set entry 's document state 's ever populated to true.

    13. Run completionSteps .

To process create navigation params from a navigate fetch , srcdoc resource given a session history entry entry , a navigable navigable , a target snapshot params targetSnapshotParams , a navigation id ID -or-null navigationId , request a NavigationTimingType request navTimingType , two browsing contexts and an algorithm processResponseEndOfBody :

  1. Let documentResource be entry 's document state 's resource .

  2. Let sourceBrowsingContext response be a new response whose URL list consists of about:srcdoc , header list consists of (` Content-Type `, ` text/html `), and body is documentResource .

  3. Let responseOrigin be the result of determining the origin given response 's URL , targetSnapshotParams 's sandboxing flags , null, and browsingContext , entry 's document state 's origin .

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

  5. Let navigationType 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 response '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 response 's URL , entry 's document state 's history policy container , null, navigable 's container document 's policy container , and null.

  7. Return a new navigation params , with

    id
    navigationId
    request
    null
    response
    response
    origin
    responseOrigin
    policy container
    policyContainer
    final sandboxing flag set
    sandboxFlags , two targetSnapshotParams's sandboxing flags
    cross-origin opener policy containers
    historyPolicyContainer coop and
    COOP enforcement result
    initiatorPolicyContainer coopEnforcementResult
    reserved environment
    null
    navigable
    navigable
    navigation timing type
    navTimingType
    has cross-origin redirects
    false
    process response end of body
    an algorithm that does nothing
    commit early hints
    null

To create navigation params by fetching given a session history entry entry , a boolean navigable allowedToDownload navigable , a boolean source snapshot params hasTransientActivation sourceSnapshotParams , an origin a target snapshot params incumbentNavigationOrigin targetSnapshotParams , a history handling behavior string cspNavigationType , a navigation ID -or-null historyHandling navigationId , and a NavigationTimingType processResponseEndOfBody navTimingType , which is and an algorithm accepting a response : processResponseEndOfBody :

This algorithm mutates entry .

  1. Let response documentResource be null. entry 's document state 's resource .

  2. Set Let request be a new request , with

    url
    entry 's client URL to
    policy container
    sourceBrowsingContext entry 's active document state 's relevant settings object , history policy container
    client
    sourceSnapshotParams 's fetch client
    destination to
    " document ", mode to " navigate ",
    credentials mode to
    " include ", "
    use-URL-credentials flag ,
    set
    redirect mode to
    " manual ", and "
    replaces client id to
    browsingContext navigable 's active document 's relevant settings object 's id
    mode
    " navigate "
    referrer
    entry 's document state 's request referrer
    referrer policy
    entry 's document state 's request referrer policy
  3. If documentResource is a POST resource , then:

    1. Set request 's method to ` POST `.

    2. Set request 's body to documentResource 's request body .

    3. Set ` Content-Type ` to documentResource 's request content-type in request 's header list .

  4. If hasTransientActivation entry 's document state 's reload pending is true, then set request 's reload-navigation flag .

  5. Otherwise, if entry 's document state 's ever populated is true, then set request 's history-navigation flag .

  6. If sourceSnapshotParams 's has transient activation is true, then set request 's user-activation to true.

  7. If browsingContext navigable 's container is non-null:

    1. If the browsingContext navigable '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 navigable 's container 's local name .

  8. Let responseOrigin response be null.

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

  10. Let coopEnforcementResult be a new cross-origin opener policy enforcement result whose , with

    needs a browsing context group switch is false,
    false
    would need a browsing context group switch due to report-only is false,
    false
    url is
    browsingContext navigable 's active document 's url , URL
    origin is
    browsingContext navigable 's active document 's origin ,
    cross-origin opener policy is
    browsingContext navigable 's active document 's cross-origin opener policy , and
    current context is navigation source
    true if navigable 's active document 's origin is same origin with currentContextIsSource . sourceSnapshotParams 's origin ; otherwise false
  11. Let finalSandboxFlags be an empty sandboxing flag set .

  12. Let responsePolicyContainer be null.

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

  14. Let locationURL be null.

  15. Let currentURL be request 's current URL .

  16. Let hasCrossOriginRedirects be false.

  17. Let commitEarlyHints be null.

  18. While true:

    1. If locationURL is non-null, then: If locationURL 's origin is not the same as currentURL 's origin , then set hasCrossOriginRedirects to true. Set currentURL to locationURL . 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. Set commitEarlyHints to null.

        Preloaded links from early hint headers remain in the preload cache after a same origin redirect, but get discarded when the redirect is cross-origin.

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

      1. Let topLevelCreationURL be currentURL .

      2. Let topLevelOrigin be null.

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

        1. Let parentEnvironment be browsingContext navigable 's container parent 's active document 's relevant settings object .

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

        3. Set 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 , navigable 's active browsing context , 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]

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

    4. Otherwise:

      If response is null, fetch request , with processEarlyHintsResponse set to the following step given a response earlyResponse : If commitEarlyHints is null, then set commitEarlyHints to the result of processing early hint headers given earlyResponse and request 's reserved client .

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

    6. If request 's body is null, then set entry 's document state 's resource to null.

      Fetch unsets the body for particular redirects.

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

      If navigationId is not null, then, while waiting, if navigable 's ongoing navigation changes to no longer equal navigationId , terminate the ongoing fetch with the aborted flag set, and return.

      Upon returning, attempt to populate the history entry's document will detect that this in-flight navigation was canceled and it will be handled accordingly.

    8. Set responsePolicyContainer to the result of creating a policy container from a fetch response given response and request 's reserved client .

    9. Set finalSandboxFlags to the union of browsingContext targetSnapshotParams 's sandboxing flags and response responsePolicyContainer 's forced CSP list 's CSP-derived sandboxing flag set flags .

    10. Let sourceOrigin be entry 's document state 's origin if request 's current URL matches about:blank , and sourceSnapshotParams 's origin otherwise.

    11. Set responseOrigin to the result of determining the origin given browsingContext , request response 's URL , finalSandboxFlags , and incumbentNavigationOrigin . sourceOrigin , and null.

    12. If browsingContext navigable is a top-level browsing context traversable , 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 , navigable 's active browsing context , 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.

    13. If response is not a network error , browsingContext navigable is a child browsing context navigable , and the result of performing a cross-origin resource policy check with browsingContext navigable 's container document 's origin , browsingContext navigable '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 navigable rather than sourceBrowsingContext . navigable itself. This is because we care about the same-originness of the embedded content against the parent context, not the navigation source.

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

    15. If locationURL is failure or null, then break .

    16. Set entry 's URL to locationURL .

    17. Set entry 's serialized state to null.

    18. Let oldDocState be entry 's document state .

    19. Set entry 's document state to a new document state , with request referrer , request referrer policy , resource , ever populated , and navigable target name copied from oldDocState , and the history policy container set to a clone of the oldDocState 's history policy container .

      For the navigation case, only entry referenced oldDocState , so this is functionally just an update to entry 's document state . For the traversal case, it's possible adjacent session history entries also reference oldDocState , in which case they will continue doing so even after we've updated entry 's document state .

      Consider a session history which contains... TODO-DOMENIC: fill out the full example of the traversal case, maybe.

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

      1. Set entry 's document state 's resource to null.

      2. Break .

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

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

    22. Set currentURL to locationURL .

    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 .

  19. If locationURL is failure, then set response to a network error . Otherwise, if locationURL is a URL whose scheme is a fetch scheme not null or " javascript ", then set response to is a network error . Otherwise, if locationURL is a URL , then process a navigate URL scheme given locationURL , browsingContext , sandboxFlags , and hasTransientActivation , and return. Let responsePolicyContainer be the result of creating a policy container from a fetch response given response and request 's reserved client . return null.

  20. Let resultPolicyContainer be the result of determining navigation params policy container given response 's URL , historyPolicyContainer , entry 's document state 's history policy container , initiatorPolicyContainer , sourceSnapshotParams 's source policy container , null, and responsePolicyContainer .

  21. Let navigationParams be Return a new navigation params whose , with

    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
    navigable is
    historyHandling , process response end of body navigable
    navigation timing type is
    processResponseEndOfBody , navTimingType
    has cross-origin redirects is
    hasCrossOriginRedirects , and commit early hints is commitEarlyHints . 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 end of body navigationParams :
    Let response be navigationParams processResponseEndOfBody 's response . Let browsingContext be navigationParams 's browsing context .
    commit early hints
    Let failure commitEarlyHints be false.

If response is An element has a network error , then set failure to true. Otherwise, browsing context scope origin 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] its Document Otherwise, if navigationParams 's reserved environment node navigable 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 top-level traversable is false, then set failure to true. Otherwise, or if the result all 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. If failure is true, then: its Document Call navigationParams 's process response end of body ancestor navigables with response . Display the inline content with an appropriate error shown to all have active documents whose origins are the user same origin given browsingContext . Run as the environment discarding steps element's node document for navigationParams 's reserved environment origin . Invoke WebDriver BiDi navigation failed with browsingContext and If an element has a new WebDriver BiDi navigation status whose id is navigationParams 's id browsing context scope origin , status then its value is " canceled ", and url the origin is response 's URL of the element's node document . Return.

This definition is where the network errors defined broken and propagated by Fetch , such as DNS or TLS errors, end up being displayed needs investigation to users. [FETCH] see what it was intended to express: see issue #4703 .

If response 's status To load a document given navigation params is 204 or 205, then call navigationParams 's process response end of body and source snapshot params with response sourceSnapshotParams , and return. If response has perform the following steps. They return a ` Content-Disposition Document ` header specifying the attachment disposition type, then: or null.

  1. If allowedToDownload is true, then handle response as a download . 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 . Return. Let type be the computed type of response navigationParams 's response .

  2. 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 navigable , 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: types:

    an HTML MIME type
    Follow the steps given in Return the result of loading an HTML document section providing , given 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 Return the result of loading an XML document section providing given 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 Return the plain result of loading a text file document section providing given navigationParams and type . Once the steps have completed, return.
    " multipart/x-mixed-replace "
    Follow the steps given in Return the result of loading a multipart/x-mixed-replace section providing document , given navigationParams and sourceSnapshotParams . Once the steps have completed, return.
    A supported image, video, or audio type
    Follow the steps given in Return the result of loading a media document section providing given 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 return the result of creating a document for inline content that doesn't have a DOM given browsingContext . Once the steps have completed, return. See issue #6003 for discussion on picking one of these two behaviors to standardize. navigationParams 's navigable .

    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), content, or one for which the user agent has dedicated processing rules (e.g., rules. For example, 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. type.

    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), content, or one for which the user agent has dedicated processing rules, or one for which rules.

    In both cases, the external application or user agent has a dedicated handler. will either display the content inline directly in navigationParams 's navigable , or hand it off to external software . Both happen in the steps below.

  3. Otherwise, the document's type is such that the resource will not affect browsingContext , navigationParams 's navigable , 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 navigationParams 's response , , browsingContext , navigationParams 's navigable , navigationParams 's final sandboxing flag set , and hasTransientActivation sourceSnapshotParams .

  4. To process a navigate URL scheme , given a URL url , a browsing context browsingContext , a sandboxing flag set Return null.

7.4.5.2 The javascript: sandboxFlags , and a boolean hasTransientActivation : URL special case 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

javascript: given url , browsingContext , sandboxFlags , and hasTransientActivation . 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 URLs have a registered handler for the given scheme. Display the inline content dedicated label given browsingContext . In on the case of a registered handler being used, navigate will be invoked issue tracker documenting various problems with a new URL. their specification.

To hand-off to external software given populate a history entry's document by evaluating a javascript: URL or response for session history entry resource historyEntry , given a browsing context navigable browsingContext targetNavigable , a sandboxing flag set source snapshot params sandboxFlags sourceSnapshotParams , and a boolean string hasTransientActivation cspNavigationType , user agents should: Return without invoking the external sofware package if all of these conditions hold: browsingContext is not and a top-level browsing context URL ; sandboxFlags has its sandboxed custom protocols navigation browsing context flag set; and url :

  1. sandboxFlags has its sandboxed top-level navigation with user activation browsing context flag set, or Let hasTransientActivation request is false. Navigation inside an iframe toward external software can be seen by users as a new popup or a new top-level navigation. That's why its is allowed in sandboxed iframe only when one of allow-popups , allow-top-navigation , allow-top-navigation-by-user-activation , or allow-top-navigation-to-custom-protocols is specified. 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 request 's origin whose URL 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. url .

    To execute a javascript: URL request , given

    This is a request synthetic request , a browsing context browsingContext , and an origin initiatorOrigin : solely for plumbing into other algorithms. It will never hit the network.

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

  3. If both of the following are true:

    then:

    1. Let urlString be the result of running the URL serializer on request 's URL . 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 targetNavigable 's active document 's URL to request 's URL list .

    5. Let settings be browsingContext targetNavigable '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.

  4. 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 Let type , content type policyContainer be contentType , and navigation params targetNavigable 's active document navigationParams : 's policy container .

  5. Let browsingContext finalSandboxFlags be the result of the obtaining a browsing context to use for a navigation response given navigationParams policyContainer 's browsing context , navigationParams CSP list 's final CSP-derived sandboxing flag set , flags .

  6. Let navigationParams coop be targetNavigable 's active document 's cross-origin opener policy , and navigationParams 's COOP enforcement result .

  7. Let permissionsPolicy coopEnforcementResult be the result of creating a permissions new cross-origin opener policy from enforcement result with

    needs a response browsing context group switch given browsingContext ,
    false
    would need a browsing context group switch due to report-only
    false
    url
    navigationParams url 's
    origin , and
    navigationParams sourceSnapshotParams 's response . [PERMISSIONSPOLICY] origin The creating a permissions
    cross-origin opener policy from a response algorithm makes use of the passed origin . If document.domain
    has been used for browsingContext coop 's container document , then its origin
    current context is navigation source cannot
    false
  8. Let navigationParams be same origin-domain a new navigation params , with the passed origin, because these steps run before the

    id
    document navigationId 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 request check instead. See below for some examples of this in action. Let
    creationURL request be
    response
    navigationParams 's response
    origin 's URL . If
    navigationParams sourceSnapshotParams 's request origin is non-null, then
    policy container
    policyContainer
    final sandboxing flag set
    creationURL finalSandboxFlags to
    cross-origin opener policy
    navigationParams coop 's request
    COOP enforcement result 's current URL . If
    browsingContext coopEnforcementResult is still on its initial about:blank Document , and
    reserved environment
    null
    navigable
    navigationParams targetNavigable 's history handling
    navigation timing type is
    " replace navigate ", and "
    has cross-origin redirects
    false
    process response end of body
    an algorithm that does nothing
    commit early hints
    null
  9. Set browsingContext historyEntry 's active document state 's origin document is same origin-domain to the result loading an HTML document with given navigationParams 's origin , then do nothing. .

    This means that both the initial about:blank javascript: URL documents go through a special path wherein we never actually call into attempt to populate the history entry's document , but instead we synchronously populate its document right here.

  10. Document

    Set historyEntry 's document state 's ever populated to true.

, 7.4.6 Applying the history step

For both navigation and traversal, once we have an idea of where we want to head to in the session history, much of the work comes about in applying that notion to the traversable navigable and the new relevant Document that . For navigations, this work generally occurs toward the end of the process; for traversals, it is about to be created, will share the same beginning.

7.4.6.1 Updating the traversable Window object.

Otherwise: Ensuring a traversable ends up at the right session history step is particularly complex, as it can involve coordinating across multiple navigable descendants of the traversable, populating them in parallel, and then synchronizing back up to ensure everyone has the same view of the result. This is further complicated by the existence of synchronous same-document navigations being mixed together with cross-document navigations, and how web pages have come to have certain relative timing expectations.

Let oacHeader be A changing navigable continuation state is used to store information during the result apply the history step algorithm, allowing parts of getting the algorithm to continue only after other parts have finished. It is a structured field value struct given ` with:

Origin-Agent-Cluster
displayed document
A Document ` and " item " from response 's header list . Let requestsOAC be true if
target entry
A session history entry
navigable
A navigable
update only
A boolean

To apply the history step non-negative integer oacHeader step is not null and to a traversable navigable oacHeader [0] is the traversable , with optional boolean true; otherwise false. If navigationParams checkForUserCancelation 's reserved environment (default false), optional source snapshot params is a non-secure context , then set requestsOAC to false. -or-null Let agent sourceSnapshotParams be the result of obtaining a similar-origin window agent (default null), and optional navigable given navigationParams initiatorToCheck 's origin , :

browsingContext sourceSnapshotParams 's group , and requestsOAC . Let realm execution context initiatorToCheck be the result of creating a new JavaScript realm are always either both given agent and or both not given. They are usually not given, as most callers do not need the following customizations: For extra checks on the global object, create a new Window navigation initiator that they cause. (Possibly because the caller has already performed such checks themselves.)

    object.
  1. For the global this binding, use Assert: This is running within browsingContext traversable 's WindowProxy object. session history traversal queue .

  2. Let topLevelCreationURL targetStep be the result of getting the used step given creationURL . Let topLevelOrigin traversable be and navigationParams 's origin . step .

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

    1. Let parentEnvironment be Assert: browsingContext sourceSnapshotParams 's container 's relevant settings object . is not null.

    2. Set topLevelCreationURL to For each parentEnvironment navigable 's top-level creation URL . Set of get all navigables whose current session history entry will change or reload : if topLevelOrigin initiatorToCheck is not allowed by sandboxing to navigate parentEnvironment navigable 's top-level origin . given sourceSnapshotParams , then return.

  4. Set up Let navigablesCrossingDocuments be the result of getting all navigables that might experience a window environment settings object cross-document traversal with given creationURL , traversable and realm execution context , targetStep .

  5. If navigationParams checkForUserCancelation 's reserved environment , is true, and the result of checking if unloading is user-canceled given topLevelCreationURL , navigablesCrossingDocuments given traversable and topLevelOrigin . targetStep is " refuse ", then return.

    This Some algorithms check if unloading is the usual case, where the new Document user-canceled we're about to create gets as a new Window prerequisite to go along with it. modifying the history tree. Those algorithms will set checkForUserCancelation to false when calling this algorithm to avoid performing the check twice.

    It might not be correct to block on beforeunload results here. This may have observable consequences.

  6. Let loadTimingInfo changingNavigables be a new document load timing info with its navigation start time the result of get all navigables whose current session history entry will change or reload set to given response traversable 's timing info 's start time . and targetStep .

  7. Let document nonchangingNavigablesThatStillNeedUpdates 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 the result of getting all navigables that only need history object length/index update is given navigationParams traversable '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 targetStep .

  8. For each is navigationParams navigable 's id . of changingNavigables :

    The new Window
      's associated Document
    1. is set to

      Let document targetEntry later, when be the caller result of this algorithm updates getting the session target history with the new page . That algorithm sets the active document as part of its larger role of synchronizing the Window , Document entry , browsing context , given navigable and session history . targetStep .

    2. Set document navigable 's URL current session history entry to creationURL targetEntry .

    3. Set document navigable 's current document readiness ongoing navigation to " loading traversal ".

  9. Run CSP initialization for a Document Let changeJobs be the size given of document changingNavigables . [CSP]

  10. If Let navigationParams completedChangeJobs 's request is non-null, then: be 0.

  11. Set Let document changingNavigableContinuations 's referrer be an empty queue of changing navigable continuation states .

    This queue is used to split the empty string. Let operations on referrer changingNavigables be into two parts. Specifically, navigationParams changingNavigableContinuations 's request 's referrer holds data for the second part .

  12. If For each referrer navigable is of changingNavigables , queue a URL record , then set global task on the navigation and traversal task source of document navigable 's referrer active window to run the serialization of referrer . steps:

    Per Fetch , This set of steps are split into two parts to allow synchronous navigations to be processed before documents unload. State is stored in referrer changingNavigableContinuations will be either a URL record or " no-referrer " at this point. for the second part .

    1. Let historyHandling displayedEntry be navigationParams navigable 's active session history handling entry .

    2. Let navigationTimingType targetEntry be the result of switching on navigationParams navigable 's current session history handling : " default entry .

    3. Let changingNavigableContinuation be a changing navigable continuation state with:

      "
      " replace displayed document "
      " navigate displayedEntry 's document "
      " reload target entry "
      " reload targetEntry "
      " entry update navigable "
      " back_forward navigable
      update-only "
      false
    4. Let If redirectCount displayedEntry be 0 if is navigationParams targetEntry and targetEntry 's has cross-origin redirects document state 's reload pending is true; otherwise false, then:

      1. Set navigationParams changingNavigableContinuation 's request update-only 's redirect count . to true.

      2. Create the navigation timing entry Enqueue for document , with navigationParams changingNavigableContinuation 's response 's timing info , on redirectCount , changingNavigableContinuations .

      3. Abort these steps.

      This case occurs due to a synchronous navigation which already updated the active session history entry .

    5. Let navigationTimingType , and oldOrigin be navigationParams targetEntry 's response document state 's service worker timing info origin .

    6. If navigationParams targetEntry 's response document has a ` Refresh is null, or targetEntry 's document state ` header, 's reload pending is true, then:

      1. Let value navTimingType be the isomorphic decoding of the value of the header. " Run the shared declarative refresh steps back_forward with " if document targetEntry and value . We do not currently have a spec for how to handle multiple ` 's document is null; otherwise " Refresh reload ` headers. This is tracked as issue #2900 . ".

      2. If navigationParams 's commit early hints is not null, then call Let navigationParams targetSnapshotParams 's commit early hints be the result of snapshotting target snapshot params with given document navigable .

      3. Process link headers given document , Let navigationParams potentiallyTargetSpecificSourceSnapshotParams 's response , and " pre-media ". Return be document sourceSnapshotParams .

      4. In this example, the child document If potentiallyTargetSpecificSourceSnapshotParams is not allowed to use PaymentRequest , despite being same origin-domain at the time the child document tries null, then set it to use it. At the time the child document is initialized, only the parent document has set document.domain result of snapshotting source snapshot params , and the child given navigable 's active 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 case there is initialized, none no clear source of the documents have set document.domain yet so same origin-domain falls back to a normal same origin check. traversal/reload. We treat this situation as if navigable navigated itself.

        <!-- 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>
      5. Some of the sections below, to which the above algorithm defers in certain cases, require the user agent Attempt to update populate the session history with the new page , entry's document for targetEntry , given some navigation params navigable , potentiallyTargetSpecificSourceSnapshotParams , targetSnapshotParams , with allowPOST set to navigationParams targetEntry 's document state 's reload pending , and a Document completionSteps newDocument . When a user agent is required set to do this, it must queue a global task on the networking navigation and traversal task source , given the relevant global object of the Document object of the current entry (not the new one), to run the following steps: Let sessionHistory be given navigationParams navigable 's browsing context active window 's session history . Let unloadTimingInfo be a new document unload timing info . to continue these steps.

      6. Let previousDocument be Set sessionHistory targetEntry 's current entry document state 's document . reload pending to false.

    7. Unload previousDocument with unloadTimingInfo and If newDocument targetEntry 's relevant global object . If this instance of the navigation algorithm is canceled while this step is running the unload a document algorithm, is null, then the unload a document set changingNavigableContinuation 's update-only algorithm must be allowed to run true.

      This means we tried to completion, but this instance of the navigation algorithm must not run beyond this step. (In particular, for instance, populate the cancelation of this algorithm does not abort any event dispatch or script execution occurring as part document, but were unable to do so, e.g. because of unloading the document or its descendants.) server returning a 204.

    8. If newDocument targetEntry 's event loop document 's origin is not previousDocument oldOrigin , then set targetEntry 's event loop , then the user agent may unload serialized state to null.

      This clears history state when the origin changed vs a previous load of previousDocument targetEntry without a redirect occuring. This can happen due to a change in parallel , In that case, CSP sandbox headers.

    9. If all of the user agent should set following are true:

      then set newDocument targetEntry 's previous document unload timing state 's navigable target name to unloadTimingInfo . the empty string.

    10. Switch on Enqueue navigationParams changingNavigableContinuation 's history handling : on changingNavigableContinuations .

      " entry update " " reload

      The rest of this job runs later " in this algorithm.

  13. Let oldDocument navigablesThatMustWaitBeforeHandlingSyncNavigation be sessionHistory 's current entry 's document an empty set .

  14. For each While entry completedChangeJobs of does not equal sessionHistory totalChangeJobs : if

    1. If entry traversable 's document running nested apply history step is false, then:

      1. While oldDocument , then set entry traversable 's document to newDocument . Traverse the session history traversal queue to sessionHistory 's current entry algorithm set contains one or more synchronous navigation steps with historyHandling a target navigable set to navigationParams 's history handling . " replace not contained " in navigablesThatMustWaitBeforeHandlingSyncNavigation :

        1. Let newEntry steps be a new session history entry whose URL the first item is in newDocument traversable 's URL session history traversal queue and document 's algorithm set that is newDocument . Some browsers copy over the serialized state sessionHistory 's current entry synchronous navigation steps in cases where its URL with a target navigable equals not contained that of in newDocument , but this is inconsistent. See issue #6213 for more discussion on this. navigablesThatMustWaitBeforeHandlingSyncNavigation .

        2. If Remove newDocument steps 's URL requires storing the policy container in history , set from newEntry traversable 's policy container session history traversal queue to navigationParams 's policy container algorithm set .

        3. Insert newEntry into Set sessionHistory traversable after its current entry . 's running nested apply history step to true.

        4. Run steps .

        5. Traverse the history to

          Set newEntry traversable with historyHandling 's running nested apply history step set to " replace ". false.

        " default " Remove all

        Synchronous navigations that are intended to take place before this traversal jump the entries queue at this point, so they can be added to the correct place in sessionHistory traversable after its current entry . (If the current entry is the last entry in the 's session history, then no history entries are removed.) This doesn't necessarily have to affect the user agent's user interface. before this traversal potentially unloads their document. More details can be found here .

    2. Let newEntry changingNavigableContinuation be a new session history entry whose URL is newDocument 's URL and document the result of dequeuing is from newDocument changingNavigableContinuations .

    3. If newDocument changingNavigableContinuation 's URL requires storing the policy container in history , is nothing, then set continue .

    4. Let newEntry displayedDocument 's policy container to be navigationParams changingNavigableContinuation 's policy container displayed document .

    5. Append Let newEntry targetEntry to be sessionHistory . changingNavigableContinuation 's target entry .

    6. Traverse the history to Let newEntry . navigable be changingNavigableContinuation 's navigable .

    7. The Set navigable 's ongoing navigation algorithm has now matured . Try to scroll to the fragment null.

      This allows new navigations for of newDocument . To try to scroll navigable to start, whereas during the fragment for a Document traversal they were blocked.

    8. Let ( document scriptHistoryLength , perform scriptHistoryIndex ) be the following steps in parallel : result of getting the history object length and index given traversable and targetStep .

      These values might have changed since they were last calculated.

    9. Wait for an implementation-defined Append amount of time. (This is intended to allow the user agent navigable to optimize the user experience navigablesThatMustWaitBeforeHandlingSyncNavigation .

      Once a navigable has reached this point in traversal, additionally queued synchronous navigation steps are likely to be intended to occur after this traversal rather than before it, so they no longer jump the face of performance concerns.) queue. More details can be found here .

    10. Queue a global task on the networking navigation and traversal task source given of document navigable 's relevant global object active window to run these the steps:

      1. If document changingNavigableContinuation has no parser, or its parser has stopped parsing , or the user agent has reason to believe the user 's update-only is no longer interested in scrolling to the fragment , then abort these steps. false, then:

        1. Scroll to the fragment Unload displayedDocument given in document targetEntry '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 .

        2. When an HTML document is to be loaded , given navigation params For each navigationParams , the user agent must childNavigable of displayedDocument 's descendant navigables , queue a global task on the networking navigation and traversal task source to: given childNavigable 's active window to unload childNavigable 's active document .

        3. Let Activate history entry document targetEntry be the result of creating and initializing a Document object given " html ", " text/html ", and for navigationParams navigable .

      2. Create an HTML parser and associate it with the If targetEntry 's document . Each task that the networking is not equal to displayedDocument , then queue a global task source places on the navigation and traversal task queue source while fetching runs must then fill the parser's input byte stream given targetEntry 's document with the fetched bytes and cause the HTML parser 's relevant global object to perform the appropriate processing of the input stream. The first task that following step. Otherwise, continue onward to perform the networking task source places on following step within the task queue while fetching runs must process link headers currently-queued task.

      3. Update document for history step application given targetEntry 's document , targetEntry , navigationParams changingNavigableContinuation 's response update-only , scriptHistoryLength , and " media ", after the task has been procesed by scriptHistoryIndex .

      4. Increment completedChangeJobs .

  15. Let totalNonchangingJobs be the HTML parser . size of nonchangingNavigablesThatStillNeedUpdates .

    The input byte stream converts bytes into characters for use in the tokenizer . This process relies, in part, on character encoding information found in step onwards deliberately waits for all the real Content-Type metadata previous operations to complete, as they include processing synchronous navigations of the resource; the computed type is not used for this purpose. which will also post tasks to update history length and index.

  16. When no more bytes are available, Let completedNonchangingJobs be 0.

  17. Let ( scriptHistoryLength , scriptHistoryIndex ) be the user agent must result of getting the history object length and index given traversable and targetStep .

  18. For each navigable of nonchangingNavigablesThatStillNeedUpdates , queue a global task on the networking navigation and traversal task source given the newly-created Document of navigable 's relevant global object active window to run the following steps:

    1. Call Let navigationParams document 's process response end of body with be navigationParams navigable 's response active document .

    2. Have the parser process the implied EOF character, which eventually causes a load Set document 's history object 's index to scriptHistoryIndex .

    3. event

      Set document 's history object 's length to be fired. scriptHistoryLength .

    4. Increment completedNonchangingJobs .

  19. After creating the Wait for completedNonchangingJobs to equal totalNonchangingJobs .

  20. Document

    Set traversable 's current session history step object, but before any script execution, certainly before the parser stops , the user agent must update the to targetStep .

To activate history entry session history with the new page entry given navigationParams entry and the newly-created Document for navigable . navigable :

    7.11.3 Page load processing model for XML files
  1. Save persisted state to the navigable 's active session history entry .

  2. When faced with displaying an XML file inline, provided navigation params Let navigationParams newDocument and a string be 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 entry 's document .

  3. Assert: newDocument 's is initial Document about:blank object document , given " is false, i.e., we never traverse back to the initial xml about:blank ", type , and navigationParams . They must also create a corresponding XML parser . [XML] [XMLNS] [RFC7303] Document [DOM] because it always gets replaced when we navigate away from it.

  4. The first task Set navigable 's active session history entry that the networking task source to entry .

  5. Make active places on newDocument .

To get the task queue while fetching runs must process link headers used step given a traversable navigable document traversable , navigationParams 's response , and " media ", after the task has been procesed by a non-negative integer step , perform the XML parser . following steps. They return a non-negative integer.

At
  1. Let steps be the time result of writing, the XML specification community had not actually yet specified how XML and the DOM interact. getting all used history steps within traversable .

  2. The actual HTTP headers and other metadata, not the headers as mutated or implied by Return the algorithms given greatest item in this specification, are the ones steps 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 less than or equal to that character encoding. Then, with document , the user agent must update the step .

    This caters for situations where there's no session history entry with the new page step 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 step , due to be executed. the removal of a navigable .

When no more bytes are available, To get the user agent must queue history object length and index given a global task traversable navigable on traversable , and a non-negative integer step , perform the networking task source following steps. They return a tuple given of two non-negative integers.

  1. Let document steps 's relevant global object be the result of getting all used history steps to call within navigationParams traversable .

  2. Let scriptHistoryLength 's process response end of body be the size with of navigationParams 's response . steps .

  3. Once parsing is complete, the user agent must set Assert: document steps 's navigation id contains to null. step .

    For HTML documents this is reset when parsing It is complete, after firing assumed that step has been adjusted by getting the load event. used step .

  4. Error messages from the parse process (e.g., XML namespace well-formedness errors) may Let scriptHistoryIndex be reported inline by mutating the Document . 7.11.4 Page load processing model for text files index of step in sessionSteps .

  5. When Return ( scriptHistoryLength , scriptHistoryIndex ).

To get all navigables whose current session history entry will change or reload given a plain text document is to be loaded, provided navigation params traversable navigable navigationParams traversable , and a string non-negative integer type targetStep , perform the user agent must queue following steps. They return a task list on of navigables .

  1. Let results be an empty list .

  2. Let navigablesToCheck be « traversable ».

    This list is extended in the networking task source loop below.

  3. For each to: navigable of navigablesToCheck :

    1. Let document targetEntry be the result of creating and initializing a Document object getting the target history entry given " html ", type , navigable and navigationParams targetStep .

    2. Set If document targetEntry is not navigable 's parser cannot change the mode flag current session history entry to true. Set or document targetEntry 's mode document state 's reload pending is true, then append navigable to " no-quirks ". results .

    3. Create an HTML parser If targetEntry 's document and associate it with the is navigable 's 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 targetEntry 's tokenizer to the PLAINTEXT document state . Each task that the networking task source places on the task queue 's reload pending while fetching runs must is false, then fill the parser's input byte stream extend navigablesToCheck with the fetched bytes and cause the HTML parser child navigables 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 navigable .

      Adding child navigables to the user, are defined navigablesToCheck means those navigables will also be checked by the specifications for the computed MIME type this loop. Child navigables of are only checked if the resource (i.e., type navigable ). The document's character encoding 's active document must be set to the character encoding used to decode the document. will not change as part of this traversal.

  4. The first task Return results .

To get all navigables that the networking task source places on the task queue while fetching runs must process link headers only need history object length/index update given a traversable navigable document traversable , navigationParams 's response , and " media ", after the task has been procesed by a non-negative integer targetStep , perform the HTML parser following steps. They return a list of navigables .

When no more bytes are available,

Other navigables might not be impacted by the user agent must queue traversal. For example, if the response is a global task on 204, the networking task source given currently active document will remain. Additionally, going 'back' after a 204 will change the newly-created Document 's relevant global object to run current session history entry , but the following steps: active session history entry will already be correct.

  1. Call Let navigationParams results 's process response end of body with be an empty list .

  2. Let navigationParams navigablesToCheck 's response . be « traversable ».

    This list is extended in the loop below.

  3. Have the parser process the implied EOF character, which eventually causes a load For each navigable of navigablesToCheck :

      event to be fired. After creating the Document
    1. object, but potentially before the page has finished parsing,

      Let targetEntry be the user agent must update result of getting the session target history with the new page entry given navigationParams navigable and the newly-created Document . targetStep .

    2. User agents may add content to the head element of the Document If targetEntry is navigable 's current session history entry , e.g., linking to a style sheet, providing script, or giving the and targetEntry 's document a title state . 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. 's reload pending is false, then:

      7.11.5 Page load processing model for multipart/x-mixed-replace resources
      1. 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] Append This algorithm is passed navigation params , but it's unclear how exactly navigable to use them. results .

      2. For each body part obtained from the resource, the user agent must run process a navigate response Extend using the new body part and the same browsing context , navigablesToCheck with history handling navigable 's child navigables .

        Adding child navigables set to " replace navigablesToCheck means those navigables will also be checked by this loop. child navigables " are only checked 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 navigable 's active document 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 will not change 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. of this traversal.

        7.11.6 Page load processing model for media
  4. When an image, video, or audio resource is to be loaded, provided navigation params Return results .

To get the target history entry given a navigable navigationParams navigable , and a string non-negative integer type step , perform the user agent should: following steps. They return a session history entry .

  1. Let document entries be the result of creating and initializing a Document object getting session history entries given " html ", type , and for navigationParams navigable .

  2. Set Return the item in document entries 's mode to " no-quirks ". Append an html that has the greatest step element less than or equal to document step .

Append a head To see why getting the target history entry element returns the entry with the greatest step less than or equal to the input step, consider the following Jake diagram :

html element. Append a element to the html body
body 0 1 2 3
top element. Append an element host element for the media, as described below, to the /t /t#foo
frames[0] element. /i-0-a /i-0-b

Set the appropriate attribute of For the element host element , as described below, to input step 1, the address of target history entry for the image, video, or audio resource. Process link headers given document , navigationParams 's response , and " media top ". The element host element to create for the media navigable is the element given in /t entry, whose step is 0, while the table below in target history entry for the second cell of frames[0] navigable is the row /i-0-b entry, whose first cell describes the media. The appropriate attribute to set step is the one given by the third cell in that same row. 1:

Type of media Element for the media Appropriate attribute Image img Video video
0 1 2 3
top src /t /t#foo
frames[0] src /i-0-a /i-0-b

Similarly, given the input step 3 we get the top entry whose step is 3, and the frames[0] entry whose step is 1:

Audio audio 0 1 2 3
top src /t /t#foo
frames[0] /i-0-a /i-0-b

Then, To get all navigables that might experience a cross-document traversal given a traversable navigable traversable , and a non-negative integer targetStep , perform the user agent must act as following steps. They return a list of navigables .

From traversable 's session history traversal queue 's perspective, these documents are candidates for going cross-document during the traversal described by targetStep . They will not experience a cross-document traversal if it had stopped parsing the status code for their target document is HTTP 204 No Content.

Note that if a given navigable might experience a cross-document traversal, this algorithm will return navigable but not its child navigables . Those would end up unloaded , not traversed.

  1. After creating Let results be an empty list .

  2. Let navigablesToCheck be « traversable ».

    This list is extended in the loop below.

  3. Document For each navigable of navigablesToCheck :

      object, but potentially before the page has finished fully loading,
    1. Let targetEntry be the user agent must update result of getting the session target history with the new page entry given navigationParams navigable and the newly-created Document . targetStep .

    2. User agents may add content to the head If targetEntry 's document element of the Document is not navigable 's document , or attributes to the element host element , e.g., to link to a style sheet, to provide a script, to give the targetEntry 's document a title state , or 's reload pending is true, then append navigable to make the media autoplay . results .

      When no more bytes are available, the user agent must queue a global task

      Although navigable 's active history entry on can change synchronously, the networking task source given new entry will always have the newly-created same Document 's relevant global object to call , so accessing navigationParams navigable 's process response end of body document is reliable.

    3. Otherwise, extend navigablesToCheck with navigationParams navigable 's response child navigables .

      Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop. Child navigables are only checked if the navigable 's active document will not change as part of this traversal.

  4. Return results .

7.11.7 7.4.6.2 Page load processing model Updating the document

To update document for content that uses plugins history step application given a Document When document , a resource that requires an external resource to be rendered is to be loaded, provided navigation params session history entry navigationParams and entry , a string boolean type doNotReactivate , the user agent should: and integers scriptHistoryLength and scriptHistoryIndex :

  1. Let document documentIsNew be the result of creating and initializing a Document object true if document 's latest entry given " html ", is null; otherwise false.

  2. Let type , and documentsEntryChanged be true if navigationParams . document 's latest entry is not entry ; otherwise false.

  3. Set document 's mode history object 's index to " no-quirks ". scriptHistoryIndex .

  4. Mark Set document as being a plugin document 's history object 's length to scriptHistoryLength .

  5. Append an If documentsEntryChanged is true, then:

      html
    1. element to

      Let oldURL be document . 's latest entry 's URL .

    2. Append a head Set document 's latest entry element to the html element. entry .

    3. Append a body element to Restore the html history object state element. given document and entry .

    4. Append If documentIsNew is false, then fire an embed event named to the body popstate element. Set the at document 's relevant global object , using src PopStateEvent attribute of , with the embed state element attribute initialized to the address of the resource. document 's history object 's state .

    5. Process link headers Restore persisted state given document , entry .

    6. If navigationParams documentIsNew 's response , is false, and " media ". The term plugin document oldURL 's fragment is used by Content Security Policy as part of the mechanism that ensures iframe s can't be used not equal to evade plugin-types directives. [CSP] entry 's URL Then, the user agent must act as if it had stopped parsing . After creating the Document 's fragment , then queue a global task object, but potentially before the page has finished fully loading, the user agent must update the session history with on the new page DOM manipulation task source given navigationParams document and the newly-created Document 's relevant global object . User agents may add content to the fire an event named head hashchange element of the at document 's relevant global object , using Document HashChangeEvent , or attributes to with the embed oldURL element, e.g. to link to a style sheet or attribute initialized to give the document a title serialization . If of oldURL and the Document newURL 's active sandboxing flag set has its sandboxed plugins browsing context flag set, attribute initialized to the synthesized embed serialization of entry 's URL .

  6. If documentIsNew is true, then:

      element will fail
    1. Try to scroll to render the content . fragment for document .

    2. At this point scripts may run for the newly-created document document .

  7. Otherwise, if documentsEntryChanged is false and doNotReactivate is false, then reactivate document .

    7.11.8 Page load processing model documentsEntryChanged can be false for inline content that doesn't have one of two reasons: either we are restoring from bfcache , or we are asynchronously finishing up a DOM synchronous navigation which already synchronously set document 's latest entry . The doNotReactivate argument distinguishes between these two cases.

To restore the history object state given Document When the user agent is to display a user agent page inline, provided a browsing context document and session history entry browsingContext , the user agent should: entry :

  1. Let navigationParams targetRealm be a new navigation params whose request is null, response document 's relevant Realm .

  2. Let state be null.

  3. If entry 's serialized state is not null, origin is a new opaque origin , final sandboxing flag then set state to StructuredDeserialize 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 ( entry 's serialized state , reserved environment is null, process response end of body is targetRealm ). If this throws an algorithm that does nothing, exception, catch it and browsing context ignore the exception.

  4. Set document 's history object is 's state to browsingContext state . The algorithm called in the next step is not prepared to deal with

To make active a null response . Probably we should synthesize one instead. Document document :

  1. Let document window be the result of creating and initializing a Document document 's relevant global object .

  2. Set document 's browsing context given " html ", " text/html 's WindowProxy ", and 's [[Window]] internal slot value to navigationParams window .

  3. Set document 's mode visibility state to " no-quirks ". document 's node navigable 's traversable navigable 's system visibility state .

  4. Either associate Set document window with 's relevant settings object 's execution ready flag .

To reactivate a custom rendering that is not rendered using the normal Document rendering rules, or mutate document :

This algorithm updates document until after it represents the content the user agent wants to render. Once the page has been set up, the user agent must act as if come out of bfcache , i.e., after 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 made fully active . again.

7.11.9 Navigating to a fragment
  1. To navigate to a fragment given a browsing context For each browsingContext , a URL formControl of form controls in url , a history handling behavior document with an autofill field name historyHandling , and a navigation id of " off navigationId : ", invoke the reset algorithm for formControl .

  2. If historyHandling document 's suspended timer handles is not " empty :

      replace
    1. ", then remove all the entries in

      Assert: browsingContext document 's session history after the current entry . (If the current entry suspension time 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. not zero.

    2. Remove any tasks queued by Let suspendDuration be the history traversal task source that are associated with any Document current high resolution time minus document 's suspension time .

    3. objects in

      Let browsingContext activeTimers be document 's top-level browsing context relevant global object 's document family map of active timers .

    4. Append a new session history entry to the session history whose URL is For each handle in url , document is the current entry 's document suspended timer handles , policy container is the current entry if activeTimers [ handle ] exists , then increase activeTimers [ handle ] by suspendDuration .

  3. If document 's policy-container current document readiness is " complete ", and scroll restoration mode document 's page showing flag is the current entry 's scroll restoration mode . false, then:

    1. Traverse the history Set document 's page showing flag to the new entry, with true.

    2. historyHandling

      set to historyHandling . This will scroll to Update the fragment visibility state given in what is now the document's URL . of document to " visible ".

    3. Invoke WebDriver BiDi fragment navigated with browsingContext , and Fire a new WebDriver BiDi navigation status whose id is navigationId , url is resource 's url , and status page transition event is " named complete pageshow ". If the scrolling fails because the at document 's relevant ID has not yet been parsed, then the original navigation global object algorithm will take care of the scrolling instead, as the last few steps of its update the session history with the new page algorithm. true.

When the user agent is required To try to scroll to the fragment and for a Document document , perform the indicated part following steps in parallel :

  1. Wait for an implementation-defined amount of the document , if any, time. (This is being rendered , intended to allow the user agent must either change the scrolling position of the document using to optimize the following algorithm, or perform some other action such that user experience in the indicated part face of performance concerns.)

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

    1. If there is document has no indicated part, parser, or if the indicated part is not being rendered its parser has stopped parsing , then or the user agent must do nothing. The aforementioned algorithm has reason to believe the user is as follows: no longer interested in scrolling to the fragment , then abort these steps.

    2. Scroll to the fragment given document .

    3. If there is no document 's indicated part of is still null, then try to scroll to the fragment for document , set .

7.4.6.3 Scrolling to a fragment

To scroll to the fragment given a Document document :

  1. If document 's indicated part is null, then set document 's target element to null.

  2. If the Otherwise, if document 's indicated part of the document is the top of the document, document , then:

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

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

    3. Return.

  3. Otherwise:

    1. Assert: document 's indicated part is an element.

    2. Let target be element that is the document 's indicated part of the document .

    3. Set the Document document 's target element to target .

    4. Run the ancestor details revealing algorithm on target .

    5. Run the ancestor hidden-until-found revealing algorithm on target .

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

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

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

A Document 's The indicated part of the document is the one that the its URL 's fragment , identifies, or null if any, identifies. the fragment does not identify anything. 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 an HTML documents (and HTML MIME types document ), document , the following processing model must be followed to determine what the its indicated part of the document is. :

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

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

  3. If find Let potentialIndicatedElement be the result of finding a potential indicated element with given document and fragment .

  4. If potentialIndicatedElement returns non-null, is not null, then the return value is the indicated part of the document ; return. potentialIndicatedElement .

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

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

  7. If find Set potentialIndicatedElement to the result of finding a potential indicated element with given document and decodedFragment .

  8. If potentialIndicatedElement returns non-null, is not null, then the return value is the indicated part of the document ; return. potentialIndicatedElement .

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

  10. There is no indicated part of the document . Return null.

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

  1. If there is an element in the document tree whose root is document and 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 whose root is document 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 "), 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 . If entry 's document is null, then: Assert: historyHandling is " default ". Let request be a new request whose URL is entry 's URL . If explicitHistoryNavigation is true, then set request 's history-navigation flag . 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. Return. Save persisted state to the current 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. If newDocument is different than the current entry 's document , or historyHandling is " entry update " or " reload ", then: If newDocument 's suspended timer handles is not empty : Assert: newDocument 's suspension time is not zero. Let suspendDuration be the current high resolution time minus newDocument 's suspension time . Let activeTimers be newDocument 's relevant global object 's map of active timers . For each handle in newDocument 's suspended timer handles , if activeTimers [ handle ] exists , then increase activeTimers [ handle ] by suspendDuration . Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context 's document family . If newDocument 's origin is not same origin with the current entry 's document 's origin , then: 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 . For each entryToUpdate of entriesToUpdate , set entryToUpdate 's browsing context name to the current browsing context name . 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. Set the active document of the browsing context to newDocument . If entry 's browsing context name is not null, then: Set the browsing context's name to entry 's browsing context name . 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 . For each entryToUpdate of entriesToUpdate , set entryToUpdate 's browsing context name to null. If newDocument has any form controls whose autofill field name is " off ", invoke the reset algorithm of each of those elements. 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: If newDocument 's page showing flag is true, then abort these steps. Set newDocument 's page showing flag to true. Update the visibility state of newDocument to " hidden ". Fire a page transition event named pageshow at newDocument 's relevant global object with true. Set newDocument 's URL to entry 's URL . Let hashChanged be false, and let oldURL and newURL be null. 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 . If historyHandling is " replace ", then remove the entry immediately before entry in the session history . If entry 's persisted user state is null, and its URL 's fragment is non-null, then scroll to the fragment . Set the current entry to entry . Let targetRealm be the current Realm Record . Let state be null. 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. Set newDocument 's History object's state to state . Let stateChanged be true if newDocument has a latest entry , and that entry is not entry ; otherwise let it be false. Set newDocument 's latest entry to entry . 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 . Restore persisted state from entry . If hashChanged is true, then queue a global task on the DOM manipulation task source given newDocument 's relevant global object to fire an event named hashchange at newDocument 's relevant global object , using HashChangeEvent , with the oldURL attribute initialized to oldURL and the newURL attribute initialized to newURL .
7.11.10.1 7.4.6.4 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 . navigable containers .

Child browsing context navigable scroll restoration is handled by the history entry for those browsing contexts' Document s. 7.11.10.2 The PopStateEvent interface ✔ MDN PopStateEvent Support in all current engines. Firefox 4+ Safari 6+ Chrome 4+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android ? Safari iOS ? Chrome Android ? WebView Android ? Samsung Internet ? Opera Android 12.1+ [Exposed=Window] interface { constructor(DOMString type, optional eventInitDict = {}); readonly attribute any ; }; dictionary { any state = null; }; event . state Returns a copy as part 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 ✔ MDN HashChangeEvent Support in all current engines. Firefox 3.6+ Safari 5+ Chrome 8+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android ? Safari iOS 5+ Chrome Android ? WebView Android ? Samsung Internet ? Opera Android 11+ [Exposed=Window] interface { constructor(DOMString type, optional eventInitDict = {}); readonly attribute USVString ; readonly attribute USVString ; }; dictionary { USVString oldURL = ""; USVString newURL = ""; }; event . oldURL ✔ MDN HashChangeEvent/oldURL Support in all current engines. Firefox 6+ Safari 5.1+ Chrome 8+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android ? Safari iOS ? Chrome Android ? WebView Android ? Samsung Internet ? Opera Android 12.1+ Returns the URL of the session history entry that was previously current. event . newURL ✔ MDN HashChangeEvent/newURL Support in all current engines. Firefox 6+ Safari 5.1+ Chrome 8+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android ? Safari iOS ? Chrome Android ? WebView Android ? Samsung Internet ? Opera Android 12.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 ✔ MDN PageTransitionEvent Support in all current engines. Firefox 1.5+ Safari 5+ Chrome 4+ Opera ? Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android ? Safari iOS 4+ Chrome Android ? WebView Android 37+ Samsung Internet ? Opera Android ? [Exposed=Window] interface { constructor(DOMString type, optional eventInitDict = {}); readonly attribute boolean ; }; dictionary { boolean persisted = false; }; event . persisted ✔ MDN PageTransitionEvent/persisted Support in all current engines. Firefox 11+ Safari 5+ Chrome 4+ Opera ? Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android ? Safari iOS 4+ Chrome Android ? WebView Android 37+ Samsung Internet ? Opera Android ? 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 user agent decided to not keep the Document alive in a session history entry after unload Having iframe s that are not salvageable Active WebSocket objects Aborting a Document 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 initialized 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 : Assert: document 's browsing context is non-null. Set document 's completely loaded time to the current time. 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 . 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 . 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: Increase the event loop 's termination nesting level by 1. Increase the document 's unload counter by 1. Let event be the result of creating an event using BeforeUnloadEvent . Initialize event 's type attribute to beforeunload and its cancelable attribute true. Dispatch event at document 's relevant global object . Decrease the event loop 's termination nesting level by 1. Let result be " no-prompt ". If all of the following are true: document 's active sandboxing flag set does not have its sandboxed modals flag set document 's relevant global object has sticky activation event 's canceled flag is set, or the returnValue attribute of event is not the empty string 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: Invoke WebDriver BiDi user prompt opened with document 's relevant global object , " beforeunload ", and "". Pause while waiting for the user's response. If the user confirmed the page navigation, then set result to " confirm "; otherwise to " refuse ". Invoke WebDriver BiDi user prompt closed with document 's relevant global object and true if result is " confirm " or false otherwise. If the recursiveFlag is not set, then: Let descendants be the list of the descendant browsing contexts of document . For each browsingContext in descendants : Let internalResult be the result of calling prompt to unload restoration for browsingContext 's active document with the recursiveFlag set. If internalResult is " refuse ", then return internalResult . Otherwise, if internalResult is " confirm ", set result to internalResult . Decrease the document 's unload counter by 1. Return result . To unload a Document document , given an optional recursiveFlag , a document unload timing info -or-null unloadTimingInfo (default null), and an optional global object newGlobal : Increase the event loop 's termination nesting level by one. Increase document 's unload counter by 1. 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. If document 's page showing flag is true: Set document 's page showing flag to false. Fire a page transition event named pagehide at document 's relevant global object with document 's salvageable state. Update the visibility state of newDocument to " hidden ". If unloadTimingInfo is not null, then set unloadTimingInfo 's unload event start time to the current high resolution time given newGlobal , coarsened given document 's relevant settings object 's cross-origin isolated capability . 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. If unloadTimingInfo is not null, then set unloadTimingInfo 's unload event end time to the current high resolution time given newGlobal , coarsened given document 's relevant settings object 's cross-origin isolated capability . Decrease the event loop 's termination nesting level by one. Set document 's suspension time to the current high resolution time given document 's relevant global object . Set document 's suspended timer handles to the result of getting the keys for the map of active timers . Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications . If the recursiveFlag is not set, then: Let descendants be the list of the descendant browsing contexts of document . For each browsingContext in descendants : Unload the active document of browsingContext with the recursiveFlag set. If the salvageable state of the active document of browsingContext is false, then set the salvageable state of document to false also. If document 's salvageable state is false, then discard document . 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 : Let window be document 's relevant global object . 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. If document 's salvageable state is false, then: For each EventSource object eventSource whose relevant global object is equal to window , forcibly close eventSource . Clear window 's map of active timers . 7.11.12.1 The BeforeUnloadEvent interface ✔ MDN BeforeUnloadEvent Support in all current engines. Firefox 1.5+ Safari 7+ Chrome 30+ Opera ? Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android ? Safari iOS ? Chrome Android ? WebView Android 37+ Samsung Internet 3.0+ Opera Android ? [Exposed=Window] interface { attribute DOMString ; }; 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 : 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. 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. If document 's navigation id is non-null, then: 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 . Set document 's navigation id to null. If document has an active parser , then: Set document 's active parser was aborted to true. Abort that parser . 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: Let browsingContext be document 's browsing context . If browsingContext 's active document is not document , then return. If there is an existing attempt to navigate browsingContext and document 's unload counter is 0, then cancel that navigation . Abort document . 7.11.14 The ` X-Frame-Options ` header ✔ MDN Headers/X-Frame-Options navigables Support in all current engines. Firefox 4+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android ? Samsung Internet ? Opera Android ? 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 : If browsingContext is not a child browsing context , then return true. For each policy of navigationParams 's policy container 's CSP list : If policy 's disposition is not " enforce ", then continue . If policy 's directive set contains a frame-ancestors directive, then return true. Let rawXFrameOptions be the result of getting, decoding, and splitting ` X-Frame-Options ` from navigationParams 's response 's header list . Let xFrameOptions be a new set . For each value of rawXFrameOptions , append value , converted to ASCII lowercase , to xFrameOptions . 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. 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. If xFrameOptions [0] is " deny ", then return false. If xFrameOptions [0] is " sameorigin ", then: Let containerDocument be browsingContext 's container document . While containerDocument is not null: If containerDocument 's origin is not same origin with destinationOrigin , then return false. Let containerBC be containerDocument 's browsing context . Set containerDocument to containerBC 's container document , if containerBC is non-null; otherwise, null. 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 ` Valid Result ` 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. s.

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 .