recursal/MDN huggingface dataset:
Navigation: forward() method
============================

**Experimental:** **This is an experimental technology**  
Check the Browser compatibility table carefully before using this in production.

 The **`forward()`** method of the
 `Navigation` interface navigates forwards by one entry in the navigation history.

Syntax
------


```js
forward(options)
```

### Parameters

`options` Optional

An options object containing the following properties:

`info` Optional

Developer-defined information to be passed along to the `navigate` event, made available in `NavigateEvent.info`. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`.


### Return value

An object with the following properties:

`committed`

A `Promise` which will fulfill when the visible URL has changed and a new `NavigationHistoryEntry` has been created.

`finished`

A `Promise` which will fulfill when all promises returned by the `NavigateEvent.intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires.

Either one of these promises rejects if the navigation has failed for some reason.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `Navigation.currentEntry`'s `NavigationHistoryEntry.index` value is -1 or `navigation.entries().length - 1`, i.e. either the current `Document` is not yet active, or the current history entry is the last one in the history, meaning that forwards navigation is not possible, or if the current `Document` is unloading.

Examples
--------


```js
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigation-forward-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo
Navigation: back() method
=========================

**Experimental:** **This is an experimental technology**  
Check the Browser compatibility table carefully before using this in production.

 The **`back()`** method of the
 `Navigation` interface navigates backwards by one entry in the navigation history.

Syntax
------


```js
back(options)
```

### Parameters

`options` Optional

An options object containing the following properties:

`info` Optional

Developer-defined information to be passed along to the `navigate` event, made available in `NavigateEvent.info`. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`.


### Return value

An object with the following properties:

`committed`

A `Promise` which will fulfill when the visible URL has changed and a new `NavigationHistoryEntry` has been created.

`finished`

A `Promise` which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires.

Either one of these promises rejects if the navigation has failed for some reason.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `Navigation.currentEntry`'s `NavigationHistoryEntry.index` value is -1 or 0, i.e. either the current `Document` is not yet active, or the current history entry is the first one in the history, meaning that backwards navigation is not possible, or if the current `Document` is unloading.

Examples
--------


```js
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigation-back-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo
Navigation: updateCurrentEntry() method
=======================================

**Experimental:** **This is an experimental technology**  
Check the Browser compatibility table carefully before using this in production.

The **`updateCurrentEntry()`** method of the `Navigation` interface updates the `state` of the `currentEntry`; used in cases where the state change will be independent of a navigation or reload.

Syntax
------


```js
updateCurrentEntry()
updateCurrentEntry(options)
```

### Parameters

`options` Optional

An options object containing the following properties:

`state`

Developer-defined information to be stored in the associated `NavigationHistoryEntry` once the navigation is complete, retrievable via `getState()`. This can be any data type. You might, for example, wish to store a page visit count for analytics purposes, or store UI state details so the view can be shown exactly as the user last left it. Any data stored in `state` must be structured-cloneable.


### Return value

None (`undefined`).

### Exceptions

`DataCloneError` `DOMException`

Thrown if the `state` parameter had values included in it that are not structured-cloneable.

`InvalidStateError` `DOMException`

Thrown if the `Navigation.currentEntry` is `null`, i.e. there is no current history entry. This could occur for example if the current page is `about:blank`.

Examples
--------

You could use something like the following to update the open/closed state of a `<details>` element so that the state can be restored when reloading the page or navigating back from somewhere else.


```js
detailsElem.addEventListener("toggle", () => {
  navigation.updateCurrentEntry({ state: { detailOpen: detailsElem.open } });
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigation-updatecurrententry-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo
Navigation: navigate event
==========================

**Experimental:** **This is an experimental technology**  
Check the Browser compatibility table carefully before using this in production.

The **`navigate`** event of the `Navigation` interface is fired when any type of navigation is initiated, allowing you to intercept as required.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.


```js
addEventListener("navigate", (event) => {});

onnavigate = (event) => {};
```

Event type
----------

A `NavigateEvent`. Inherits from `Event`.

Event

NavigateEventExamples
--------

### Handling a navigation using `intercept()`


```js
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) {
    return;
  }

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        // The URL has already changed, so show a placeholder while
        // fetching the new content, such as a spinner or loading page
        renderArticlePagePlaceholder();

        // Fetch the new content and display when ready
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);
      },
    });
  }
});
```


**Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `event.preventDefault()`, perform the appropriate `History.pushState()` call, then set up the page view based on the new URL. And this wouldn't handle all navigations — only user-initiated link clicks.

### Handling scrolling using `scroll()`

In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a `scroll()` call between the two.


```js
navigation.addEventListener("navigate", (event) => {
  if (shouldNotIntercept(navigateEvent)) {
    return;
  }
  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);

        event.scroll();

        const secondaryContent = await getSecondaryContent(url.pathname);
        addSecondaryContent(secondaryContent);
      },
    });
  }
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # event-navigate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo
Navigation: canGoBack property
==============================

**Experimental:** **This is an experimental technology**  
Check the Browser compatibility table carefully before using this in production.

 The **`canGoBack`** read-only property of the
 `Navigation` interface returns `true`
 if it is possible to navigate backwards in the navigation history
 (i.e. the `currentEntry` is
 not the first one in the history entry list),
 and `false` if it is not.

Value
-----

A boolean value: `true` if it is possible to navigate backwards in the navigation history, `false` otherwise.

Examples
--------


```js
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigation-cangoback-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo
Navigation: traverseTo() method
===============================

**Experimental:** **This is an experimental technology**  
Check the Browser compatibility table carefully before using this in production.

The **`traverseTo()`** method of the `Navigation` interface navigates to the `NavigationHistoryEntry` identified by the given `key`.

Syntax
------


```js
traverseTo(key)
traverseTo(key, options)
```

### Parameters

`key`

The `key` of the `NavigationHistoryEntry` to navigate to.

`options` Optional

An options object containing the following properties:

`info` Optional

Developer-defined information to be passed along to the `navigate` event, made available in `NavigateEvent.info`. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`.


### Return value

An object with the following properties:

`committed`

A `Promise` which will fulfill when the visible URL has changed and a new `NavigationHistoryEntry` has been created.

`finished`

A `Promise` which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires.

Either one of these promises rejects if the navigation has failed for some reason.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `Navigation.currentEntry`'s `NavigationHistoryEntry.index` value is -1, meaning the current `Document` is not yet active, of if the navigation history list does not contain a `NavigationHistoryEntry` with the specified key, or if the current `Document` is unloading.

Examples
--------

### Set up home button


```js
function initHomeBtn() {
  // Get the key of the first loaded entry
  // so the user can always go back to this view.
  const { key } = navigation.currentEntry;
  backToHomeButton.onclick = () => {
    navigation.traverseTo(key);
  };
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
  event.intercept({
    async handler() {
      // Navigate to a different view,
      // but the "home" button will always work.
    },
  });
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigation-traverseto-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo
Location: pathname property
===========================

 The **`pathname`** property of the `Location`
 interface is a string containing the path of the URL for the location. If there is no path, `pathname` will be empty: otherwise, `pathname` contains an initial '/' followed by the path of the URL, not including the query string or fragment.

Value
-----

A string.

Examples
--------


```js
// Let's say we are on the URL https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname#examples
console.log(location.pathname); // '/en-US/docs/Web/API/Location/pathname'
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-pathname-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: host property
=======================

 The **`host`** property of the `Location`
 interface is a string containing the host, that is the
 *hostname*, and then, if the *port* of the URL is nonempty, a
 `':'`, and the *port* of the URL.

Value
-----

A string.

Examples
--------


```js
const anchor = document.createElement("a");

anchor.href = "https://developer.mozilla.org/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org");

anchor.href = "https://developer.mozilla.org:443/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org");
// The port number is not included because 443 is the scheme's default port

anchor.href = "https://developer.mozilla.org:4097/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org:4097");
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-host-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: port property
=======================

 The **`port`** property of the `Location`
 interface is a string containing the port number of the URL. If the
 URL does not contain an explicit port number, it will be set to `''`.

Value
-----

A string.

Examples
--------


```js
// Let's an <a id="myAnchor" href="https://developer.mozilla.org:443/en-US/docs/Location.port"> element be in the document
const anchor = document.getElementByID("myAnchor");
const result = anchor.port; // Returns:'443'
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-port-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: search property
=========================

 The **`search`** property of the `Location`
 interface is a search string, also called a *query string*; that is, a
 string containing a `'?'` followed by the parameters of the
 URL.

 Modern browsers provide
 `URLSearchParams`
 and
 `URL.searchParams`
 to make it easy to parse out the parameters from the querystring.

Value
-----

A string.

Examples
--------


```js
// Let an <a id="myAnchor" href="/en-US/docs/Location.search?q=123"> element be in the document
const anchor = document.getElementById("myAnchor");
const queryString = anchor.search; // Returns:'?q=123'

// Further parsing:
const params = new URLSearchParams(queryString);
const q = parseInt(params.get("q")); // is the number 123
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-search-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: toString() method
===========================

 The **`toString()`** stringifier method of the
 `Location` interface returns a string containing the
 whole URL. It is a read-only version of `Location.href`.

Syntax
------


```js
toString()
```

### Parameters

None.

### Return value

A string representing the object's URL.

Examples
--------


```js
// Let's imagine this code is executed on https://example.com/path?search#hash
const result = window.location.toString(); // Returns: 'https://example.com/path?search#hash'
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-href-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: protocol property
===========================

 The **`protocol`** property of the `Location`
 interface is a string representing the protocol scheme of the URL,
 including the final `':'`.

Value
-----

A string.

Examples
--------


```js
// Let's an <a id="myAnchor" href="https://developer.mozilla.org/en-US/Location.protocol"> element be in the document
const anchor = document.getElementById("myAnchor");
const result = anchor.protocol; // Returns:'https:'
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-protocol-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: ancestorOrigins property
==================================

 The **`ancestorOrigins`** read-only
 property of the `Location` interface is a static
 `DOMStringList` containing, in reverse order, the origins of all ancestor
 browsing contexts of the document associated with the given `Location`
 object.

 You can use `location.ancestorOrigins` in the script for a document to
 determine, for example, whenever the document is being framed by a site which you don't
 expect it to be framed by. You can also use it to vary the behavior of the document
 based on what site or list of sites is framing it.

Value
-----

A `DOMStringList`.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-ancestororigins-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: href property
=======================

 The **`href`** property of the `Location`
 interface is a stringifier that returns a string containing the whole
 URL, and allows the href to be updated.

 Setting the value of `href` *navigates* to the provided URL. If you
 want *redirection*, use `location.replace()`. The difference from setting the `href` property value is that when using the `location.replace()` method, after navigating to the given URL, the current page will not be saved in session history — meaning the user won't be able to use the back button to navigate to it.

Value
-----

A string.

Examples
--------


```js
// Lets imagine an <a id="myAnchor" href="https://developer.mozilla.org/en-US/Location/href"> element is in the document
const anchor = document.getElementById("myAnchor");
const result = anchor.href; // Returns: 'https://developer.mozilla.org/en-US/Location/href'
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-href-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: hostname property
===========================

 The **`hostname`** property of the `Location`
 interface is a string containing the domain of the URL.

Value
-----

A string.

Examples
--------


```js
const anchor = document.createElement("a");
anchor.href = "https://developer.mozilla.org:4097/en-US/docs/Location.hostname";

console.log(anchor.hostname); // developer.mozilla.org
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-hostname-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Location: reload() method
=========================

The **`reload()`** method of the `Location` interface reloads the current URL, like the Refresh button.

Syntax
------


```js
reload()
```

### Parameters

`forceGet` 
Non-standard

Pass `true` to force a reload bypassing the cache. Defaults to `false`. Only supported in Firefox.

### Return value

None (`undefined`).

### Exceptions

`SecurityError` `DOMException`

Thrown if the origin of the script calling the method is not the same origin of the page originally described by the `Location` object, mostly when the script is hosted on a different domain.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-location-reload-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `Location` interface it belongs to.
* Similar methods: `Location.assign()` and
 `Location.replace()`.