1. 7.8 Session history and navigation
      1. 7.8.1 Browsing sessions
      2. 7.8.2 The session history of browsing contexts
      3. 7.8.3 The History interface
      4. 7.8.4 The Location interface

7.8 Session history and navigation

7.8.1 Browsing sessions

A browsing session is …. See whatwg/html issue #4782 and whatwg/html issue #5350 for defining browsing session. It is roughly analogous to a top-level browsing context except that it cannot be replaced due to a `Cross-Origin-Opener-Policy` header or navigation.

A top-level browsing context has an associated browsing session which is a browsing session.

The browsing session of an environment settings object environment is the result of running these steps:

  1. Assert: environment has a responsible document.

  2. Return environment's responsible document's browsing context's top-level browsing context's browsing session.

7.8.2 The session history of browsing contexts

The sequence of Documents in a browsing context is its session history. Each browsing context, including child browsing contexts, has a distinct session history. A browsing context's session history consists of a flat list of session history entries.

Each Document object in a browsing context's session history is associated with a unique History object which must all model the same underlying session history.


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

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

Several contiguous entries in a session history can share the same document. 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 (and that are therefore merely different states of one particular document) are contiguous by definition.


At any point, one of the entries in the session history is the current entry. This is the entry representing the active document of the browsing context. Which entry is the current entry is changed by the algorithms defined in this specification, e.g., during session history traversal.

The current entry is usually the initial entry created upon navigation. However, it can also be one of the contiguous entries that share the same document, as described above.

Each Document in a browsing context can also have a latest entry. This is the entry for that Document to which the browsing context's session history was most recently traversed. When a Document is created, it initially has no latest entry.

7.8.3 The History interface

History

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Window/history

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
window.history.length

Returns the number of entries in the joint session history.

window.history.scrollRestoration [ = value ]

Returns the scroll restoration mode of the current entry in the session history.

Can be set, to change the scroll restoration mode of the current entry in the session history.

window.history.state

Returns the current serialized state, deserialized into an object.

window.history.go([ delta ])

Goes back or forward the specified number of steps in the joint session history.

A zero delta will reload the current page.

If the delta is out of range, does nothing.

window.history.back()

Goes back one step in the joint session history.

If there is no previous page, does nothing.

window.history.forward()

Goes forward one step in the joint session history.

If there is no next page, does nothing.

window.history.pushState(data, "")

Push a new entry into session history with the given data associated. The current entry's URL will be copied over and used for the new entry's URL.

(The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.)

window.history.pushState(data, "", url)

Push a new entry into session history with the given data associated, and with its URL set to url.

If the current Document cannot have its URL rewritten to url, a "SecurityError" DOMException will be thrown.

(The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.)

window.history.replaceState(data, "")

Updates the data stored in the current session history entry to data.

(The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.)

window.history.replaceState(data, "", url)

Updates the data stored in the current session history entry to data, and its URL to url.

If the current Document cannot have its URL rewritten to url, a "SecurityError" DOMException will be thrown.

(The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.)

The joint session history of a top-level browsing context is the union of all the session histories of all browsing contexts of all the fully active Document objects that share that top-level browsing context, with all the entries that are current entries in their respective session histories removed except for the current entry of the joint session history.

The current entry of the joint session history is the entry that most recently became a current entry in its session history.

Entries in the joint session history are ordered chronologically by the time they were added to their respective session histories. Each entry has an index; the earliest entry has index 0, and the subsequent entries are numbered with consecutively increasing integers (1, 2, 3, etc).

Since each Document in a browsing context might have a different event loop, the actual state of the joint session history can be somewhat nebulous. For example, two sibling iframe elements could both traverse from one unique origin to another at the same time, so their precise order might not be well-defined; similarly, since they might only find out about each other later, they might disagree about the length of the joint session history.

A Document document can have its URL rewritten to a URL targetURL if the following algorithm returns true:

  1. Let documentURL be document's URL.

  2. If targetURL and documentURL differ in their scheme, username, password, host, or port components, then return false.

  3. If targetURL's scheme is an HTTP(S) scheme, then return true. (Differences in path, query, and fragment are allowed for http: and https: URLs.)

  4. If targetURL's scheme is "file", and targetURL and documentURL differ in their path component, then return false. (Differences in query and fragment are allowed for file: URLs.)

  5. If targetURL and documentURL differ in their path component or query components, then return false. (Only differences in fragment are allowed for other types of URLs.)

  6. Return true.

document's URL targetURL can have its URL rewritten
https://example.com/home https://example.com/home#about
https://example.com/home https://example.com/home?page=shop
https://example.com/home https://example.com/shop
https://example.com/home https://user:pass@example.com/home
https://example.com/home http://example.com/home
file:///path/to/x file:///path/to/x#hash
file:///path/to/x file:///path/to/x?search
file:///path/to/x file:///path/to/y
about:blank about:blank#hash
about:blank about:blank?search
about:blank about:srcdoc
data:text/html,foo data:text/html,foo#hash
data:text/html,foo data:text/html,foo?search
data:text/html,foo data:text/html,bar
data:text/html,foo data:bar
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43#hash
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43?search
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/anything
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:path

Note how only the URL of the Document matters, and not its origin. They can mismatch in cases like about:blank Documents with inherited origins, in sandboxed iframes, or when the document.domain setter has been used.

Consider a game where the user can navigate along a line, such that the user is always at some coordinate, and such that the user can bookmark the page corresponding to a particular coordinate, to return to it later.

A static page implementing the x=5 position in such a game could look like the following:

<!DOCTYPE HTML>
<!-- this is https://example.com/line?x=5 -->
<html lang="en">
<title>Line Game - 5</title>
<p>You are at coordinate 5 on the line.</p>
<p>
 <a href="?x=6">Advance to 6</a> or
 <a href="?x=4">retreat to 4</a>?
</p>

The problem with such a system is that each time the user clicks, the whole page has to be reloaded. Here instead is another way of doing it, using script:

<!DOCTYPE HTML>
<!-- this starts off as https://example.com/line?x=5 -->
<html lang="en">
<title>Line Game - 5</title>
<p>You are at coordinate <span id="coord">5</span> on the line.</p>
<p>
 <a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or
 <a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>?
</p>
<script>
 var currentPage = 5; // prefilled by server
 function go(d) {
   setupPage(currentPage + d);
   history.pushState(currentPage, "", '?x=' + currentPage);
 }
 onpopstate = function(event) {
   setupPage(event.state);
 }
 function setupPage(page) {
   currentPage = page;
   document.title = 'Line Game - ' + currentPage;
   document.getElementById('coord').textContent = currentPage;
   document.links[0].href = '?x=' + (currentPage+1);
   document.links[0].textContent = 'Advance to ' + (currentPage+1);
   document.links[1].href = '?x=' + (currentPage-1);
   document.links[1].textContent = 'retreat to ' + (currentPage-1);
 }
</script>

In systems without script, this still works like the previous example. However, users that do have script support can now navigate much faster, since there is no network access for the same experience. Furthermore, contrary to the experience the user would have with just a naïve script-based approach, bookmarking and navigating the session history still work.

In the example above, the data argument to the pushState() method is the same information as would be sent to the server, but in a more convenient form, so that the script doesn't have to parse the URL each time the user navigates.

Most applications want to use the same scroll restoration mode value for all of their history entries. To achieve this they can set the scrollRestoration attribute as soon as possible (e.g., in the first script element in the document's head element) to ensure that any entry added to the history session gets the desired scroll restoration mode.

<head>
  <script>
       if ('scrollRestoration' in history)
            history.scrollRestoration = 'manual';
  </script>
</head>
   

7.8.4 The Location interface

Document/location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Window/location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Each Window object is associated with a unique instance of a Location object, allocated when the Window object is created.

document.location [ = value ]
window.location [ = value ]

Returns a Location object with the current page's location.

Can be set, to navigate to another page.

Location objects provide a representation of the URL of the active document of their Document's browsing context, and allow the current entry of the browsing context's session history to be changed, by adding or replacing entries in the history object.

location.toString()
location.href

Returns the Location object's URL.

Can be set, to navigate to the given URL.

location.origin

Returns the Location object's URL's origin.

location.protocol

Returns the Location object's URL's scheme.

Can be set, to navigate to the same URL with a changed scheme.

location.host

Returns the Location object's URL's host and port (if different from the default port for the scheme).

Can be set, to navigate to the same URL with a changed host and port.

location.hostname

Returns the Location object's URL's host.

Can be set, to navigate to the same URL with a changed host.

location.port

Returns the Location object's URL's port.

Can be set, to navigate to the same URL with a changed port.

location.pathname

Returns the Location object's URL's path.

Can be set, to navigate to the same URL with a changed path.

location.search

Returns the Location object's URL's query (includes leading "?" if non-empty).

Can be set, to navigate to the same URL with a changed query (ignores leading "?").

location.hash

Returns the Location object's URL's fragment (includes leading "#" if non-empty).

Can be set, to navigate to the same URL with a changed fragment (ignores leading "#").

location.assign(url)

Navigates to the given URL.

location.replace(url)

Removes the current page from the session history and navigates to the given URL.

location.reload()

Reloads the current page.

location.ancestorOrigins

Returns a DOMStringList object listing the origins of the ancestor browsing contexts, from the parent browsing context to the top-level browsing context.