From f74c58c289ee4ce68f40ed89272b75fae3a19ca1 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Mon, 31 Oct 2022 11:32:01 +0000 Subject: [PATCH 01/50] add docs for the Navigation API --- files/en-us/web/api/navigation_api/index.md | 194 ++++++++++++++++++++ files/jsondata/GroupData.json | 15 ++ 2 files changed, 209 insertions(+) create mode 100644 files/en-us/web/api/navigation_api/index.md diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md new file mode 100644 index 000000000000000..b029905b503ae73 --- /dev/null +++ b/files/en-us/web/api/navigation_api/index.md @@ -0,0 +1,194 @@ +--- +title: Navigation API +slug: Web/API/Navigation_API +page-type: web-api-overview +tags: + - API + - History + - Landing + - Navigate + - Navigation + - Navigation API + - Overview + - Scroll + - Traversal +browser-compat: + - api.Navigation + - api.NavigateEvent + - api.Window.navigation +--- + +{{securecontext_header}}{{seecompattable}}{{DefaultAPISidebar("Navigation API")}} + +The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also introspect an application's history entries. This is a successor to previous web platform features such as [The History API](/en-US/docs/Web/API/History_API) and {{domxref("window.location")}}, which solves their shortcomings and is specifically aimed at the needs of {{glossary("SPA", "single-page applications (SPAs)")}}. + +## Concepts and Usage + +In SPAs, the page template tends to stay the same during usage, and the content is dynamically rewritten as the user visits different pages or features. As a result, only one distinct page is loaded in the browser, which breaks the expected user experience of navigating back and forth between different locations in the viewing history. This problem can be solved to a degree via [The History API](/en-US/docs/Web/API/History_API), but it is not designed for the needs of SPAs. The Navigation API aims to bridge that gap. + +The API is accessed via the {{domxref("Window.navigation")}} property, which returns a reference to a global {{domxref("Navigation")}} object. Each `window` object has its own corresponding `navigation` instance. + +### Handling navigations + +`navigation` has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place. The `navigate` event has an event object of type {{domxref("NavigateEvent")}}, which contains detailed information including the navigation's destination URL, type, whether it contains `POST` form data or a download request, and more. + +It also contains two methods: + +- {{domxref("NavigateEvent.intercept", "intercept()")}} allows you to control what happens when the navigation is initiated using a callback handler function, which should return a promise. For example, in the case of an SPA, it can be used to load relevant new content into the UI based on the path of the URL navigated to. +- {{domxref("NavigateEvent.scroll", "scroll()")}} allows you to manually initiate the browser's scroll behavior (e.g. to a fragment identifier in the URL), if it makes sense for your code, rather than waiting for the browser to handle it automatically. + +Once a navigation is initiated, and your `intercept()` handler is called, a {{domxref("NavigationTransition")}} object instance is created (accessible via {{domxref("Navigation.transition")}}), which can be used used to track the process of the ongoing navigation. + +> **Note:** In this context "transition" refers to the transition between one history entry and another. It isn't related to CSS transitions. + +> **Note:** You can also call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely. + +When the `initiate()` handler function's promise fulfills, the `Navigate` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases if it is needed. + +### Programmatically traversing the navigation history + +As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct {{domxref("NavigationHistoryEntry")}} object instance. These contain several useful properties such as the entry's key, URL, and state information. You can return the entry that the user is currently navigated to right now using {{domxref("Navigation.currentEntry","currentEntry")}}, and an array of all existing history entries using {{domxref("Navigation.entries", "entries()")}}. Each `NavigationHistoryEntry` object has a {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} event, which fires when the entry is no longer part of the browser history (e.g. navigate back three times, then navigate forwards to somewhere else. Those three history entries will be disposed). + +The `Navigation` object contains all the methods you'll need to traverse through the navigation history: + +- {{domxref("Navigation.navigate", "navigate()")}} navigates to a new URL, creating a new navigation history entry. +- {{domxref("Navigation.reload", "reload()")}} reloads the current navigation history entry. +- {{domxref("Navigation.back", "back()")}} navigates to the previous navigation history entry, if that is possible. +- {{domxref("Navigation.forward", "forward()")}} navigates to the next navigation history entry, if that is possible. +- {{domxref("Navigation.traverseTo", "traverseTo()")}} navigates to a specific navigation history entry identified by its key value, which is obtained via the relevant entry's {{domxref("NavigationHistoryEntry.key")}} property. + +Each one of the above methods returns an object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: + +- `committed` fulfills, meaning that the visible URL has changed and a new NavigationHistoryEntry has been created. +- `finished` fulfills, meaning that all promises returned by your `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, as mentioned earlier. +- either one of the above promises rejects, meaning that the navigation transition has failed for some reason. + +### State + +The Navigation API allows you to store state on each history entry. This is developer-defined information — it can be whatever you like. For example, you might want to store a `visitCount` property that records the number of times a view has been visited, or an object containing multiple properties. + +To get a {{domxref("NavigationHistoryEntry")}}'s state, you call its {{domxref("NavigationHistoryEntry.getState", "getState()")}} method. It is initially `undefined`, but when state information is set on the entry, it will return the previously-set state information. + +Setting state is a bit more nuanced. You can't retrieve the state value and then update it directly — the copy stored on the entry will not change. Instead, you need to update it while performing a {{domxref("Navigation.navigate", "navigate()")}} or {{domxref("Navigation.reload", "reload()")}} — each one of these optionally takes an options object parameter, which includes a `state` property containing the new state to set on the history entry. When these navigations complete, the state change will be automatically applied. + +In other cases a state change is not automatically applied, and you will need to do it manually once the navigation has completed. This is handled using {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}. The {{domxref("Navigation/currententrychange_event", "currententrychange")}} will fire when the current entry change is complete. + +(I'M REALLY NOT SURE IF THIS SECTION ON STATE IS ACCURATE. I AM KINDA GUESSING AT THE "AUTOMATIC BEHAVIOR" MENTIONED ABOVE, AND WHEN UPDATECURRENTENTRY() SHOULD BE USED. NONE OF THE MATERIAL I'VE FOUND SEEMS PARTICULARLY CLEAR ON THIS POINT.) + +### Limitations + +There are a few perceived limitations with the Navigation API, which may or may not be limitating depending on how your app is set up. Find out about these by reading [Modern client-side routing: the Navigation API > What's missing?](https://developer.chrome.com/docs/web-platform/navigation-api/#whats-missing) + +## Interfaces + +- {{domxref("Navigation")}} + - : Allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, introspecting navigation history entries, and managing navigations as they happen. +- {{domxref("NavigationDestination")}} + - : Represents the destination being navigated to in the current navigation. +- {{domxref("NavigationHistoryEntry")}} + - : Represents a single navigation history entry. +- {{domxref("NavigationTransition")}} + - : Represents an ongoing navigation. +- {{domxref("NavigationCurrentEntryChangeEvent")}} + - : Event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the currently navigated to history entry changes. Provides access to the navigation type, and the previous history entry that was navigated from. +- {{domxref("NavigateEvent")}} + - : Event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated. Provides access to information about that navigation, and most notably the {{domxref("NavigateEvent.intercept", "intercept()")}}, which allows you to control what happens when the navigation is initiated. + +## Extensions to the `Window` interface + +- {{domxref("Window.navigation")}} + - : Returns the current `window`'s associated {{domxref("Navigation")}} object. Entry point for the API. + +## Examples + +> **Note:** Check out Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/). + +### Handling a navigation using `intercept()` + +```js +navigation.addEventListener('navigate', navigateEvent => { + // Exit early if this navigation shouldn't be intercepted, + // e.g. if the navigation is cross-origin, or a download request + if (shouldNotIntercept(navigateEvent)) return; + + const url = new URL(navigateEvent.destination.url); + + if (url.pathname.startsWith('/articles/')) { + navigateEvent.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); + }, + }); + } +}); +``` + +### Handling scrolling using `scroll()` + +```js +navigation.addEventListener('navigate', navigateEvent => { + if (shouldNotIntercept(navigateEvent)) return; + const url = new URL(navigateEvent.destination.url); + + if (url.pathname.startsWith('/articles/')) { + navigateEvent.intercept({ + async handler() { + const articleContent = await getArticleContent(url.pathname); + renderArticlePage(articleContent); + navigateEvent.scroll(); + + const secondaryContent = await getSecondaryContent(url.pathname); + addSecondaryContent(secondaryContent); + }, + }); + } +}); +``` + +### Traversing to a specific history entry + +```js +// On JS startup, get the key of the first loaded page +// so the user can always go back there. +const {key} = navigation.currentEntry; +backToHomeButton.onclick = () => navigation.traverseTo(key); + +// Navigate away, but the button will always work. +await navigation.navigate('/another_url').finished; +``` + +### Updating state + +```js +navigation.navigate(url, {state: newState}); +``` + +Or + +```js +navigation.reload({state: newState}); +``` + +Or if the state could not be updated automatically during a navigation transition: + +```js +navigation.updateCurrentEntry({state: newState}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) diff --git a/files/jsondata/GroupData.json b/files/jsondata/GroupData.json index 01cd81977eb8545..7220a43cc2d64bf 100644 --- a/files/jsondata/GroupData.json +++ b/files/jsondata/GroupData.json @@ -873,6 +873,21 @@ "properties": [], "events": [] }, + "Navigation API": { + "overview": ["Navigation API"], + "guides": [], + "interfaces": [ + "NavigateEvent", + "Navigation", + "NavigationCurrentEntryChangeEvent", + "NavigationDestination", + "NavigationHistoryEntry", + "NavigationTransition" + ], + "methods": [], + "properties": ["Window.navigation"], + "events": [] + }, "Navigation Timing": { "overview": ["Navigation timing API"], "guides": ["/docs/Web/API/Navigation_timing_API/Using_Navigation_Timing"], From 91e37e251e69954273e0c0e3c065f0bdb730a89e Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 1 Nov 2022 07:15:50 +0000 Subject: [PATCH 02/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: Domenic Denicola --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index b029905b503ae73..9da5efbdec23ed5 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -43,7 +43,7 @@ Once a navigation is initiated, and your `intercept()` handler is called, a {{do > **Note:** You can also call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely. -When the `initiate()` handler function's promise fulfills, the `Navigate` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases if it is needed. +When the `intercept()` handler function's promise fulfills, the `Navigate` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases if it is needed. ### Programmatically traversing the navigation history From 388f304144bd5e1218e65516c247fc56be67e23a Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 1 Nov 2022 07:16:05 +0000 Subject: [PATCH 03/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: Domenic Denicola --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 9da5efbdec23ed5..c53fda5aa11413a 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -69,7 +69,7 @@ The Navigation API allows you to store state on each history entry. This is deve To get a {{domxref("NavigationHistoryEntry")}}'s state, you call its {{domxref("NavigationHistoryEntry.getState", "getState()")}} method. It is initially `undefined`, but when state information is set on the entry, it will return the previously-set state information. -Setting state is a bit more nuanced. You can't retrieve the state value and then update it directly — the copy stored on the entry will not change. Instead, you need to update it while performing a {{domxref("Navigation.navigate", "navigate()")}} or {{domxref("Navigation.reload", "reload()")}} — each one of these optionally takes an options object parameter, which includes a `state` property containing the new state to set on the history entry. When these navigations complete, the state change will be automatically applied. +Setting state is a bit more nuanced. You can't retrieve the state value and then update it directly — the copy stored on the entry will not change. Instead, you need to update it while performing a {{domxref("Navigation.navigate", "navigate()")}} or {{domxref("Navigation.reload", "reload()")}} — each one of these optionally takes an options object parameter, which includes a `state` property containing the new state to set on the history entry. When these navigations commit, the state change will be automatically applied. In other cases a state change is not automatically applied, and you will need to do it manually once the navigation has completed. This is handled using {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}. The {{domxref("Navigation/currententrychange_event", "currententrychange")}} will fire when the current entry change is complete. From a9ca2668f5ede53cae9633385256130c4d3b816d Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 1 Nov 2022 07:16:23 +0000 Subject: [PATCH 04/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: Domenic Denicola --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index c53fda5aa11413a..22088a321dbd487 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -107,7 +107,7 @@ There are a few perceived limitations with the Navigation API, which may or may ```js navigation.addEventListener('navigate', navigateEvent => { - // Exit early if this navigation shouldn't be intercepted, + // Exit early if this navigation shouldn't be intercepted, // e.g. if the navigation is cross-origin, or a download request if (shouldNotIntercept(navigateEvent)) return; From 03a56c76a2eaa211efa759d692d5f7b44f4610f4 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 1 Nov 2022 07:45:30 +0000 Subject: [PATCH 05/50] updating landing page according to domenics comments --- files/en-us/web/api/navigation_api/index.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 22088a321dbd487..1a021106f17ead0 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -18,7 +18,7 @@ browser-compat: - api.Window.navigation --- -{{securecontext_header}}{{seecompattable}}{{DefaultAPISidebar("Navigation API")}} +{{seecompattable}}{{DefaultAPISidebar("Navigation API")}} The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also introspect an application's history entries. This is a successor to previous web platform features such as [The History API](/en-US/docs/Web/API/History_API) and {{domxref("window.location")}}, which solves their shortcomings and is specifically aimed at the needs of {{glossary("SPA", "single-page applications (SPAs)")}}. @@ -41,7 +41,7 @@ Once a navigation is initiated, and your `intercept()` handler is called, a {{do > **Note:** In this context "transition" refers to the transition between one history entry and another. It isn't related to CSS transitions. -> **Note:** You can also call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely. +> **Note:** In future implementations you will be able to call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely. This is specced out, but not currently implemented anywhere. When the `intercept()` handler function's promise fulfills, the `Navigate` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases if it is needed. @@ -69,15 +69,13 @@ The Navigation API allows you to store state on each history entry. This is deve To get a {{domxref("NavigationHistoryEntry")}}'s state, you call its {{domxref("NavigationHistoryEntry.getState", "getState()")}} method. It is initially `undefined`, but when state information is set on the entry, it will return the previously-set state information. -Setting state is a bit more nuanced. You can't retrieve the state value and then update it directly — the copy stored on the entry will not change. Instead, you need to update it while performing a {{domxref("Navigation.navigate", "navigate()")}} or {{domxref("Navigation.reload", "reload()")}} — each one of these optionally takes an options object parameter, which includes a `state` property containing the new state to set on the history entry. When these navigations commit, the state change will be automatically applied. +Setting state is a bit more nuanced. You can't retrieve the state value and then update it directly — the copy stored on the entry will not change. Instead, you update it while performing a {{domxref("Navigation.navigate", "navigate()")}} or {{domxref("Navigation.reload", "reload()")}} — each one of these optionally takes an options object parameter, which includes a `state` property containing the new state to set on the history entry. When these navigations commit, the state change will be automatically applied. -In other cases a state change is not automatically applied, and you will need to do it manually once the navigation has completed. This is handled using {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}. The {{domxref("Navigation/currententrychange_event", "currententrychange")}} will fire when the current entry change is complete. - -(I'M REALLY NOT SURE IF THIS SECTION ON STATE IS ACCURATE. I AM KINDA GUESSING AT THE "AUTOMATIC BEHAVIOR" MENTIONED ABOVE, AND WHEN UPDATECURRENTENTRY() SHOULD BE USED. NONE OF THE MATERIAL I'VE FOUND SEEMS PARTICULARLY CLEAR ON THIS POINT.) +In some cases however, a state change will be independent from a navigation or reload — for example when a page contains an expandable/collapsible {{htmlelement("details")}} element. In this case, you might want to store the expanded/collapsed state in your history entry, so you can restore it when the user returns to the page or restarts their browser. Cases like this are handled using {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}. The {{domxref("Navigation/currententrychange_event", "currententrychange")}} will fire when the current entry change is complete. ### Limitations -There are a few perceived limitations with the Navigation API, which may or may not be limitating depending on how your app is set up. Find out about these by reading [Modern client-side routing: the Navigation API > What's missing?](https://developer.chrome.com/docs/web-platform/navigation-api/#whats-missing) +There are a few perceived limitations with the Navigation API, which may or may not be limiting depending on how your app is set up. Find out about these by reading [Modern client-side routing: the Navigation API > What's missing?](https://developer.chrome.com/docs/web-platform/navigation-api/#whats-missing) ## Interfaces @@ -175,7 +173,7 @@ Or navigation.reload({state: newState}); ``` -Or if the state could not be updated automatically during a navigation transition: +Or if the state is independent from a navigation or reload: ```js navigation.updateCurrentEntry({state: newState}); @@ -192,3 +190,4 @@ navigation.updateCurrentEntry({state: newState}); ## See also - [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) From 6b7a9043c30f0504db8633c748d742eaf9d160b2 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 2 Nov 2022 10:59:35 +0000 Subject: [PATCH 06/50] remaining interface pages plus assorted fixes --- files/en-us/web/api/navigateevent/index.md | 125 ++++++++++++++++ files/en-us/web/api/navigation/index.md | 141 ++++++++++++++++++ files/en-us/web/api/navigation_api/index.md | 16 +- .../index.md | 73 +++++++++ .../web/api/navigationdestination/index.md | 84 +++++++++++ .../web/api/navigationhistoryentry/index.md | 79 ++++++++++ .../web/api/navigationtransition/index.md | 55 +++++++ files/en-us/web/api/window/index.md | 4 +- .../en-us/web/api/window/navigation/index.md | 44 ++++++ 9 files changed, 614 insertions(+), 7 deletions(-) create mode 100644 files/en-us/web/api/navigateevent/index.md create mode 100644 files/en-us/web/api/navigation/index.md create mode 100644 files/en-us/web/api/navigationcurrententrychangeevent/index.md create mode 100644 files/en-us/web/api/navigationdestination/index.md create mode 100644 files/en-us/web/api/navigationhistoryentry/index.md create mode 100644 files/en-us/web/api/navigationtransition/index.md create mode 100644 files/en-us/web/api/window/navigation/index.md diff --git a/files/en-us/web/api/navigateevent/index.md b/files/en-us/web/api/navigateevent/index.md new file mode 100644 index 000000000000000..ab4ae12a3dabc54 --- /dev/null +++ b/files/en-us/web/api/navigateevent/index.md @@ -0,0 +1,125 @@ +--- +title: NavigateEvent +slug: Web/API/NavigateEvent +page-type: web-api-interface +tags: + - API + - History + - Interface + - Landing + - Navigate + - NavigateEvent + - Navigation API + - Scroll + - Traversal +browser-compat: api.NavigateEvent +--- + +{{DefaultAPISidebar("Navigation API")}} + +The **`NavigateEvent`** interface of the {{domxref("Navigation API")}} is the event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated (this includes usage of History API features like {{domxref("History.go()")}}). `NavigateEvent` provides access to information about that navigation, and allows developers to intercept and control the navigation handling. + +{{InheritanceDiagram}} + +## Constructor + +- {{domxref("NavigateEvent.NavigateEvent", "NavigateEvent()")}} + - : Creates a new `NavigateEvent` object instance. + +## Instance properties + +_Inherits properties from its parent, {{DOMxRef("Event")}}._ + +- {{domxref("NavigateEvent.canIntercept", "canIntercept")}} {{ReadOnlyInline}} + - : Returns `true` if the navigation can be intercepted, or `false` otherwise (e.g. you can't intercept a cross-origin navigation). +- {{domxref("NavigateEvent.destination", "destination")}} {{ReadOnlyInline}} + - : Returns the URL being navigated to. +- {{domxref("NavigateEvent.downloadRequest", "downloadRequest")}} {{ReadOnlyInline}} + - : Returns the filename of the file requested for download, in the case of a download navigation (e.g. an {{htmlelement("a")}} or {{htmlelement("area")}} element with a `download` attribute), or `null` otherwise. +- {{domxref("NavigateEvent.formData", "formData")}} {{ReadOnlyInline}} + - : Returns the {{domxref("FormData")}} object representing the submitted data in the case of a `POST` form submission, or null otherwise. +- {{domxref("NavigateEvent.hashChange", "hashChange")}} {{ReadOnlyInline}} + - : Returns `true` if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document), or `false` otherwise. +- {{domxref("NavigateEvent.info", "info")}} {{ReadOnlyInline}} + - : Returns the `info` data value passed by the initiating navigation operation (e.g. {{domxref("Navigation.back()")}}, or {{domxref("Navigation.navigate()")}}), or `undefined` if no `info` data was passed. +- {{domxref("NavigateEvent.navigationType", "navigationType")}} {{ReadOnlyInline}} + - : Returns the type of the navigation, which is one of `push`, `reload`, `replace`, or `traverse`. +- {{domxref("NavigateEvent.signal", "signal")}} {{ReadOnlyInline}} + - : Returns an {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button). +- {{domxref("NavigateEvent.userInitiated", "userInitiated")}} {{ReadOnlyInline}} + - : Returns `true` if the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons), or `false` otherwise. + +## Instance methods + +_Inherits methods from its parent, {{DOMxRef("Event")}}._ + +- {{domxref("NavigateEvent.intercept", "intercept()")}} + - : Intercepts this navigation, turning it into a same-document navigation to the {{domxref("NavigateEvent.destination", "destination")}} URL. It can accept a handler that defines what the navigation handling behavior should be, plus options to control autofocus ansd scroll behavior as desired. +- {{domxref("NavigateEvent.scroll", "scroll()")}} + - : Can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed. + +## Examples + +### Handling a navigation using `intercept()` + +```js +navigation.addEventListener('navigate', navigateEvent => { + // Exit early if this navigation shouldn't be intercepted, + // e.g. if the navigation is cross-origin, or a download request + if (shouldNotIntercept(navigateEvent)) return; + + const url = new URL(navigateEvent.destination.url); + + if (url.pathname.startsWith('/articles/')) { + navigateEvent.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:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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()` + +```js +navigation.addEventListener('navigate', navigateEvent => { + if (shouldNotIntercept(navigateEvent)) return; + const url = new URL(navigateEvent.destination.url); + + if (url.pathname.startsWith('/articles/')) { + navigateEvent.intercept({ + async handler() { + const articleContent = await getArticleContent(url.pathname); + renderArticlePage(articleContent); + navigateEvent.scroll(); + + const secondaryContent = await getSecondaryContent(url.pathname); + addSecondaryContent(secondaryContent); + }, + }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/index.md b/files/en-us/web/api/navigation/index.md new file mode 100644 index 000000000000000..4d33e5d17f0c863 --- /dev/null +++ b/files/en-us/web/api/navigation/index.md @@ -0,0 +1,141 @@ +--- +title: Navigation +slug: Web/API/Navigation +page-type: web-api-interface +tags: + - API + - History + - Interface + - Landing + - Navigate + - Navigation + - Navigation API + - Scroll + - Traversal +browser-compat: api.Navigation +--- + +{{DefaultAPISidebar("Navigation API")}} + +The **`Navigation`** interface of the {{domxref("Navigation API")}} allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, introspecting navigation history entries, and managing navigations as they happen. + +It is accessed via the {{domxref("Window.navigation")}} property. + +The Navigation API only creates history entries created directly in the application document (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. + +{{InheritanceDiagram}} + +## Instance properties + +_Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ + +- {{domxref("Navigation.canGoBack", "canGoBack")}} {{ReadOnlyInline}} + - : Returns `true` if it is possible to navigate backwards in the navigation history + (i.e. the {{domxref("Navigation.currentEntry", "currentEntry")}} is not the first one in the history entry list), + and `false` if it is not. +- {{domxref("Navigation.canGoForward", "canGoForward")}} {{ReadOnlyInline}} + - : Returns `true` if it is possible to navigate forwards in the navigation history + (i.e. the {{domxref("Navigation.currentEntry", "currentEntry")}} is not the last one in the history entry list), + and `false` if it is not. +- {{domxref("Navigation.currentEntry", "currentEntry")}} {{ReadOnlyInline}} + - : Returns a {{domxref("NavigationHistoryEntry")}} object representing the location the user is currently + navigated to right now. +- {{domxref("Navigation.transition", "transition")}} {{ReadOnlyInline}} + - : Returns a {{domxref("NavigationTransition")}} object representing the status of an in-progress navigation, + which can be used to track it. Returns `null` in no navigation is currently in progress. + +### `Navigation` events + +- {{domxref("Navigation/currententrychange_event", "currententrychange")}} + - : Fired when the {{domxref("Navigation.currentEntry")}} has changed. +- {{domxref("Navigation/navigate_event", "navigate")}} + - : Fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, allowing you to intercept as required. +- {{domxref("Navigation/navigateerror_event", "navigateerror")}} + - : Fired when a navigation fails. +- {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} + - : Fired when a successful navigation has completed. + +## Instance methods + +_Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ + +- {{domxref("Navigation.back", "back()")}} + - : Navigates backwards by one entry in the navigation history. +- {{domxref("Navigation.entries", "entries()")}} + - : Returns an array of {{domxref("NavigationHistoryEntry")}} objects representing all existing history entries. +- {{domxref("Navigation.forward", "forward()")}} + - : Navigates forwards by one entry in the navigation history. +- {{domxref("Navigation.navigate", "navigate()")}} + - : Navigates to a specific URL, updating any provided `state` in the history entries list. +- {{domxref("Navigation.reload", "reload()")}} + - : Reloads the current URL, updating any provided `state` in the history entries list. +- {{domxref("Navigation.traverseTo", "traverseTo()")}} + - : Navigates to a specific {{domxref("NavigationHistoryEntry")}} by {{domxref("NavigationHistoryEntry.key", "key")}}, + passing any provided `info` to the corresponding {{domxref("NavigateEvent")}}. +- {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}} + - : Updates the `state` of the {{domxref("Navigation.currentEntry","currentEntry")}}, + in cases where the state change will be independent from a navigation or reload. + +## Examples + +### Moving forwards and backwards in the history + +```js +if(navigation.canGoBack) { + navigation.back(); +} else { + displayBanner('You are on the first page'); +} + + ... + +if(navigation.canGoForward) { + navigation.forward(); +} else { + displayBanner('You are on the last page'); +} +``` + +### Traversing to a specific history entry + +```js +// On JS startup, get the key of the first loaded page +// so the user can always go back there. +const {key} = navigation.currentEntry; +backToHomeButton.onclick = () => navigation.traverseTo(key); + +// Navigate away, but the button will always work. +await navigation.navigate('/another_url').finished; +``` + +### Navigating and updating state + +```js +navigation.navigate(url, {state: newState}); +``` + +Or + +```js +navigation.reload({state: newState}); +``` + +Or if the state is independent from a navigation or reload: + +```js +navigation.updateCurrentEntry({state: newState}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 1a021106f17ead0..0986b00bd136878 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -30,7 +30,7 @@ The API is accessed via the {{domxref("Window.navigation")}} property, which ret ### Handling navigations -`navigation` has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place. The `navigate` event has an event object of type {{domxref("NavigateEvent")}}, which contains detailed information including the navigation's destination URL, type, whether it contains `POST` form data or a download request, and more. +`navigation` has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the {{domxref("History API")}}, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event has an event object of type {{domxref("NavigateEvent")}}, which contains detailed information including the navigation's destination URL, type, whether it contains `POST` form data or a download request, and more. It also contains two methods: @@ -45,11 +45,15 @@ Once a navigation is initiated, and your `intercept()` handler is called, a {{do When the `intercept()` handler function's promise fulfills, the `Navigate` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases if it is needed. -### Programmatically traversing the navigation history +> **Note:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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. + +### Programmatically updating and traversing the navigation history As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct {{domxref("NavigationHistoryEntry")}} object instance. These contain several useful properties such as the entry's key, URL, and state information. You can return the entry that the user is currently navigated to right now using {{domxref("Navigation.currentEntry","currentEntry")}}, and an array of all existing history entries using {{domxref("Navigation.entries", "entries()")}}. Each `NavigationHistoryEntry` object has a {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} event, which fires when the entry is no longer part of the browser history (e.g. navigate back three times, then navigate forwards to somewhere else. Those three history entries will be disposed). -The `Navigation` object contains all the methods you'll need to traverse through the navigation history: +> **Note:** The Navigation API only creates history entries created directly in the application document (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. + +The `Navigation` object contains all the methods you'll need to update and traverse through the navigation history: - {{domxref("Navigation.navigate", "navigate()")}} navigates to a new URL, creating a new navigation history entry. - {{domxref("Navigation.reload", "reload()")}} reloads the current navigation history entry. @@ -65,7 +69,7 @@ Each one of the above methods returns an object containing two promises — `{ c ### State -The Navigation API allows you to store state on each history entry. This is developer-defined information — it can be whatever you like. For example, you might want to store a `visitCount` property that records the number of times a view has been visited, or an object containing multiple properties. +The Navigation API allows you to store state on each history entry. This is developer-defined information — it can be whatever you like. For example, you might want to store a `visitCount` property that records the number of times a view has been visited, or an object containing multiple properties related to UI state, so that state can be restored when a user returns to that view. To get a {{domxref("NavigationHistoryEntry")}}'s state, you call its {{domxref("NavigationHistoryEntry.getState", "getState()")}} method. It is initially `undefined`, but when state information is set on the entry, it will return the previously-set state information. @@ -88,9 +92,9 @@ There are a few perceived limitations with the Navigation API, which may or may - {{domxref("NavigationTransition")}} - : Represents an ongoing navigation. - {{domxref("NavigationCurrentEntryChangeEvent")}} - - : Event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the currently navigated to history entry changes. Provides access to the navigation type, and the previous history entry that was navigated from. + - : Event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the {{domxref("Navigation.currentEntry")}} has changed. It provides access to the navigation type, and the previous history entry that was navigated from. - {{domxref("NavigateEvent")}} - - : Event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated. Provides access to information about that navigation, and most notably the {{domxref("NavigateEvent.intercept", "intercept()")}}, which allows you to control what happens when the navigation is initiated. + - : Event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated. It provides access to information about that navigation, and most notably the {{domxref("NavigateEvent.intercept", "intercept()")}}, which allows you to control what happens when the navigation is initiated. ## Extensions to the `Window` interface diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/index.md new file mode 100644 index 000000000000000..2faaf8834a0de74 --- /dev/null +++ b/files/en-us/web/api/navigationcurrententrychangeevent/index.md @@ -0,0 +1,73 @@ +--- +title: NavigationCurrentEntryChangeEvent +slug: Web/API/NavigationCurrentEntryChangeEvent +page-type: web-api-interface +tags: + - API + - History + - Interface + - Landing + - Navigate + - NavigationCurrentEntryChangeEvent + - Navigation API + - Scroll + - Traversal +browser-compat: api.NavigationCurrentEntryChangeEvent +--- + +{{DefaultAPISidebar("Navigation API")}} + +The **`NavigationCurrentEntryChangeEvent`** interface of the {{domxref("Navigation API")}} is the event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the {{domxref("Navigation.currentEntry")}} has changed. + +This event will fire for same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}), replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`), or other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API")}}'s {{domxref("History.replaceState()")}}). + +This event fires after the navigation is committed, meaning that the visible URL has changed and the {{domxref("NavigationHistoryEntry")}} update has occurred. It is useful for migrating from usage of older API features like the {{domxref("Window/hashchange_event", "hashchange")}} or {{domxref("Window/popstate_event", "popstate")}} events. + +{{InheritanceDiagram}} + +## Constructor + +- {{domxref("NavigationCurrentEntryChangeEvent.NavigationCurrentEntryChangeEvent", "NavigationCurrentEntryChangeEvent()")}} + - : Creates a new `NavigationCurrentEntryChangeEvent` object instance. + +## Instance properties + +_Inherits properties from its parent, {{DOMxRef("Event")}}._ + +- {{domxref("NavigationCurrentEntryChangeEvent.from", "from")}} {{ReadOnlyInline}} + - : Returns the {{domxref("NavigationHistoryEntry")}} that has changed. +- {{domxref("NavigationCurrentEntryChangeEvent.navigationType", "navigationType")}} {{ReadOnlyInline}} + - : Returns the type of the navigation that resulted in the change. + +## Examples + +Navigation data reporting: + +```js +navigation.addEventListener("currententrychange", () => { + const data = navigation.currentEntry.getState() + submitAnalyticsData(data.analytics); +}); +``` + +Setting up a per-entry event: + +```js +navigation.addEventListener("currententrychange", () => { + navigation.currentEntry.addEventListener("dispose", genericDisposeHandler); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationdestination/index.md b/files/en-us/web/api/navigationdestination/index.md new file mode 100644 index 000000000000000..d42ac9868fcc36e --- /dev/null +++ b/files/en-us/web/api/navigationdestination/index.md @@ -0,0 +1,84 @@ +--- +title: NavigationDestination +slug: Web/API/NavigationDestination +page-type: web-api-interface +tags: + - API + - History + - Interface + - Landing + - Navigate + - NavigationDestination + - Navigation API + - Scroll + - Traversal +browser-compat: api.NavigationDestination +--- + +{{DefaultAPISidebar("Navigation API")}} + +The **`NavigationDestination`** interface of the {{domxref("Navigation API")}} represents the destination being navigated to in the current navigation. + +It is accessed via the {{domxref("NavigateEvent.destination")}} property. + +{{InheritanceDiagram}} + +## Instance properties + +- {{domxref("NavigationDestination.id", "id")}} {{ReadOnlyInline}} + - : Returns the {{domxref("NavigationHistoryEntry.id", "id")}} value of the destination {{domxref("NavigationHistoryEntry")}} if the {{domxref("NavigateEvent.navigationType")}} is `traverse`, or `null` otherwise. +- {{domxref("NavigationDestination.index", "index")}} {{ReadOnlyInline}} + - : Returns the {{domxref("NavigationHistoryEntry.index", "index")}} value of the destination {{domxref("NavigationHistoryEntry")}} if the {{domxref("NavigateEvent.navigationType")}} is `traverse`, or `-1` otherwise. +- {{domxref("NavigationDestination.key", "key")}} {{ReadOnlyInline}} + - : Returns the {{domxref("NavigationHistoryEntry.key", "key")}} value of the destination {{domxref("NavigationHistoryEntry")}} if the {{domxref("NavigateEvent.navigationType")}} is `traverse`, or `null` otherwise. +- {{domxref("NavigationDestination.sameDocument", "sameDocument")}} {{ReadOnlyInline}} + - : Returns `true` if the navigation is to the same `document` as the current {{domxref("Window.document")}} value, or `false` otherwise. +- {{domxref("NavigationDestination.url", "url")}} {{ReadOnlyInline}} + - : Returns the URL being navigated to. + +## Instance methods + +- {{domxref("NavigationDestination.getState", "getState()")}} + - : Returns the available `state` associated with the destination {{domxref("NavigationHistoryEntry")}}, or navigation operation (e.g. {{domxref("Navigation.navigate()", "navigate()")}}) as appropriate. + +## Examples + +```js +navigation.addEventListener('navigate', navigateEvent => { + // Exit early if this navigation shouldn't be intercepted, + // e.g. if the navigation is cross-origin, or a download request + if (shouldNotIntercept(navigateEvent)) return; + + // Returns a URL() object constructed from the + // NavigationDestination.url value + const url = new URL(navigateEvent.destination.url); + + if (url.pathname.startsWith('/articles/')) { + navigateEvent.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); + }, + }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationhistoryentry/index.md b/files/en-us/web/api/navigationhistoryentry/index.md new file mode 100644 index 000000000000000..435263946687fca --- /dev/null +++ b/files/en-us/web/api/navigationhistoryentry/index.md @@ -0,0 +1,79 @@ +--- +title: NavigationHistoryEntry +slug: Web/API/NavigationHistoryEntry +page-type: web-api-interface +tags: + - API + - History + - Interface + - Landing + - Navigate + - NavigationHistoryEntry + - Navigation API + - Scroll + - Traversal +browser-compat: api.NavigationHistoryEntry +--- + +{{DefaultAPISidebar("Navigation API")}} + +The **`NavigationHistoryEntry`** interface of the {{domxref("Navigation API")}} represents a single navigation history entry. + +These objects are commonly accessed via the {{domxref("Navigation.currentEntry")}} property and {{domxref("Navigation.entries()")}} method. + +The Navigation API only creates history entries created directly in the application document (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. + +{{InheritanceDiagram}} + +## Instance properties + +_Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ + +- {{domxref("NavigationHistoryEntry.id", "id")}} {{ReadOnlyInline}} + - : Returns a unique, UA-generated value that always represents the history entry, useful to correlate a history entry with an external resource such as a storage cache. +- {{domxref("NavigationHistoryEntry.index", "index")}} {{ReadOnlyInline}} + - : Returns the index of the history entry in the history entries list (i.e. returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list. +- {{domxref("NavigationHistoryEntry.key", "key")}} {{ReadOnlyInline}} + - : Returns a unique, UA-generated value that represents the history entry's slot in the history entries list, used to navigate to this place in the history via {{domxref("Navigation.traverseTo()")}}. It will be reused by other entries that replace the entry in the list (i.e. if the {{domxref("NavigateEvent.navigationType")}} is `replace`). +- {{domxref("NavigationHistoryEntry.sameDocument", "sameDocument")}} {{ReadOnlyInline}} + - : Returns `true` if this history entry is for the same `document` as the current {{domxref("Window.document")}} value, or `false` otherwise. +- {{domxref("NavigationHistoryEntry.url", "url")}} {{ReadOnlyInline}} + - : Returns the URL of this history entry. + +## `NavigationHistoryEntry` events + +- {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} + - : Fires when the entry is no longer part of the history entry list. + +## Instance methods + +_Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ + +- {{domxref("NavigationHistoryEntry.getState", "getState()")}} + - : Returns the available `state` associated with this history entry. + +## Examples + +```js +// On JS startup, get the key of the first loaded page +// so the user can always go back there. +const {key} = navigation.currentEntry; +backToHomeButton.onclick = () => navigation.traverseTo(key); + +// Navigate away, but the button will always work. +await navigation.navigate('/another_url').finished; +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationtransition/index.md b/files/en-us/web/api/navigationtransition/index.md new file mode 100644 index 000000000000000..7c96bb5db69b62d --- /dev/null +++ b/files/en-us/web/api/navigationtransition/index.md @@ -0,0 +1,55 @@ +--- +title: NavigationTransition +slug: Web/API/NavigationTransition +page-type: web-api-interface +tags: + - API + - History + - Interface + - Landing + - Navigate + - NavigationTransition + - Navigation API + - Scroll + - Traversal +browser-compat: api.NavigationTransition +--- + +{{DefaultAPISidebar("Navigation API")}} + +The **`NavigationTransition`** interface of the {{domxref("Navigation API")}} represents an ongoing navigation, that is, a navigation that hasn't yet reached the {{domxref("Navigation/navigatesuccess_event", "success")}} or {{domxref("Navigation/navigateerror_event", "error")}} stage. + +It is accessed via the {{domxref("Navigation.transition")}} property. + +{{InheritanceDiagram}} + +## Instance properties + +- {{domxref("NavigationTransition.navigationType", "navigationType")}} {{ReadOnlyInline}} + - : Returns the type of the ongoing navigation. +- {{domxref("NavigationTransition.from", "from")}} {{ReadOnlyInline}} + - : Returns the {{domxref("NavigationHistoryEntry")}} that the transition is coming from. +- {{domxref("NavigationTransition.finished", "finished")}} {{ReadOnlyInline}} + - : Returns a {{jsxref("Promise")}} that fulfills at the same time the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, or rejects at the same time the {{domxref("Navigation/navigateerror_event", "navigateerror")}} event fires. + +## Examples + +```js +await navigation.transition.finished; +// Navigation has completed successfully +// Cleanup any ongoing monitoring +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/window/index.md b/files/en-us/web/api/window/index.md index 675572a8b7e1421..1cdf86fc03ef167 100644 --- a/files/en-us/web/api/window/index.md +++ b/files/en-us/web/api/window/index.md @@ -41,7 +41,7 @@ See also the [DOM Interfaces](/en-US/docs/Web/API/Document_Object_Model). - {{domxref("HTMLOptionElement.Option")}} - : Used for creating an {{domxref("HTMLOptionElement")}}. - {{domxref("StaticRange")}} {{Experimental_Inline}} {{ReadOnlyInline}} - - : Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object. + - : Returns a {{domxref("StaticRange.StaticRange","StaticRange()")}} constructor which creates a {{domxref("StaticRange")}} object. - {{domxref("Worker")}} - : Used for creating a [Web worker](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers). - {{domxref("XMLSerializer")}} @@ -103,6 +103,8 @@ Note that properties which are objects (e.g., for overriding the prototype of bu - : Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See `mozScreenPixelsPerCSSPixel` for a conversion factor to adapt to screen pixels if needed. - {{domxref("Window.name")}} - : Gets/sets the name of the window. +- {{domxref("Window.navigation")}} {{ReadOnlyInline}} + - : Returns the current `window`'s associated {{domxref("Navigation")}} object. The entry point for the {{domxref("Navigation API")}}. - {{domxref("Window.navigator")}} {{ReadOnlyInline}} - : Returns a reference to the navigator object. - {{domxref("Window.opener")}} diff --git a/files/en-us/web/api/window/navigation/index.md b/files/en-us/web/api/window/navigation/index.md new file mode 100644 index 000000000000000..48dd4660f1e76a4 --- /dev/null +++ b/files/en-us/web/api/window/navigation/index.md @@ -0,0 +1,44 @@ +--- +title: Window.navigation +slug: Web/API/Window/navigation +page-type: web-api-instance-property +tags: + - API + - Navigate + - Navigation + - Navigation API + - Property + - Reference + - Window +browser-compat: api.Window.navigation +--- + +{{ ApiRef() }} + +The `navigation` read-only property of the {{domxref("Window")}} interface returns the current `window`'s associated {{domxref("Navigation")}} object. + +The entry point for the {{domxref("Navigation API")}}. + +## Value + +A {{domxref("Navigation")}} object instance. + +## Examples + +```js +let currentNavEntries = window.navigation.entries(); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) From 9a2b3ba57d4991fca70430ebb2568d4e6c9885a5 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Fri, 4 Nov 2022 07:46:54 +0000 Subject: [PATCH 07/50] add all member pages for Navigate --- files/en-us/web/api/navigateevent/index.md | 4 +- files/en-us/web/api/navigation/back/index.md | 86 +++++++++++++ .../web/api/navigation/cangoback/index.md | 68 +++++++++++ .../web/api/navigation/cangoforward/index.md | 66 ++++++++++ .../web/api/navigation/currententry/index.md | 55 +++++++++ .../currententrychange_event/index.md | 65 ++++++++++ .../en-us/web/api/navigation/entries/index.md | 80 ++++++++++++ .../en-us/web/api/navigation/forward/index.md | 86 +++++++++++++ files/en-us/web/api/navigation/index.md | 17 ++- .../web/api/navigation/navigate/index.md | 114 ++++++++++++++++++ .../api/navigation/navigate_event/index.md | 100 +++++++++++++++ .../navigation/navigateerror_event/index.md | 72 +++++++++++ .../navigation/navigatesuccess_event/index.md | 72 +++++++++++ .../en-us/web/api/navigation/reload/index.md | 79 ++++++++++++ .../web/api/navigation/transition/index.md | 53 ++++++++ .../web/api/navigation/traverseto/index.md | 80 ++++++++++++ .../navigation/updatecurrententry/index.md | 71 +++++++++++ files/en-us/web/api/navigation_api/index.md | 6 +- .../index.md | 4 +- .../web/api/navigationdestination/index.md | 4 +- .../web/api/navigationhistoryentry/index.md | 4 +- .../web/api/navigationtransition/index.md | 4 +- files/en-us/web/api/window/index.md | 2 +- .../en-us/web/api/window/navigation/index.md | 3 +- 24 files changed, 1180 insertions(+), 15 deletions(-) create mode 100644 files/en-us/web/api/navigation/back/index.md create mode 100644 files/en-us/web/api/navigation/cangoback/index.md create mode 100644 files/en-us/web/api/navigation/cangoforward/index.md create mode 100644 files/en-us/web/api/navigation/currententry/index.md create mode 100644 files/en-us/web/api/navigation/currententrychange_event/index.md create mode 100644 files/en-us/web/api/navigation/entries/index.md create mode 100644 files/en-us/web/api/navigation/forward/index.md create mode 100644 files/en-us/web/api/navigation/navigate/index.md create mode 100644 files/en-us/web/api/navigation/navigate_event/index.md create mode 100644 files/en-us/web/api/navigation/navigateerror_event/index.md create mode 100644 files/en-us/web/api/navigation/navigatesuccess_event/index.md create mode 100644 files/en-us/web/api/navigation/reload/index.md create mode 100644 files/en-us/web/api/navigation/transition/index.md create mode 100644 files/en-us/web/api/navigation/traverseto/index.md create mode 100644 files/en-us/web/api/navigation/updatecurrententry/index.md diff --git a/files/en-us/web/api/navigateevent/index.md b/files/en-us/web/api/navigateevent/index.md index ab4ae12a3dabc54..301b1d48c4e48b9 100644 --- a/files/en-us/web/api/navigateevent/index.md +++ b/files/en-us/web/api/navigateevent/index.md @@ -4,18 +4,20 @@ slug: Web/API/NavigateEvent page-type: web-api-interface tags: - API + - Experimental - History - Interface - Landing - Navigate - NavigateEvent - Navigation API + - Reference - Scroll - Traversal browser-compat: api.NavigateEvent --- -{{DefaultAPISidebar("Navigation API")}} +{{APIRef("Navigation API")}}{{seecompattable}} The **`NavigateEvent`** interface of the {{domxref("Navigation API")}} is the event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated (this includes usage of History API features like {{domxref("History.go()")}}). `NavigateEvent` provides access to information about that navigation, and allows developers to intercept and control the navigation handling. diff --git a/files/en-us/web/api/navigation/back/index.md b/files/en-us/web/api/navigation/back/index.md new file mode 100644 index 000000000000000..f061a864c60c1cf --- /dev/null +++ b/files/en-us/web/api/navigation/back/index.md @@ -0,0 +1,86 @@ +--- +title: Navigation.back() +slug: Web/API/Navigation/back +page-type: web-api-instance-method +tags: + - API + - Experimental + - back + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.Navigation.back +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`back()`** method of the +{{domxref("Navigation")}} interface navigates backwards by one entry in the navigation history. + +## Syntax + +```js-nolint +back(options) +``` + +### Parameters + +- `options` {{optional_inline}} + - : An options object containing the following properties: + - `info` + - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("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 containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: + +- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. +- either one of the above promises rejects, meaning that the navigation has failed for some reason. + +### Exceptions + +- `InvalidStateError` {{domxref("DOMException")}} + - : Thrown if the {{domxref("Navigation.currentEntry")}}'s {{domxref("NavigationHistoryEntry.index")}} value is -1 or 0, i.e. either the current {{domxref("Document")}} is not yet active, or the current history entry is the first one in the history, meaning that backwards navigation is not possible. + +## Examples + +```js +if(navigation.canGoBack) { + await navigation.back( { info: "swipe-right" } ).finished; + // Handle any required clean-up after + // navigation has finished +} else { + displayBanner('You are on the first page'); +} + + ... + +if(navigation.canGoForward) { + await navigation.forward( { info: "swipe-right" } ).finished; + // Handle any required clean-up after + // navigation has finished +} else { + displayBanner('You are on the last page'); +} +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/cangoback/index.md b/files/en-us/web/api/navigation/cangoback/index.md new file mode 100644 index 000000000000000..187dd1c528f6dd8 --- /dev/null +++ b/files/en-us/web/api/navigation/cangoback/index.md @@ -0,0 +1,68 @@ +--- +title: Navigation.canGoBack +slug: Web/API/Navigation/canGoBack +page-type: web-api-instance-property +tags: + - API + - canGoBack + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.Navigation.canGoBack +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`canGoBack`** read-only property of the +{{domxref("Navigation")}} interface returns `true` +if it is possible to navigate backwards in the navigation history +(i.e. the {{domxref("Navigation.currentEntry", "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` if not. + +## Examples + +```js +if(navigation.canGoBack) { + await navigation.back( { info: "swipe-right" } ).finished; + // Handle any required clean-up after + // navigation has finished +} else { + displayBanner('You are on the first page'); +} + + ... + +if(navigation.canGoForward) { + await navigation.forward( { info: "swipe-right" } ).finished; + // Handle any required clean-up after + // navigation has finished +} else { + displayBanner('You are on the last page'); +} +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/cangoforward/index.md b/files/en-us/web/api/navigation/cangoforward/index.md new file mode 100644 index 000000000000000..1cf05294150cc05 --- /dev/null +++ b/files/en-us/web/api/navigation/cangoforward/index.md @@ -0,0 +1,66 @@ +--- +title: Navigation.canGoForward +slug: Web/API/Navigation/canGoForward +page-type: web-api-instance-property +tags: + - API + - canGoForward + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.Navigation.canGoForward +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`canGoForward`** read-only property of the +{{domxref("Navigation")}} interface returns `true` if it is possible to navigate forwards in the navigation history +(i.e. the {{domxref("Navigation.currentEntry", "currentEntry")}} is not the last one in the history entry list), +and `false` if it is not. + +## Value + +A boolean value—`true` if it is possible to navigate forwards in the navigation history, `false` if not. + +## Examples + +```js +if(navigation.canGoBack) { + await navigation.back().finished; + // Handle any required clean-up after + // navigation has finished +} else { + displayBanner('You are on the first page'); +} + + ... + +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 + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/currententry/index.md b/files/en-us/web/api/navigation/currententry/index.md new file mode 100644 index 000000000000000..021bdf7d0e97290 --- /dev/null +++ b/files/en-us/web/api/navigation/currententry/index.md @@ -0,0 +1,55 @@ +--- +title: Navigation.currentEntry +slug: Web/API/Navigation/currentEntry +page-type: web-api-instance-property +tags: + - API + - currentEntry + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.Navigation.currentEntry +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`currentEntry`** read-only property of the +{{domxref("Navigation")}} interface returns a {{domxref("NavigationHistoryEntry")}} object representing the location the user is currently + navigated to right now. + +## Value + +A {{domxref("NavigationHistoryEntry")}} object. + +## Examples + +```js +// On JS startup, get the key of the first loaded page +// so the user can always go back there. +const {key} = navigation.currentEntry; +backToHomeButton.onclick = () => navigation.traverseTo(key); + +// Navigate away, but the button will always work. +await navigation.navigate('/another_url').finished; +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/currententrychange_event/index.md b/files/en-us/web/api/navigation/currententrychange_event/index.md new file mode 100644 index 000000000000000..eedd235cc330283 --- /dev/null +++ b/files/en-us/web/api/navigation/currententrychange_event/index.md @@ -0,0 +1,65 @@ +--- +title: "Navigation: currententrychange event" +slug: Web/API/Navigation/currententrychange_event +page-type: web-api-event +tags: + - API + - currententrychange + - Event + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Reference + - reload + - Scroll + - Traversal + - updateCurrentEntry +browser-compat: api.Navigation.currententrychange_event +--- + +{{APIRef("Navigation API")}}{{SeeCompatTable}} + +The **`currententrychange`** event of the {{domxref("Navigation")}} interface is fired when the {{domxref("Navigation.currentEntry")}} has changed. + +This event will fire for same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}), replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`), or other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API")}}'s {{domxref("History.replaceState()")}}). + +This event fires after the navigation is committed, meaning that the visible URL has changed and the {{domxref("NavigationHistoryEntry")}} update has occurred. It is useful for migrating from usage of older API features like the {{domxref("Window/hashchange_event", "hashchange")}} or {{domxref("Window/popstate_event", "popstate")}} events. + +## Syntax + +Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. + +```js +addEventListener("currententrychange", (event) => {}); + +oncurrententrychange = (event) => {}; +``` + +> **Note:** The event object is of type {{domxref("NavigationCurrentEntryChangeEvent")}}. + +## Examples + +`changeentrychange` could be used by analytics packages that don't care about the navigation finishing, just committing. It could also be used to set up relevant per-entry events, for example: + +```js +navigation.addEventListener("currententrychange", () => { + navigation.currentEntry.addEventListener("dispose", disposeHandler); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/entries/index.md b/files/en-us/web/api/navigation/entries/index.md new file mode 100644 index 000000000000000..3f66c55f3b854e8 --- /dev/null +++ b/files/en-us/web/api/navigation/entries/index.md @@ -0,0 +1,80 @@ +--- +title: Navigation.entries() +slug: Web/API/Navigation/entries +page-type: web-api-instance-method +tags: + - API + - entries + - Experimental + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.Navigation.entries +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`entries()`** method of the +{{domxref("Navigation")}} interface returns an array of {{domxref("NavigationHistoryEntry")}} objects representing all existing history entries. + +## Syntax + +```js-nolint +entries() +``` + +### Parameters + +None. + +### Return value + +An array of {{domxref("NavigationHistoryEntry")}} objects. + +### Exceptions + +None. + +## Examples + +### Return the number of entries in the history + +```js +let numOfEntries = Navigation.entries().length - 1; +``` + +### A smart back button + +A page-supplied "back" button can take you back, even after reload, by inspecting the previous history entries: + +```js +backButtonEl.addEventListener("click", () => { + if (navigation.entries()[navigation.currentEntry.index - 1]?.url === "/product-listing") { + navigation.back(); + } else { + // If the user arrived here in some other way + // e.g. by typing the URL directly: + navigation.navigate("/product-listing", { history: "replace" }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/forward/index.md b/files/en-us/web/api/navigation/forward/index.md new file mode 100644 index 000000000000000..454cfe1420cc97c --- /dev/null +++ b/files/en-us/web/api/navigation/forward/index.md @@ -0,0 +1,86 @@ +--- +title: Navigation.forward() +slug: Web/API/Navigation/forward +page-type: web-api-instance-method +tags: + - API + - Experimental + - forward + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.Navigation.forward +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`forward()`** method of the +{{domxref("Navigation")}} interface navigates forwards by one entry in the navigation history. + +## Syntax + +```js-nolint +forward(options) +``` + +### Parameters + +- `options` {{optional_inline}} + - : An options object containing the following properties: + - `info` + - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("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 containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: + +- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. +- either one of the above promises rejects, meaning that the navigation has failed for some reason. + +### Exceptions + +- `InvalidStateError` {{domxref("DOMException")}} + - : Thrown if the {{domxref("Navigation.currentEntry")}}'s {{domxref("NavigationHistoryEntry.index")}} value is -1 or {{domxref("Navigation.entries", "Navigation.entries().length - 1")}}, i.e. either the current {{domxref("Document")}} is not yet active, or the current history entry is the last one in the history, meaning that forwards navigation is not possible. + +## Examples + +```js +if(navigation.canGoBack) { + await navigation.back( { info: "swipe-right" } ).finished; + // Handle any required clean-up after + // navigation has finished +} else { + displayBanner('You are on the first page'); +} + + ... + +if(navigation.canGoForward) { + await navigation.forward( { info: "swipe-right" } ).finished; + // Handle any required clean-up after + // navigation has finished +} else { + displayBanner('You are on the last page'); +} +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/index.md b/files/en-us/web/api/navigation/index.md index 4d33e5d17f0c863..d205f3fab797db6 100644 --- a/files/en-us/web/api/navigation/index.md +++ b/files/en-us/web/api/navigation/index.md @@ -4,18 +4,20 @@ slug: Web/API/Navigation page-type: web-api-interface tags: - API + - Experimental - History - Interface - Landing - Navigate - Navigation - Navigation API + - Reference - Scroll - Traversal browser-compat: api.Navigation --- -{{DefaultAPISidebar("Navigation API")}} +{{APIRef("Navigation API")}}{{seecompattable}} The **`Navigation`** interface of the {{domxref("Navigation API")}} allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, introspecting navigation history entries, and managing navigations as they happen. @@ -70,10 +72,9 @@ _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("Navigation.reload", "reload()")}} - : Reloads the current URL, updating any provided `state` in the history entries list. - {{domxref("Navigation.traverseTo", "traverseTo()")}} - - : Navigates to a specific {{domxref("NavigationHistoryEntry")}} by {{domxref("NavigationHistoryEntry.key", "key")}}, - passing any provided `info` to the corresponding {{domxref("NavigateEvent")}}. + - : Navigates to a specific {{domxref("NavigationHistoryEntry")}} by {{domxref("NavigationHistoryEntry.key", "key")}}. - {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}} - - : Updates the `state` of the {{domxref("Navigation.currentEntry","currentEntry")}}, + - : Updates the `state` of the {{domxref("Navigation.currentEntry","currentEntry")}}; used in cases where the state change will be independent from a navigation or reload. ## Examples @@ -82,7 +83,9 @@ _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ ```js if(navigation.canGoBack) { - navigation.back(); + await navigation.back().finished; + // Handle any required clean-up after + // navigation has finished } else { displayBanner('You are on the first page'); } @@ -90,7 +93,9 @@ if(navigation.canGoBack) { ... if(navigation.canGoForward) { - navigation.forward(); + await navigation.forward().finished; + // Handle any required clean-up after + // navigation has finished } else { displayBanner('You are on the last page'); } diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md new file mode 100644 index 000000000000000..17d705d7a2a9074 --- /dev/null +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -0,0 +1,114 @@ +--- +title: Navigation.navigate() +slug: Web/API/Navigation/navigate +page-type: web-api-instance-method +tags: + - API + - Experimental + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.Navigation.navigate +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`navigate()`** method of the +{{domxref("Navigation")}} interface navigates to a specific URL, updating any provided `state` in the history entries list. + +## Syntax + +```js-nolint +navigate(url, options) +``` + +### Parameters + +- `url` + - : The destination URL to navigate to. +- `options` {{optional_inline}} + - : An options object containing the following properties: + - `state` + - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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. + - `info` + - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("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`. + - `history` + - : An enumerated value that sets the history behavior of this navigation. The available values are: + - `auto`: The default value; will usually perform a `push` navigation but will perform a `replace` navigation under special circumstances (see the `NotSupportedError` description below). + - `push`: Will push a new {{domxref("NavigationHistoryEntry")}} onto the entries list, or fail under special circumstances (see the `NotSupportedError` description below). + - `replace`: Will replace the current {{domxref("NavigationHistoryEntry")}}. + +### Return value + +An object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: + +- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. +- either one of the above promises rejects, meaning that the navigation has failed for some reason. + +### Exceptions + +- `SyntaxError` {{domxref("DOMException")}} + - : Thrown if the `url` parameter is not a valid URL. +- `NotSupportedError` {{domxref("DOMException")}} + - : Thrown if the `history` option is set to `push`, and any of the following special circumstances are true: + - The browser is currently showing the initial `about:blank` document. + - The current {{domxref("Document")}} is not yet loaded. + - The `url` parameter is set to the current URL. + - The `url`'s scheme is `javascript`. + +## Examples + +### Set up home button + +```js +// On JS startup, get the key of the first loaded page +// so the user can always go back there. +const {key} = navigation.currentEntry; +backToHomeButton.onclick = () => navigation.traverseTo(key); + +// Navigate away, but the button will always work. +await navigation.navigate('/another_url').finished; +``` + +### A smart back button + +A page-supplied "back" button can take you back, even after reload, by inspecting the previous history entries: + +```js +backButtonEl.addEventListener("click", () => { + if (navigation.entries()[navigation.currentEntry.index - 1]?.url === "/product-listing") { + navigation.back(); + } else { + // If the user arrived here in some other way + // e.g. by typing the URL directly: + navigation.navigate("/product-listing", { history: "replace" }); + } +}); +``` + +### Usage of info and state + +```js +await navigation.navigate(url, { info: { animation: "swipe-right" }, state: { infoPaneOpen: true } } ); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/navigate_event/index.md b/files/en-us/web/api/navigation/navigate_event/index.md new file mode 100644 index 000000000000000..407ad04fd762523 --- /dev/null +++ b/files/en-us/web/api/navigation/navigate_event/index.md @@ -0,0 +1,100 @@ +--- +title: "Navigation: navigate event" +slug: Web/API/Navigation/navigate_event +page-type: web-api-event +tags: + - API + - Event + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Reference + - reload + - Scroll + - Traversal + - updateCurrentEntry +browser-compat: api.Navigation.navigate_event +--- + +{{APIRef("Navigation API")}}{{SeeCompatTable}} + +The **`navigate`** event of the {{domxref("Navigation")}} interface is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, allowing you to intercept as required. + +## Syntax + +Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. + +```js +addEventListener("navigate", (event) => {}); + +onnavigate = (event) => {}; +``` + +> **Note:** The event object is of type {{domxref("NavigateEvent")}}. + +## Examples + +### Handling a navigation using `intercept()` + +```js +navigation.addEventListener('navigate', navigateEvent => { + // Exit early if this navigation shouldn't be intercepted, + // e.g. if the navigation is cross-origin, or a download request + if (shouldNotIntercept(navigateEvent)) return; + + const url = new URL(navigateEvent.destination.url); + + if (url.pathname.startsWith('/articles/')) { + navigateEvent.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); + }, + }); + } +}); +``` + +### Handling scrolling using `scroll()` + +```js +navigation.addEventListener('navigate', navigateEvent => { + if (shouldNotIntercept(navigateEvent)) return; + const url = new URL(navigateEvent.destination.url); + + if (url.pathname.startsWith('/articles/')) { + navigateEvent.intercept({ + async handler() { + const articleContent = await getArticleContent(url.pathname); + renderArticlePage(articleContent); + navigateEvent.scroll(); + + const secondaryContent = await getSecondaryContent(url.pathname); + addSecondaryContent(secondaryContent); + }, + }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/navigateerror_event/index.md b/files/en-us/web/api/navigation/navigateerror_event/index.md new file mode 100644 index 000000000000000..b95f33df302a10e --- /dev/null +++ b/files/en-us/web/api/navigation/navigateerror_event/index.md @@ -0,0 +1,72 @@ +--- +title: "Navigation: navigateerror event" +slug: Web/API/Navigation/navigateerror_event +page-type: web-api-event +tags: + - API + - Event + - Experimental + - History + - Navigate + - navigateerror + - Navigation + - Navigation API + - Property + - Reference + - reload + - Scroll + - Traversal + - updateCurrentEntry +browser-compat: api.Navigation.navigateerror_event +--- + +{{APIRef("Navigation API")}}{{SeeCompatTable}} + +The **`navigateerror`** event of the {{domxref("Navigation")}} interface is fired when a navigation fails. + +For example, if the network is down, any {{domxref("fetch()")}} method invoked to handle a navigation will fail, and the error will be routed to `navigateerror`. + +## Syntax + +Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. + +```js +addEventListener("navigateerror", (event) => {}); + +onnavigateerror = (event) => {}; +``` + +> **Note:** The event object is of type {{domxref("ErrorEvent")}}. + +## Examples + +You might deal with a successful navigation by hiding a previously displayed progress indicator, like this: + +```js +navigation.addEventListener('navigatesuccess', event => { + loadingIndicator.hidden = true; +}); +``` + +Or you might show an error message on failure: + +```js +navigation.addEventListener('navigateerror', event => { + loadingIndicator.hidden = true; // also hide indicator + showMessage(`Failed to load page: ${event.message}`); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/navigatesuccess_event/index.md b/files/en-us/web/api/navigation/navigatesuccess_event/index.md new file mode 100644 index 000000000000000..fd6d09ebe0a917d --- /dev/null +++ b/files/en-us/web/api/navigation/navigatesuccess_event/index.md @@ -0,0 +1,72 @@ +--- +title: "Navigation: navigatesuccess event" +slug: Web/API/Navigation/navigatesuccess_event +page-type: web-api-event +tags: + - API + - Event + - Experimental + - History + - Navigate + - navigatesuccess + - Navigation + - Navigation API + - Property + - Reference + - reload + - Scroll + - Traversal + - updateCurrentEntry +browser-compat: api.Navigation.navigatesuccess_event +--- + +{{APIRef("Navigation API")}}{{SeeCompatTable}} + +The **`navigatesuccess`** event of the {{domxref("Navigation")}} interface is fired when a successful navigation has completed. + +This means that all promises returned by your `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling. + +## Syntax + +Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. + +```js +addEventListener("navigatesuccess", (event) => {}); + +onnavigatesuccess = (event) => {}; +``` + +> **Note:** The event object is of type {{domxref("Event")}}. + +## Examples + +You might deal with a successful navigation by hiding a previously displayed progress indicator, like this: + +```js +navigation.addEventListener('navigatesuccess', event => { + loadingIndicator.hidden = true; +}); +``` + +Or you might show an error message on failure: + +```js +navigation.addEventListener('navigateerror', event => { + loadingIndicator.hidden = true; // also hide indicator + showMessage(`Failed to load page: ${event.message}`); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/reload/index.md b/files/en-us/web/api/navigation/reload/index.md new file mode 100644 index 000000000000000..b5465381b2750a9 --- /dev/null +++ b/files/en-us/web/api/navigation/reload/index.md @@ -0,0 +1,79 @@ +--- +title: Navigation.reload() +slug: Web/API/Navigation/reload +page-type: web-api-instance-method +tags: + - API + - Experimental + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - reload + - Scroll + - transition + - Traversal +browser-compat: api.Navigation.reload +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`reload()`** method of the +{{domxref("Navigation")}} interface reloads the current URL, updating any provided `state` in the history entries list. + +## Syntax + +```js-nolint +navigate(options) +``` + +### Parameters + +- `options` {{optional_inline}} + - : An options object containing the following properties: + - `state` + - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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. + - `info` + - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("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 containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: + +- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. +- either one of the above promises rejects, meaning that the navigation has failed for some reason. + +### Exceptions + +None. + +## Examples + +Usage of info and state + +```js +await navigation.reload({ info: { animation: "fade-in" }, state: { infoPaneOpen: true } } ); +``` + +Reload page and add a new state item: + +```js +await navigation.reload({ state: { ...navigation.currentEntry.getState(), newState: 3 } }); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/transition/index.md b/files/en-us/web/api/navigation/transition/index.md new file mode 100644 index 000000000000000..d88fb80cb0c6f74 --- /dev/null +++ b/files/en-us/web/api/navigation/transition/index.md @@ -0,0 +1,53 @@ +--- +title: Navigation.transition +slug: Web/API/Navigation/transition +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.Navigation.transition +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`transition`** read-only property of the +{{domxref("Navigation")}} interface returns a {{domxref("NavigationTransition")}} object representing the status of an in-progress navigation, + which can be used to track it. + +## Value + +A {{domxref("NavigationTransition")}} object, or `null` in no navigation is currently in progress. + +## Examples + +```js +if(navigation.transition) { + showLoadingSpinner(); + await navigation.transition.finished; + hideLoadingSpinner(); +} +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/traverseto/index.md b/files/en-us/web/api/navigation/traverseto/index.md new file mode 100644 index 000000000000000..5fcf7ecd1d7c70e --- /dev/null +++ b/files/en-us/web/api/navigation/traverseto/index.md @@ -0,0 +1,80 @@ +--- +title: Navigation.traverseTo() +slug: Web/API/Navigation/traverseTo +page-type: web-api-instance-method +tags: + - API + - Experimental + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal + - traverseTo +browser-compat: api.Navigation.traverseTo +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`traverseTo()`** method of the +{{domxref("Navigation")}} interface navigates to a specific {{domxref("NavigationHistoryEntry")}} by {{domxref("NavigationHistoryEntry.key", "key")}}. + +## Syntax + +```js-nolint +traverseTo(key, options) +``` + +### Parameters + +- `key` + - : The `key` of the {{domxref("NavigationHistoryEntry")}} to navigate to. +- `options` {{optional_inline}} + - : An options object containing the following properties: + - `info` + - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("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 containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: + +- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. +- either one of the above promises rejects, meaning that the navigation has failed for some reason. + +### Exceptions + +- `InvalidStateError` {{domxref("DOMException")}} + - : Thrown if the {{domxref("Navigation.currentEntry")}}'s {{domxref("NavigationHistoryEntry.index")}} value is -1, meaning the current {{domxref("Document")}} is not yet active, of if the navigation history list does not contain a {{domxref("NavigationHistoryEntry")}} with the specified key. + +## Examples + +### Set up home button + +```js +// On JS startup, get the key of the first loaded page +// so the user can always go back there. +const {key} = navigation.currentEntry; +backToHomeButton.onclick = () => navigation.traverseTo(key); + +// Navigate away, but the button will always work. +await navigation.navigate('/another_url').finished; +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/updatecurrententry/index.md b/files/en-us/web/api/navigation/updatecurrententry/index.md new file mode 100644 index 000000000000000..1cad31fe654a02c --- /dev/null +++ b/files/en-us/web/api/navigation/updatecurrententry/index.md @@ -0,0 +1,71 @@ +--- +title: Navigation.updateCurrentEntry() +slug: Web/API/Navigation/updateCurrentEntry +page-type: web-api-instance-method +tags: + - API + - Experimental + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - reload + - Scroll + - Traversal + - updateCurrentEntry +browser-compat: api.Navigation.updateCurrentEntry +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`updateCurrentEntry()`** method of the +{{domxref("Navigation")}} interface updates the `state` of the {{domxref("Navigation.currentEntry","currentEntry")}}; used + in cases where the state change will be independent from a navigation or reload. + +## Syntax + +```js-nolint +updateCurrentEntry(options) +``` + +### Parameters + +- `options` {{optional_inline}} + - : An options object containing the following properties: + - `state` + - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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. + +### Return value + +`undefined`. + +### Exceptions + +- `InvalidStateError` {{domxref("DOMException")}} + - : Thrown if the {{domxref("Navigation.currentEntry")}} is `null`, i.e. there is no current history entry. This could occur for exaple if the current page is `about:blank`. + +## Examples + +You could use something like the following to update the open/closed state of a {{htmlelement("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 + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 0986b00bd136878..c21be0016295552 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -4,12 +4,14 @@ slug: Web/API/Navigation_API page-type: web-api-overview tags: - API + - Experimental - History - Landing - Navigate - Navigation - Navigation API - Overview + - Reference - Scroll - Traversal browser-compat: @@ -63,9 +65,9 @@ The `Navigation` object contains all the methods you'll need to update and trave Each one of the above methods returns an object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: -- `committed` fulfills, meaning that the visible URL has changed and a new NavigationHistoryEntry has been created. +- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` fulfills, meaning that all promises returned by your `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, as mentioned earlier. -- either one of the above promises rejects, meaning that the navigation transition has failed for some reason. +- either one of the above promises rejects, meaning that the navigation has failed for some reason. ### State diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/index.md index 2faaf8834a0de74..3b28ad8fd6a3062 100644 --- a/files/en-us/web/api/navigationcurrententrychangeevent/index.md +++ b/files/en-us/web/api/navigationcurrententrychangeevent/index.md @@ -4,18 +4,20 @@ slug: Web/API/NavigationCurrentEntryChangeEvent page-type: web-api-interface tags: - API + - Experimental - History - Interface - Landing - Navigate - NavigationCurrentEntryChangeEvent - Navigation API + - Reference - Scroll - Traversal browser-compat: api.NavigationCurrentEntryChangeEvent --- -{{DefaultAPISidebar("Navigation API")}} +{{APIRef("Navigation API")}}{{seecompattable}} The **`NavigationCurrentEntryChangeEvent`** interface of the {{domxref("Navigation API")}} is the event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the {{domxref("Navigation.currentEntry")}} has changed. diff --git a/files/en-us/web/api/navigationdestination/index.md b/files/en-us/web/api/navigationdestination/index.md index d42ac9868fcc36e..4f2ea119c46e234 100644 --- a/files/en-us/web/api/navigationdestination/index.md +++ b/files/en-us/web/api/navigationdestination/index.md @@ -4,18 +4,20 @@ slug: Web/API/NavigationDestination page-type: web-api-interface tags: - API + - Experimental - History - Interface - Landing - Navigate - NavigationDestination - Navigation API + - Reference - Scroll - Traversal browser-compat: api.NavigationDestination --- -{{DefaultAPISidebar("Navigation API")}} +{{APIRef("Navigation API")}}{{seecompattable}} The **`NavigationDestination`** interface of the {{domxref("Navigation API")}} represents the destination being navigated to in the current navigation. diff --git a/files/en-us/web/api/navigationhistoryentry/index.md b/files/en-us/web/api/navigationhistoryentry/index.md index 435263946687fca..45152ebf44a888d 100644 --- a/files/en-us/web/api/navigationhistoryentry/index.md +++ b/files/en-us/web/api/navigationhistoryentry/index.md @@ -4,18 +4,20 @@ slug: Web/API/NavigationHistoryEntry page-type: web-api-interface tags: - API + - Experimental - History - Interface - Landing - Navigate - NavigationHistoryEntry - Navigation API + - Reference - Scroll - Traversal browser-compat: api.NavigationHistoryEntry --- -{{DefaultAPISidebar("Navigation API")}} +{{APIRef("Navigation API")}}{{seecompattable}} The **`NavigationHistoryEntry`** interface of the {{domxref("Navigation API")}} represents a single navigation history entry. diff --git a/files/en-us/web/api/navigationtransition/index.md b/files/en-us/web/api/navigationtransition/index.md index 7c96bb5db69b62d..216a37a6b4c31ef 100644 --- a/files/en-us/web/api/navigationtransition/index.md +++ b/files/en-us/web/api/navigationtransition/index.md @@ -4,18 +4,20 @@ slug: Web/API/NavigationTransition page-type: web-api-interface tags: - API + - Experimental - History - Interface - Landing - Navigate - NavigationTransition - Navigation API + - Reference - Scroll - Traversal browser-compat: api.NavigationTransition --- -{{DefaultAPISidebar("Navigation API")}} +{{APIRef("Navigation API")}}{{seecompattable}} The **`NavigationTransition`** interface of the {{domxref("Navigation API")}} represents an ongoing navigation, that is, a navigation that hasn't yet reached the {{domxref("Navigation/navigatesuccess_event", "success")}} or {{domxref("Navigation/navigateerror_event", "error")}} stage. diff --git a/files/en-us/web/api/window/index.md b/files/en-us/web/api/window/index.md index 1cdf86fc03ef167..f470a4cebdc6fbc 100644 --- a/files/en-us/web/api/window/index.md +++ b/files/en-us/web/api/window/index.md @@ -103,7 +103,7 @@ Note that properties which are objects (e.g., for overriding the prototype of bu - : Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See `mozScreenPixelsPerCSSPixel` for a conversion factor to adapt to screen pixels if needed. - {{domxref("Window.name")}} - : Gets/sets the name of the window. -- {{domxref("Window.navigation")}} {{ReadOnlyInline}} +- {{domxref("Window.navigation")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the current `window`'s associated {{domxref("Navigation")}} object. The entry point for the {{domxref("Navigation API")}}. - {{domxref("Window.navigator")}} {{ReadOnlyInline}} - : Returns a reference to the navigator object. diff --git a/files/en-us/web/api/window/navigation/index.md b/files/en-us/web/api/window/navigation/index.md index 48dd4660f1e76a4..fc5d2ffc37d011b 100644 --- a/files/en-us/web/api/window/navigation/index.md +++ b/files/en-us/web/api/window/navigation/index.md @@ -4,6 +4,7 @@ slug: Web/API/Window/navigation page-type: web-api-instance-property tags: - API + - Experimental - Navigate - Navigation - Navigation API @@ -13,7 +14,7 @@ tags: browser-compat: api.Window.navigation --- -{{ ApiRef() }} +{{APIRef}}{{seecompattable}} The `navigation` read-only property of the {{domxref("Window")}} interface returns the current `window`'s associated {{domxref("Navigation")}} object. From fad99a326bd6957286efde59e1ccbe97cbbbece0 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Fri, 4 Nov 2022 08:48:29 +0000 Subject: [PATCH 08/50] making fixes for domenic review comments --- files/en-us/web/api/navigateevent/index.md | 8 ++++---- .../navigation/currententrychange_event/index.md | 13 +++++++++++-- files/en-us/web/api/navigation/index.md | 10 +++++----- files/en-us/web/api/navigation/navigate/index.md | 2 +- .../web/api/navigation/navigate_event/index.md | 2 ++ .../api/navigation/navigatesuccess_event/index.md | 2 +- files/en-us/web/api/navigation/reload/index.md | 2 +- files/en-us/web/api/navigation_api/index.md | 6 +++--- .../api/navigationcurrententrychangeevent/index.md | 4 ++-- files/en-us/web/api/navigationdestination/index.md | 4 ++-- files/en-us/web/api/navigationhistoryentry/index.md | 4 ++-- files/en-us/web/api/navigationtransition/index.md | 2 +- 12 files changed, 35 insertions(+), 24 deletions(-) diff --git a/files/en-us/web/api/navigateevent/index.md b/files/en-us/web/api/navigateevent/index.md index 301b1d48c4e48b9..b391d671e1713b1 100644 --- a/files/en-us/web/api/navigateevent/index.md +++ b/files/en-us/web/api/navigateevent/index.md @@ -35,7 +35,7 @@ _Inherits properties from its parent, {{DOMxRef("Event")}}._ - {{domxref("NavigateEvent.canIntercept", "canIntercept")}} {{ReadOnlyInline}} - : Returns `true` if the navigation can be intercepted, or `false` otherwise (e.g. you can't intercept a cross-origin navigation). - {{domxref("NavigateEvent.destination", "destination")}} {{ReadOnlyInline}} - - : Returns the URL being navigated to. + - : Returns a {{domxref("NavigationDestination")}} object representing the destination being navigated to. - {{domxref("NavigateEvent.downloadRequest", "downloadRequest")}} {{ReadOnlyInline}} - : Returns the filename of the file requested for download, in the case of a download navigation (e.g. an {{htmlelement("a")}} or {{htmlelement("area")}} element with a `download` attribute), or `null` otherwise. - {{domxref("NavigateEvent.formData", "formData")}} {{ReadOnlyInline}} @@ -45,9 +45,9 @@ _Inherits properties from its parent, {{DOMxRef("Event")}}._ - {{domxref("NavigateEvent.info", "info")}} {{ReadOnlyInline}} - : Returns the `info` data value passed by the initiating navigation operation (e.g. {{domxref("Navigation.back()")}}, or {{domxref("Navigation.navigate()")}}), or `undefined` if no `info` data was passed. - {{domxref("NavigateEvent.navigationType", "navigationType")}} {{ReadOnlyInline}} - - : Returns the type of the navigation, which is one of `push`, `reload`, `replace`, or `traverse`. + - : Returns the type of the navigation, which a string equal to `push`, `reload`, `replace`, or `traverse`. - {{domxref("NavigateEvent.signal", "signal")}} {{ReadOnlyInline}} - - : Returns an {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button). + - : Returns an {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one). - {{domxref("NavigateEvent.userInitiated", "userInitiated")}} {{ReadOnlyInline}} - : Returns `true` if the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons), or `false` otherwise. @@ -56,7 +56,7 @@ _Inherits properties from its parent, {{DOMxRef("Event")}}._ _Inherits methods from its parent, {{DOMxRef("Event")}}._ - {{domxref("NavigateEvent.intercept", "intercept()")}} - - : Intercepts this navigation, turning it into a same-document navigation to the {{domxref("NavigateEvent.destination", "destination")}} URL. It can accept a handler that defines what the navigation handling behavior should be, plus options to control autofocus ansd scroll behavior as desired. + - : Intercepts this navigation, turning it into a same-document navigation to the {{domxref("{{domxref("NavigationDestination.url")}}", "destination")}} URL. It can accept a handler function that defines what the navigation handling behavior should be, plus `focusReset` and `scroll` options to control behavior as desired. - {{domxref("NavigateEvent.scroll", "scroll()")}} - : Can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed. diff --git a/files/en-us/web/api/navigation/currententrychange_event/index.md b/files/en-us/web/api/navigation/currententrychange_event/index.md index eedd235cc330283..61c85248a200963 100644 --- a/files/en-us/web/api/navigation/currententrychange_event/index.md +++ b/files/en-us/web/api/navigation/currententrychange_event/index.md @@ -42,11 +42,20 @@ oncurrententrychange = (event) => {}; ## Examples -`changeentrychange` could be used by analytics packages that don't care about the navigation finishing, just committing. It could also be used to set up relevant per-entry events, for example: +Navigation data reporting: ```js navigation.addEventListener("currententrychange", () => { - navigation.currentEntry.addEventListener("dispose", disposeHandler); + const data = navigation.currentEntry.getState(); + submitAnalyticsData(data.analytics); +}); +``` + +Setting up a per-entry event: + +```js +navigation.addEventListener("currententrychange", () => { + navigation.currentEntry.addEventListener("dispose", genericDisposeHandler); }); ``` diff --git a/files/en-us/web/api/navigation/index.md b/files/en-us/web/api/navigation/index.md index d205f3fab797db6..c8d95d65d7ce10d 100644 --- a/files/en-us/web/api/navigation/index.md +++ b/files/en-us/web/api/navigation/index.md @@ -23,7 +23,7 @@ The **`Navigation`** interface of the {{domxref("Navigation API")}} allows contr It is accessed via the {{domxref("Window.navigation")}} property. -The Navigation API only creates history entries created directly in the application document (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. +The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. {{InheritanceDiagram}} @@ -55,7 +55,7 @@ _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("Navigation/navigateerror_event", "navigateerror")}} - : Fired when a navigation fails. - {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} - - : Fired when a successful navigation has completed. + - : Fired when a successful navigation has finished. ## Instance methods @@ -68,13 +68,13 @@ _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("Navigation.forward", "forward()")}} - : Navigates forwards by one entry in the navigation history. - {{domxref("Navigation.navigate", "navigate()")}} - - : Navigates to a specific URL, updating any provided `state` in the history entries list. + - : Navigates to a specific URL, updating any provided state in the history entries list. - {{domxref("Navigation.reload", "reload()")}} - - : Reloads the current URL, updating any provided `state` in the history entries list. + - : Reloads the current URL, updating any provided state in the history entries list. - {{domxref("Navigation.traverseTo", "traverseTo()")}} - : Navigates to a specific {{domxref("NavigationHistoryEntry")}} by {{domxref("NavigationHistoryEntry.key", "key")}}. - {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}} - - : Updates the `state` of the {{domxref("Navigation.currentEntry","currentEntry")}}; used + - : Updates the state of the {{domxref("Navigation.currentEntry","currentEntry")}}; used in cases where the state change will be independent from a navigation or reload. ## Examples diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index 17d705d7a2a9074..623303eed2006cb 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -20,7 +20,7 @@ browser-compat: api.Navigation.navigate {{APIRef("Navigation API")}}{{seecompattable}} The **`navigate()`** method of the -{{domxref("Navigation")}} interface navigates to a specific URL, updating any provided `state` in the history entries list. +{{domxref("Navigation")}} interface navigates to a specific URL, updating any provided state in the history entries list. ## Syntax diff --git a/files/en-us/web/api/navigation/navigate_event/index.md b/files/en-us/web/api/navigation/navigate_event/index.md index 407ad04fd762523..7285a265300a76d 100644 --- a/files/en-us/web/api/navigation/navigate_event/index.md +++ b/files/en-us/web/api/navigation/navigate_event/index.md @@ -63,6 +63,8 @@ navigation.addEventListener('navigate', navigateEvent => { }); ``` +> **Note:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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()` ```js diff --git a/files/en-us/web/api/navigation/navigatesuccess_event/index.md b/files/en-us/web/api/navigation/navigatesuccess_event/index.md index fd6d09ebe0a917d..cdbd06a971cfb20 100644 --- a/files/en-us/web/api/navigation/navigatesuccess_event/index.md +++ b/files/en-us/web/api/navigation/navigatesuccess_event/index.md @@ -22,7 +22,7 @@ browser-compat: api.Navigation.navigatesuccess_event {{APIRef("Navigation API")}}{{SeeCompatTable}} -The **`navigatesuccess`** event of the {{domxref("Navigation")}} interface is fired when a successful navigation has completed. +The **`navigatesuccess`** event of the {{domxref("Navigation")}} interface is fired when a successful navigation has finished. This means that all promises returned by your `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling. diff --git a/files/en-us/web/api/navigation/reload/index.md b/files/en-us/web/api/navigation/reload/index.md index b5465381b2750a9..5b0ca2968a9159d 100644 --- a/files/en-us/web/api/navigation/reload/index.md +++ b/files/en-us/web/api/navigation/reload/index.md @@ -21,7 +21,7 @@ browser-compat: api.Navigation.reload {{APIRef("Navigation API")}}{{seecompattable}} The **`reload()`** method of the -{{domxref("Navigation")}} interface reloads the current URL, updating any provided `state` in the history entries list. +{{domxref("Navigation")}} interface reloads the current URL, updating any provided state in the history entries list. ## Syntax diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index c21be0016295552..9b2868b57e87ded 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -32,7 +32,7 @@ The API is accessed via the {{domxref("Window.navigation")}} property, which ret ### Handling navigations -`navigation` has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the {{domxref("History API")}}, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event has an event object of type {{domxref("NavigateEvent")}}, which contains detailed information including the navigation's destination URL, type, whether it contains `POST` form data or a download request, and more. +`navigation` has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the {{domxref("History API")}}, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event has an event object of type {{domxref("NavigateEvent")}}, which contains detailed information including details around the navigation's destination, type, whether it contains `POST` form data or a download request, and more. It also contains two methods: @@ -43,7 +43,7 @@ Once a navigation is initiated, and your `intercept()` handler is called, a {{do > **Note:** In this context "transition" refers to the transition between one history entry and another. It isn't related to CSS transitions. -> **Note:** In future implementations you will be able to call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely. This is specced out, but not currently implemented anywhere. +> **Note:** You can also call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely in most cases. This works today for most push, reload, and replace navigations; cancellation of traverse navigations is not yet implemented. When the `intercept()` handler function's promise fulfills, the `Navigate` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases if it is needed. @@ -53,7 +53,7 @@ When the `intercept()` handler function's promise fulfills, the `Navigate` objec As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct {{domxref("NavigationHistoryEntry")}} object instance. These contain several useful properties such as the entry's key, URL, and state information. You can return the entry that the user is currently navigated to right now using {{domxref("Navigation.currentEntry","currentEntry")}}, and an array of all existing history entries using {{domxref("Navigation.entries", "entries()")}}. Each `NavigationHistoryEntry` object has a {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} event, which fires when the entry is no longer part of the browser history (e.g. navigate back three times, then navigate forwards to somewhere else. Those three history entries will be disposed). -> **Note:** The Navigation API only creates history entries created directly in the application document (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. +> **Note:** The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. The `Navigation` object contains all the methods you'll need to update and traverse through the navigation history: diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/index.md index 3b28ad8fd6a3062..ae36e90c77b5aa3 100644 --- a/files/en-us/web/api/navigationcurrententrychangeevent/index.md +++ b/files/en-us/web/api/navigationcurrententrychangeevent/index.md @@ -37,7 +37,7 @@ This event fires after the navigation is committed, meaning that the visible URL _Inherits properties from its parent, {{DOMxRef("Event")}}._ - {{domxref("NavigationCurrentEntryChangeEvent.from", "from")}} {{ReadOnlyInline}} - - : Returns the {{domxref("NavigationHistoryEntry")}} that has changed. + - : Returns the {{domxref("NavigationHistoryEntry")}} that was navigated from. - {{domxref("NavigationCurrentEntryChangeEvent.navigationType", "navigationType")}} {{ReadOnlyInline}} - : Returns the type of the navigation that resulted in the change. @@ -47,7 +47,7 @@ Navigation data reporting: ```js navigation.addEventListener("currententrychange", () => { - const data = navigation.currentEntry.getState() + const data = navigation.currentEntry.getState(); submitAnalyticsData(data.analytics); }); ``` diff --git a/files/en-us/web/api/navigationdestination/index.md b/files/en-us/web/api/navigationdestination/index.md index 4f2ea119c46e234..04eb392d6c0e998 100644 --- a/files/en-us/web/api/navigationdestination/index.md +++ b/files/en-us/web/api/navigationdestination/index.md @@ -34,14 +34,14 @@ It is accessed via the {{domxref("NavigateEvent.destination")}} property. - {{domxref("NavigationDestination.key", "key")}} {{ReadOnlyInline}} - : Returns the {{domxref("NavigationHistoryEntry.key", "key")}} value of the destination {{domxref("NavigationHistoryEntry")}} if the {{domxref("NavigateEvent.navigationType")}} is `traverse`, or `null` otherwise. - {{domxref("NavigationDestination.sameDocument", "sameDocument")}} {{ReadOnlyInline}} - - : Returns `true` if the navigation is to the same `document` as the current {{domxref("Window.document")}} value, or `false` otherwise. + - : Returns `true` if the navigation is to the same `document` as the current {{domxref("Document")}} value, or `false` otherwise. - {{domxref("NavigationDestination.url", "url")}} {{ReadOnlyInline}} - : Returns the URL being navigated to. ## Instance methods - {{domxref("NavigationDestination.getState", "getState()")}} - - : Returns the available `state` associated with the destination {{domxref("NavigationHistoryEntry")}}, or navigation operation (e.g. {{domxref("Navigation.navigate()", "navigate()")}}) as appropriate. + - : Returns a clone of the available state associated with the destination {{domxref("NavigationHistoryEntry")}}, or navigation operation (e.g. {{domxref("Navigation.navigate()", "navigate()")}}) as appropriate. ## Examples diff --git a/files/en-us/web/api/navigationhistoryentry/index.md b/files/en-us/web/api/navigationhistoryentry/index.md index 45152ebf44a888d..602543d44f16ff3 100644 --- a/files/en-us/web/api/navigationhistoryentry/index.md +++ b/files/en-us/web/api/navigationhistoryentry/index.md @@ -23,7 +23,7 @@ The **`NavigationHistoryEntry`** interface of the {{domxref("Navigation API")}} These objects are commonly accessed via the {{domxref("Navigation.currentEntry")}} property and {{domxref("Navigation.entries()")}} method. -The Navigation API only creates history entries created directly in the application document (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. +The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. {{InheritanceDiagram}} @@ -52,7 +52,7 @@ _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("NavigationHistoryEntry.getState", "getState()")}} - - : Returns the available `state` associated with this history entry. + - : Returns a clone of the available state associated with this history entry. ## Examples diff --git a/files/en-us/web/api/navigationtransition/index.md b/files/en-us/web/api/navigationtransition/index.md index 216a37a6b4c31ef..c54b36f3bf3f284 100644 --- a/files/en-us/web/api/navigationtransition/index.md +++ b/files/en-us/web/api/navigationtransition/index.md @@ -19,7 +19,7 @@ browser-compat: api.NavigationTransition {{APIRef("Navigation API")}}{{seecompattable}} -The **`NavigationTransition`** interface of the {{domxref("Navigation API")}} represents an ongoing navigation, that is, a navigation that hasn't yet reached the {{domxref("Navigation/navigatesuccess_event", "success")}} or {{domxref("Navigation/navigateerror_event", "error")}} stage. +The **`NavigationTransition`** interface of the {{domxref("Navigation API")}} represents an ongoing navigation, that is, a navigation that hasn't yet reached the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} or {{domxref("Navigation/navigateerror_event", "navigateerror")}} stage. It is accessed via the {{domxref("Navigation.transition")}} property. From fc0e24088f7e435ede1da4d39cc5fdb2ba2edcb5 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Fri, 4 Nov 2022 09:03:07 +0000 Subject: [PATCH 09/50] fix macro error --- files/en-us/web/api/navigateevent/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigateevent/index.md b/files/en-us/web/api/navigateevent/index.md index b391d671e1713b1..9fb58077f27136f 100644 --- a/files/en-us/web/api/navigateevent/index.md +++ b/files/en-us/web/api/navigateevent/index.md @@ -56,7 +56,7 @@ _Inherits properties from its parent, {{DOMxRef("Event")}}._ _Inherits methods from its parent, {{DOMxRef("Event")}}._ - {{domxref("NavigateEvent.intercept", "intercept()")}} - - : Intercepts this navigation, turning it into a same-document navigation to the {{domxref("{{domxref("NavigationDestination.url")}}", "destination")}} URL. It can accept a handler function that defines what the navigation handling behavior should be, plus `focusReset` and `scroll` options to control behavior as desired. + - : Intercepts this navigation, turning it into a same-document navigation to the {{domxref("NavigationDestination.url", "destination")}} URL. It can accept a handler function that defines what the navigation handling behavior should be, plus `focusReset` and `scroll` options to control behavior as desired. - {{domxref("NavigateEvent.scroll", "scroll()")}} - : Can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed. From c0ed7538d3050de83fe2c0be16eafc03f52501fe Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Fri, 4 Nov 2022 11:09:02 +0000 Subject: [PATCH 10/50] add member pages for NavigationDestination and NavigationHistoryEntry --- .../currententrychange_event/index.md | 1 - .../api/navigation/navigate_event/index.md | 1 - .../navigation/navigateerror_event/index.md | 1 - .../navigation/navigatesuccess_event/index.md | 1 - .../navigationdestination/getstate/index.md | 66 +++++++++++++++++ .../web/api/navigationdestination/id/index.md | 52 ++++++++++++++ .../api/navigationdestination/index/index.md | 50 +++++++++++++ .../api/navigationdestination/key/index.md | 52 ++++++++++++++ .../sameDocument/index.md | 52 ++++++++++++++ .../api/navigationdestination/url/index.md | 70 +++++++++++++++++++ .../dispose_event/index.md | 59 ++++++++++++++++ .../navigationhistoryentry/getstate/index.md | 65 +++++++++++++++++ .../api/navigationhistoryentry/id/index.md | 49 +++++++++++++ .../web/api/navigationhistoryentry/index.md | 8 +-- .../api/navigationhistoryentry/index/index.md | 49 +++++++++++++ .../api/navigationhistoryentry/key/index.md | 63 +++++++++++++++++ .../samedocument/index.md | 50 +++++++++++++ .../api/navigationhistoryentry/url/index.md | 49 +++++++++++++ 18 files changed, 730 insertions(+), 8 deletions(-) create mode 100644 files/en-us/web/api/navigationdestination/getstate/index.md create mode 100644 files/en-us/web/api/navigationdestination/id/index.md create mode 100644 files/en-us/web/api/navigationdestination/index/index.md create mode 100644 files/en-us/web/api/navigationdestination/key/index.md create mode 100644 files/en-us/web/api/navigationdestination/sameDocument/index.md create mode 100644 files/en-us/web/api/navigationdestination/url/index.md create mode 100644 files/en-us/web/api/navigationhistoryentry/dispose_event/index.md create mode 100644 files/en-us/web/api/navigationhistoryentry/getstate/index.md create mode 100644 files/en-us/web/api/navigationhistoryentry/id/index.md create mode 100644 files/en-us/web/api/navigationhistoryentry/index/index.md create mode 100644 files/en-us/web/api/navigationhistoryentry/key/index.md create mode 100644 files/en-us/web/api/navigationhistoryentry/samedocument/index.md create mode 100644 files/en-us/web/api/navigationhistoryentry/url/index.md diff --git a/files/en-us/web/api/navigation/currententrychange_event/index.md b/files/en-us/web/api/navigation/currententrychange_event/index.md index 61c85248a200963..71a19fabfa8f3b3 100644 --- a/files/en-us/web/api/navigation/currententrychange_event/index.md +++ b/files/en-us/web/api/navigation/currententrychange_event/index.md @@ -13,7 +13,6 @@ tags: - Navigation API - Property - Reference - - reload - Scroll - Traversal - updateCurrentEntry diff --git a/files/en-us/web/api/navigation/navigate_event/index.md b/files/en-us/web/api/navigation/navigate_event/index.md index 7285a265300a76d..654192aeb4132db 100644 --- a/files/en-us/web/api/navigation/navigate_event/index.md +++ b/files/en-us/web/api/navigation/navigate_event/index.md @@ -12,7 +12,6 @@ tags: - Navigation API - Property - Reference - - reload - Scroll - Traversal - updateCurrentEntry diff --git a/files/en-us/web/api/navigation/navigateerror_event/index.md b/files/en-us/web/api/navigation/navigateerror_event/index.md index b95f33df302a10e..5b1f937eabdcdc5 100644 --- a/files/en-us/web/api/navigation/navigateerror_event/index.md +++ b/files/en-us/web/api/navigation/navigateerror_event/index.md @@ -13,7 +13,6 @@ tags: - Navigation API - Property - Reference - - reload - Scroll - Traversal - updateCurrentEntry diff --git a/files/en-us/web/api/navigation/navigatesuccess_event/index.md b/files/en-us/web/api/navigation/navigatesuccess_event/index.md index cdbd06a971cfb20..1e168d90b8d13a3 100644 --- a/files/en-us/web/api/navigation/navigatesuccess_event/index.md +++ b/files/en-us/web/api/navigation/navigatesuccess_event/index.md @@ -13,7 +13,6 @@ tags: - Navigation API - Property - Reference - - reload - Scroll - Traversal - updateCurrentEntry diff --git a/files/en-us/web/api/navigationdestination/getstate/index.md b/files/en-us/web/api/navigationdestination/getstate/index.md new file mode 100644 index 000000000000000..105d340ba94d378 --- /dev/null +++ b/files/en-us/web/api/navigationdestination/getstate/index.md @@ -0,0 +1,66 @@ +--- +title: NavigationDestination.getState() +slug: Web/API/NavigationDestination/getState +page-type: web-api-instance-method +tags: + - API + - Experimental + - getState + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.NavigationDestination.getState +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`getState()`** method of the +{{domxref("NavigationDestination")}} interface returns a clone of the available state associated with the destination {{domxref("NavigationHistoryEntry")}}, or navigation operation (e.g. {{domxref("Navigation.navigate()", "navigate()")}}) as appropriate. + +## Syntax + +```js-nolint +getState() +``` + +### Parameters + +None. + +### Return value + +A value representing the state. This can be any type. + +If no state is defined, it returns `undefined`. + +### Exceptions + +None. + +## Examples + +```js +navigation.addEventListener('navigate', navigateEvent => { + console.log(navigateEvent.destination.getState()); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationdestination/id/index.md b/files/en-us/web/api/navigationdestination/id/index.md new file mode 100644 index 000000000000000..14ff12867883536 --- /dev/null +++ b/files/en-us/web/api/navigationdestination/id/index.md @@ -0,0 +1,52 @@ +--- +title: NavigationDestination.id +slug: Web/API/NavigationDestination/id +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - id + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationDestination.id +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`id`** read-only property of the +{{domxref("NavigationDestination")}} interface returns the {{domxref("NavigationHistoryEntry.id", "id")}} value of the destination {{domxref("NavigationHistoryEntry")}} if the {{domxref("NavigateEvent.navigationType")}} is `traverse`, or `null` otherwise. + +The `id` is a unique, UA-generated value that always represents the history entry, useful to correlate a history entry with an external resource such as a storage cache. + +## Value + +A string representing the `id` of the destination {{domxref("NavigationHistoryEntry")}}, or `null`. + +## Examples + +```js +navigation.addEventListener('navigate', navigateEvent => { + console.log(navigateEvent.destination.id); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationdestination/index/index.md b/files/en-us/web/api/navigationdestination/index/index.md new file mode 100644 index 000000000000000..599e18916c8c7a9 --- /dev/null +++ b/files/en-us/web/api/navigationdestination/index/index.md @@ -0,0 +1,50 @@ +--- +title: NavigationDestination.index +slug: Web/API/NavigationDestination/index +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - index + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationDestination.index +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`index`** read-only property of the +{{domxref("NavigationDestination")}} interface returns the {{domxref("NavigationHistoryEntry.index", "index")}} value of the destination {{domxref("NavigationHistoryEntry")}} if the {{domxref("NavigateEvent.navigationType")}} is `traverse`, or `-1` otherwise. + +## Value + +A number representing the `index` of the destination {{domxref("NavigationHistoryEntry")}}, or -1. + +## Examples + +```js +navigation.addEventListener('navigate', navigateEvent => { + console.log(navigateEvent.destination.index); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationdestination/key/index.md b/files/en-us/web/api/navigationdestination/key/index.md new file mode 100644 index 000000000000000..99b2c15a952f473 --- /dev/null +++ b/files/en-us/web/api/navigationdestination/key/index.md @@ -0,0 +1,52 @@ +--- +title: NavigationDestination.key +slug: Web/API/NavigationDestination/key +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - key + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationDestination.key +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`key`** read-only property of the +{{domxref("NavigationDestination")}} interface returns the {{domxref("NavigationHistoryEntry.key", "key")}} value of the destination {{domxref("NavigationHistoryEntry")}} if the {{domxref("NavigateEvent.navigationType")}} is `traverse`, or `null` otherwise. + +The `key` is a unique, UA-generated value that represents the history entry's slot in the history entries list, used to navigate to this place in the history via {{domxref("Navigation.traverseTo()")}}. It will be reused by other entries that replace the entry in the list (i.e. if the {{domxref("NavigateEvent.navigationType")}} is `replace`). + +## Value + +A string representing the `key` of the destination {{domxref("NavigationHistoryEntry")}}, or `null`. + +## Examples + +```js +navigation.addEventListener('navigate', navigateEvent => { + console.log(navigateEvent.destination.key); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationdestination/sameDocument/index.md b/files/en-us/web/api/navigationdestination/sameDocument/index.md new file mode 100644 index 000000000000000..c02a746bc15911e --- /dev/null +++ b/files/en-us/web/api/navigationdestination/sameDocument/index.md @@ -0,0 +1,52 @@ +--- +title: NavigationDestination.sameDocument +slug: Web/API/NavigationDestination/sameDocument +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - sameDocument + - Scroll + - Traversal +browser-compat: api.NavigationDestination.sameDocument +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`sameDocument`** read-only property of the +{{domxref("NavigationDestination")}} interface returns `true` if the navigation is to the same `document` as the current {{domxref("Document")}} value, or `false` otherwise. + +This is useful for checking whether the navigation will be same-document or cross-document. + +## Value + +A boolean. + +## Examples + +```js +navigation.addEventListener('navigate', navigateEvent => { + console.log(navigateEvent.destination.sameDocument); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationdestination/url/index.md b/files/en-us/web/api/navigationdestination/url/index.md new file mode 100644 index 000000000000000..95f59facdbc0e08 --- /dev/null +++ b/files/en-us/web/api/navigationdestination/url/index.md @@ -0,0 +1,70 @@ +--- +title: NavigationDestination.url +slug: Web/API/NavigationDestination/url +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal + - url +browser-compat: api.NavigationDestination.url +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`url`** read-only property of the +{{domxref("NavigationDestination")}} interface returns the URL being navigated to. + +## Value + +A string. + +## Examples + +### Handling a navigation using `intercept()` + +```js +navigation.addEventListener('navigate', navigateEvent => { + // Exit early if this navigation shouldn't be intercepted, + // e.g. if the navigation is cross-origin, or a download request + if (shouldNotIntercept(navigateEvent)) return; + + const url = new URL(navigateEvent.destination.url); + + if (url.pathname.startsWith('/articles/')) { + navigateEvent.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); + }, + }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md b/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md new file mode 100644 index 000000000000000..061963981e7bb34 --- /dev/null +++ b/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md @@ -0,0 +1,59 @@ +--- +title: "NavigationHistoryEntry: dispose event" +slug: Web/API/NavigationHistoryEntry/dispose_event +page-type: web-api-event +tags: + - API + - dispose + - Event + - Experimental + - History + - Navigate + - navigateerror + - Navigation + - Navigation API + - Property + - Reference + - Scroll + - Traversal + - updateCurrentEntry +browser-compat: api.NavigationHistoryEntry.dispose_event +--- + +{{APIRef("Navigation API")}}{{SeeCompatTable}} + +The **`dispose`** event of the {{domxref("NavigationHistoryEntry")}} interface is fired when the entry is no longer part of the history entry list. + +## Syntax + +Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. + +```js +addEventListener("dispose", (event) => {}); + +ondispose = (event) => {}; +``` + +> **Note:** The event object is of type {{domxref("Event")}}. + +## Examples + +```js +navigation.addEventListener("currententrychange", () => { + navigation.currentEntry.addEventListener("dispose", disposeHandler); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationhistoryentry/getstate/index.md b/files/en-us/web/api/navigationhistoryentry/getstate/index.md new file mode 100644 index 000000000000000..22d99de53c66c61 --- /dev/null +++ b/files/en-us/web/api/navigationhistoryentry/getstate/index.md @@ -0,0 +1,65 @@ +--- +title: NavigationHistoryEntry.getState() +slug: Web/API/NavigationHistoryEntry/getState +page-type: web-api-instance-method +tags: + - API + - Experimental + - getState + - History + - Method + - Navigate + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.NavigationHistoryEntry.getState +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`getState()`** method of the +{{domxref("NavigationHistoryEntry")}} interface returns a clone of the available state associated with this history entry. + +## Syntax + +```js-nolint +getState() +``` + +### Parameters + +None. + +### Return value + +A value representing the state. This can be any type. + +If no state is defined, it returns `undefined`. + +### Exceptions + +None. + +## Examples + +```js +let current = navigation.currentEntry; +console.log(current.getState()); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationhistoryentry/id/index.md b/files/en-us/web/api/navigationhistoryentry/id/index.md new file mode 100644 index 000000000000000..9dae8926bcde3f6 --- /dev/null +++ b/files/en-us/web/api/navigationhistoryentry/id/index.md @@ -0,0 +1,49 @@ +--- +title: NavigationHistoryEntry.id +slug: Web/API/NavigationHistoryEntry/id +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - id + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationHistoryEntry.id +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`id`** read-only property of the +{{domxref("NavigationHistoryEntry")}} interface returns the `id` of the history entry. This is a unique, UA-generated value that always represents the history entry, useful to correlate a history entry with an external resource such as a storage cache. + +## Value + +A string representing the `id` of the destination {{domxref("NavigationHistoryEntry")}}. + +## Examples + +```js +let current = navigation.currentEntry; +console.log(current.id); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationhistoryentry/index.md b/files/en-us/web/api/navigationhistoryentry/index.md index 602543d44f16ff3..d70bc3118107e57 100644 --- a/files/en-us/web/api/navigationhistoryentry/index.md +++ b/files/en-us/web/api/navigationhistoryentry/index.md @@ -32,15 +32,15 @@ The Navigation API only exposes history entries created directly by the applicat _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("NavigationHistoryEntry.id", "id")}} {{ReadOnlyInline}} - - : Returns a unique, UA-generated value that always represents the history entry, useful to correlate a history entry with an external resource such as a storage cache. + - : Returns the `id` of the history entry. This is a unique, UA-generated value that always represents the history entry, useful to correlate a history entry with an external resource such as a storage cache. - {{domxref("NavigationHistoryEntry.index", "index")}} {{ReadOnlyInline}} - : Returns the index of the history entry in the history entries list (i.e. returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list. - {{domxref("NavigationHistoryEntry.key", "key")}} {{ReadOnlyInline}} - - : Returns a unique, UA-generated value that represents the history entry's slot in the history entries list, used to navigate to this place in the history via {{domxref("Navigation.traverseTo()")}}. It will be reused by other entries that replace the entry in the list (i.e. if the {{domxref("NavigateEvent.navigationType")}} is `replace`). + - : Returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the history entries list, used to navigate to this place in the history via {{domxref("Navigation.traverseTo()")}}. It will be reused by other entries that replace the entry in the list (i.e. if the {{domxref("NavigateEvent.navigationType")}} is `replace`). - {{domxref("NavigationHistoryEntry.sameDocument", "sameDocument")}} {{ReadOnlyInline}} - - : Returns `true` if this history entry is for the same `document` as the current {{domxref("Window.document")}} value, or `false` otherwise. + - : Returns `true` if this history entry is for the same `document` as the current {{domxref("Document")}} value, or `false` otherwise. - {{domxref("NavigationHistoryEntry.url", "url")}} {{ReadOnlyInline}} - - : Returns the URL of this history entry. + - : Returns the absolute URL of this history entry. ## `NavigationHistoryEntry` events diff --git a/files/en-us/web/api/navigationhistoryentry/index/index.md b/files/en-us/web/api/navigationhistoryentry/index/index.md new file mode 100644 index 000000000000000..c1921f0d1a3b2da --- /dev/null +++ b/files/en-us/web/api/navigationhistoryentry/index/index.md @@ -0,0 +1,49 @@ +--- +title: NavigationHistoryEntry.index +slug: Web/API/NavigationHistoryEntry/index +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - index + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationHistoryEntry.index +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`index`** read-only property of the +{{domxref("NavigationHistoryEntry")}} interface returns the index of the history entry in the history entries list (i.e. returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list. + +## Value + +A number representing the `index` of the destination {{domxref("NavigationHistoryEntry")}}, or `-1`. + +## Examples + +```js +let current = navigation.currentEntry; +console.log(current.index); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationhistoryentry/key/index.md b/files/en-us/web/api/navigationhistoryentry/key/index.md new file mode 100644 index 000000000000000..3eaa6c19b209482 --- /dev/null +++ b/files/en-us/web/api/navigationhistoryentry/key/index.md @@ -0,0 +1,63 @@ +--- +title: NavigationHistoryEntry.key +slug: Web/API/NavigationHistoryEntry/key +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - key + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationHistoryEntry.key +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`key`** read-only property of the +{{domxref("NavigationHistoryEntry")}} interface returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the history entries list, used to navigate to this place in the history via {{domxref("Navigation.traverseTo()")}}. It will be reused by other entries that replace the entry in the list (i.e. if the {{domxref("NavigateEvent.navigationType")}} is `replace`). + +## Value + +A string representing the `key` of the destination {{domxref("NavigationHistoryEntry")}}. + +## Examples + +### Basic usage + +```js +let current = navigation.currentEntry; +console.log(current.key); +``` + +### Set up a home button + +```js +// On JS startup, get the key of the first loaded page +// so the user can always go back there. +const {key} = navigation.currentEntry; +backToHomeButton.onclick = () => navigation.traverseTo(key); + +// Navigate away, but the button will always work. +await navigation.navigate('/another_url').finished; +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationhistoryentry/samedocument/index.md b/files/en-us/web/api/navigationhistoryentry/samedocument/index.md new file mode 100644 index 000000000000000..05a9acb4837c594 --- /dev/null +++ b/files/en-us/web/api/navigationhistoryentry/samedocument/index.md @@ -0,0 +1,50 @@ +--- +title: NavigationHistoryEntry.sameDocument +slug: Web/API/NavigationHistoryEntry/sameDocument +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - sameDocument + - Scroll + - Traversal +browser-compat: api.NavigationHistoryEntry.sameDocument +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`sameDocument`** read-only property of the +{{domxref("NavigationHistoryEntry")}} interface returns `true` if this history entry is for the same `document` as the current {{domxref("Document")}} value, or `false` otherwise. + +## Value + +A boolean. + +## Examples + +```js +let current = navigation.currentEntry; +console.log(current.sameDocument); +// Will always return true +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationhistoryentry/url/index.md b/files/en-us/web/api/navigationhistoryentry/url/index.md new file mode 100644 index 000000000000000..145f6bf6dd446c9 --- /dev/null +++ b/files/en-us/web/api/navigationhistoryentry/url/index.md @@ -0,0 +1,49 @@ +--- +title: NavigationHistoryEntry.url +slug: Web/API/NavigationHistoryEntry/url +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal + - url +browser-compat: api.NavigationHistoryEntry.url +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`url`** read-only property of the +{{domxref("NavigationHistoryEntry")}} interface returns the absolute URL of this history entry. + +## Value + +A string representing the URL. + +## Examples + +```js +let current = navigation.currentEntry; +console.log(current.url); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) From 72f8ce216d1644f7cfae90140eeb353275e009c3 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Fri, 4 Nov 2022 11:15:55 +0000 Subject: [PATCH 11/50] attempt to fix folder name casing From b2e1e36dc576b4b99ce82fcc0b042991b582207b Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Mon, 7 Nov 2022 06:51:59 +0000 Subject: [PATCH 12/50] fix casing issue in directory name --- .../navigationdestination/{sameDocument => samedocument}/index.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename files/en-us/web/api/navigationdestination/{sameDocument => samedocument}/index.md (100%) diff --git a/files/en-us/web/api/navigationdestination/sameDocument/index.md b/files/en-us/web/api/navigationdestination/samedocument/index.md similarity index 100% rename from files/en-us/web/api/navigationdestination/sameDocument/index.md rename to files/en-us/web/api/navigationdestination/samedocument/index.md From 4554e97099ea4f9efb488efafe4ce3ed8b48a9ab Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Mon, 7 Nov 2022 11:13:41 +0000 Subject: [PATCH 13/50] add all remaining pages, fix flaws --- .../api/navigateevent/canintercept/index.md | 70 ++++++++++ .../api/navigateevent/destination/index.md | 69 ++++++++++ .../navigateevent/downloadrequest/index.md | 70 ++++++++++ .../web/api/navigateevent/formdata/index.md | 70 ++++++++++ .../web/api/navigateevent/hashchange/index.md | 70 ++++++++++ files/en-us/web/api/navigateevent/index.md | 20 +-- .../en-us/web/api/navigateevent/info/index.md | 72 ++++++++++ .../web/api/navigateevent/intercept/index.md | 124 ++++++++++++++++++ .../api/navigateevent/navigateevent/index.md | 96 ++++++++++++++ .../api/navigateevent/navigationtype/index.md | 87 ++++++++++++ .../web/api/navigateevent/scroll/index.md | 80 +++++++++++ .../web/api/navigateevent/signal/index.md | 63 +++++++++ .../api/navigateevent/userinitiated/index.md | 53 ++++++++ .../api/navigation/navigate_event/index.md | 16 +-- files/en-us/web/api/navigation_api/index.md | 18 +-- .../from/index.md | 50 +++++++ .../index.md | 63 +++++++++ .../navigationtype/index.md | 57 ++++++++ .../navigationdestination/getstate/index.md | 4 +- .../web/api/navigationdestination/id/index.md | 4 +- .../web/api/navigationdestination/index.md | 8 +- .../api/navigationdestination/index/index.md | 4 +- .../api/navigationdestination/key/index.md | 4 +- .../samedocument/index.md | 4 +- .../api/navigationdestination/url/index.md | 8 +- .../navigationtransition/finished/index.md | 50 +++++++ .../api/navigationtransition/from/index.md | 48 +++++++ .../web/api/navigationtransition/index.md | 8 +- .../navigationtype/index.md | 55 ++++++++ 29 files changed, 1296 insertions(+), 49 deletions(-) create mode 100644 files/en-us/web/api/navigateevent/canintercept/index.md create mode 100644 files/en-us/web/api/navigateevent/destination/index.md create mode 100644 files/en-us/web/api/navigateevent/downloadrequest/index.md create mode 100644 files/en-us/web/api/navigateevent/formdata/index.md create mode 100644 files/en-us/web/api/navigateevent/hashchange/index.md create mode 100644 files/en-us/web/api/navigateevent/info/index.md create mode 100644 files/en-us/web/api/navigateevent/intercept/index.md create mode 100644 files/en-us/web/api/navigateevent/navigateevent/index.md create mode 100644 files/en-us/web/api/navigateevent/navigationtype/index.md create mode 100644 files/en-us/web/api/navigateevent/scroll/index.md create mode 100644 files/en-us/web/api/navigateevent/signal/index.md create mode 100644 files/en-us/web/api/navigateevent/userinitiated/index.md create mode 100644 files/en-us/web/api/navigationcurrententrychangeevent/from/index.md create mode 100644 files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md create mode 100644 files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md create mode 100644 files/en-us/web/api/navigationtransition/finished/index.md create mode 100644 files/en-us/web/api/navigationtransition/from/index.md create mode 100644 files/en-us/web/api/navigationtransition/navigationtype/index.md diff --git a/files/en-us/web/api/navigateevent/canintercept/index.md b/files/en-us/web/api/navigateevent/canintercept/index.md new file mode 100644 index 000000000000000..e230e326d1ba301 --- /dev/null +++ b/files/en-us/web/api/navigateevent/canintercept/index.md @@ -0,0 +1,70 @@ +--- +title: NavigateEvent.canIntercept +slug: Web/API/NavigateEvent/canIntercept +page-type: web-api-instance-property +tags: + - API + - canIntercept + - Experimental + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigateEvent.canIntercept +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`canIntercept`** read-only property of the +{{domxref("NavigateEvent")}} interface returns `true` if the navigation can be intercepted, or `false` otherwise (e.g. you can't intercept a cross-origin navigation). + +## Value + +A boolean value—`true` if the navigation can be intercepted, `false` if not. + +## Examples + +```js +navigation.addEventListener("navigate", event => { + // Some navigations, e.g. cross-origin navigations, we + // cannot intercept. Let the browser handle those normally. + if (!event.canIntercept) { + return; + } + + // Don't intercept fragment navigations or downloads. + if (event.hashChange || event.downloadRequest !== null) { + return; + } + + event.intercept({ + handler() { + if (event.formData) { + processFormDataAndUpdateUI(event.formData, event.signal); + } else { + doSinglePageAppNav(event.destination, event.signal); + } + } + }); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/destination/index.md b/files/en-us/web/api/navigateevent/destination/index.md new file mode 100644 index 000000000000000..c49269914dd0236 --- /dev/null +++ b/files/en-us/web/api/navigateevent/destination/index.md @@ -0,0 +1,69 @@ +--- +title: NavigateEvent.destination +slug: Web/API/NavigateEvent/destination +page-type: web-api-instance-property +tags: + - API + - destination + - Experimental + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigateEvent.destination +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`destination`** read-only property of the +{{domxref("NavigateEvent")}} interface returns a {{domxref("NavigationDestination")}} object representing the destination being navigated to. + +## Value + +A {{domxref("NavigationDestination")}} object. + +## Examples + +```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); + }, + }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/downloadrequest/index.md b/files/en-us/web/api/navigateevent/downloadrequest/index.md new file mode 100644 index 000000000000000..9823db9d31aed6d --- /dev/null +++ b/files/en-us/web/api/navigateevent/downloadrequest/index.md @@ -0,0 +1,70 @@ +--- +title: NavigateEvent.downloadRequest +slug: Web/API/NavigateEvent/downloadRequest +page-type: web-api-instance-property +tags: + - API + - downloadRequest + - Experimental + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigateEvent.downloadRequest +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`downloadRequest`** read-only property of the +{{domxref("NavigateEvent")}} interface returns the filename of the file requested for download, in the case of a download navigation (e.g. an {{htmlelement("a")}} or {{htmlelement("area")}} element with a `download` attribute), or `null` otherwise. + +## Value + +A string containing the filename of the file requested for download, or `null`. + +## Examples + +```js +navigation.addEventListener("navigate", event => { + // Some navigations, e.g. cross-origin navigations, we + // cannot intercept. Let the browser handle those normally. + if (!event.canIntercept) { + return; + } + + // Don't intercept fragment navigations or downloads. + if (event.hashChange || event.downloadRequest !== null) { + return; + } + + event.intercept({ + handler() { + if (event.formData) { + processFormDataAndUpdateUI(event.formData, event.signal); + } else { + doSinglePageAppNav(event.destination, event.signal); + } + } + }); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/formdata/index.md b/files/en-us/web/api/navigateevent/formdata/index.md new file mode 100644 index 000000000000000..4c8eea4e055b17e --- /dev/null +++ b/files/en-us/web/api/navigateevent/formdata/index.md @@ -0,0 +1,70 @@ +--- +title: NavigateEvent.formData +slug: Web/API/NavigateEvent/formData +page-type: web-api-instance-property +tags: + - API + - Experimental + - formData + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigateEvent.formData +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`formData`** read-only property of the +{{domxref("NavigateEvent")}} interface returns the {{domxref("FormData")}} object representing the submitted data in the case of a `POST` form submission, or `null` otherwise. + +## Value + +A {{domxref("FormData")}} object, or `null`. + +## Examples + +```js +navigation.addEventListener("navigate", event => { + // Some navigations, e.g. cross-origin navigations, we + // cannot intercept. Let the browser handle those normally. + if (!event.canIntercept) { + return; + } + + // Don't intercept fragment navigations or downloads. + if (event.hashChange || event.downloadRequest !== null) { + return; + } + + event.intercept({ + handler() { + if (event.formData) { + processFormDataAndUpdateUI(event.formData, event.signal); + } else { + doSinglePageAppNav(event.destination, event.signal); + } + } + }); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/hashchange/index.md b/files/en-us/web/api/navigateevent/hashchange/index.md new file mode 100644 index 000000000000000..08b0586a846f633 --- /dev/null +++ b/files/en-us/web/api/navigateevent/hashchange/index.md @@ -0,0 +1,70 @@ +--- +title: NavigateEvent.hashChange +slug: Web/API/NavigateEvent/hashChange +page-type: web-api-instance-property +tags: + - API + - Experimental + - hashChange + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigateEvent.hashChange +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`hashChange`** read-only property of the +{{domxref("NavigateEvent")}} interface returns `true` if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document), or `false` otherwise. + +## Value + +A boolean value—`true` if the navigation is a fragment navigation, `false` if not. + +## Examples + +```js +navigation.addEventListener("navigate", event => { + // Some navigations, e.g. cross-origin navigations, we + // cannot intercept. Let the browser handle those normally. + if (!event.canIntercept) { + return; + } + + // Don't intercept fragment navigations or downloads. + if (event.hashChange || event.downloadRequest !== null) { + return; + } + + event.intercept({ + handler() { + if (event.formData) { + processFormDataAndUpdateUI(event.formData, event.signal); + } else { + doSinglePageAppNav(event.destination, event.signal); + } + } + }); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/index.md b/files/en-us/web/api/navigateevent/index.md index 9fb58077f27136f..31693951c3a8e9e 100644 --- a/files/en-us/web/api/navigateevent/index.md +++ b/files/en-us/web/api/navigateevent/index.md @@ -39,13 +39,13 @@ _Inherits properties from its parent, {{DOMxRef("Event")}}._ - {{domxref("NavigateEvent.downloadRequest", "downloadRequest")}} {{ReadOnlyInline}} - : Returns the filename of the file requested for download, in the case of a download navigation (e.g. an {{htmlelement("a")}} or {{htmlelement("area")}} element with a `download` attribute), or `null` otherwise. - {{domxref("NavigateEvent.formData", "formData")}} {{ReadOnlyInline}} - - : Returns the {{domxref("FormData")}} object representing the submitted data in the case of a `POST` form submission, or null otherwise. + - : Returns the {{domxref("FormData")}} object representing the submitted data in the case of a `POST` form submission, or `null` otherwise. - {{domxref("NavigateEvent.hashChange", "hashChange")}} {{ReadOnlyInline}} - : Returns `true` if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document), or `false` otherwise. - {{domxref("NavigateEvent.info", "info")}} {{ReadOnlyInline}} - : Returns the `info` data value passed by the initiating navigation operation (e.g. {{domxref("Navigation.back()")}}, or {{domxref("Navigation.navigate()")}}), or `undefined` if no `info` data was passed. - {{domxref("NavigateEvent.navigationType", "navigationType")}} {{ReadOnlyInline}} - - : Returns the type of the navigation, which a string equal to `push`, `reload`, `replace`, or `traverse`. + - : Returns the type of the navigation — `push`, `reload`, `replace`, or `traverse`. - {{domxref("NavigateEvent.signal", "signal")}} {{ReadOnlyInline}} - : Returns an {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one). - {{domxref("NavigateEvent.userInitiated", "userInitiated")}} {{ReadOnlyInline}} @@ -65,15 +65,15 @@ _Inherits methods from its parent, {{DOMxRef("Event")}}._ ### Handling a navigation using `intercept()` ```js -navigation.addEventListener('navigate', navigateEvent => { +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(navigateEvent)) return; + if (shouldNotIntercept(event)) return; - const url = new URL(navigateEvent.destination.url); + const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { - navigateEvent.intercept({ + 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 @@ -93,16 +93,16 @@ navigation.addEventListener('navigate', navigateEvent => { ### Handling scrolling using `scroll()` ```js -navigation.addEventListener('navigate', navigateEvent => { +navigation.addEventListener('navigate', event => { if (shouldNotIntercept(navigateEvent)) return; - const url = new URL(navigateEvent.destination.url); + const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { - navigateEvent.intercept({ + event.intercept({ async handler() { const articleContent = await getArticleContent(url.pathname); renderArticlePage(articleContent); - navigateEvent.scroll(); + event.scroll(); const secondaryContent = await getSecondaryContent(url.pathname); addSecondaryContent(secondaryContent); diff --git a/files/en-us/web/api/navigateevent/info/index.md b/files/en-us/web/api/navigateevent/info/index.md new file mode 100644 index 000000000000000..1baae5839663977 --- /dev/null +++ b/files/en-us/web/api/navigateevent/info/index.md @@ -0,0 +1,72 @@ +--- +title: NavigateEvent.info +slug: Web/API/NavigateEvent/info +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - info + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigateEvent.info +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`info`** read-only property of the +{{domxref("NavigateEvent")}} interface returns the `info` data value passed by the initiating navigation operation (e.g. {{domxref("Navigation.back()")}}, or {{domxref("Navigation.navigate()")}}), or `undefined` if no `info` data was passed. + +## Value + +Any data type representing the `info` value, or `false` if none was passed. + +## Examples + +One example of how `info` might be used is to trigger different single-page navigation renderings depending on how a certain route was reached. For example, consider a photo gallery app, where you can reach the same photo URL and state via various routes. You might want to use a different animation to show the photo for each route. + +```js +navigation.addEventListener("navigate", event => { + if (isPhotoNavigation(event)) { + event.intercept({ async handler() { + switch (event.info.?via) { + case "go-left": { + await animateLeft(); + break; + } + case "go-right": { + await animateRight(); + break; + } + case "gallery": { + await animateZoomFromThumbnail(event.info.thumbnail); + break; + } + } + + // TODO: actually load the photo. + } }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/intercept/index.md b/files/en-us/web/api/navigateevent/intercept/index.md new file mode 100644 index 000000000000000..37039d98fa2610c --- /dev/null +++ b/files/en-us/web/api/navigateevent/intercept/index.md @@ -0,0 +1,124 @@ +--- +title: NavigateEvent.intercept() +slug: Web/API/NavigateEvent/intercept +page-type: web-api-instance-method +tags: + - API + - Experimental + - History + - intercept + - Method + - NavigateEvent + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.NavigateEvent.intercept +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`intercept()`** method of the +{{domxref("NavigateEvent")}} interface intercepts this navigation, turning it into a same-document navigation to the {{domxref("NavigationDestination.url", "destination")}} URL. + +## Syntax + +```js-nolint +intercept(options) +``` + +### Parameters + +- `options` {{optional_inline}} + - : An options object containing the following properties: + - `handler` + - : A callback function that defines what the navigation handling behavior should be. This generally handles resource fetching, and returns a promise. + - `focusReset` + - : Defines the navigation's focus behavior. Once the promise returned by your handler function resolves, by default the browser will focus the first element with the {{htmlattrxref("autofocus")}} attribute, or the {{htmlelement("body")}} element if no element has `autofocus` set. You can turn this behavior off setting `focusReset` to `manual`. The other available value is `after-transition`, which is the default. + - `scroll` + - : Defines the navigation's focus behavior. By default the browser will handle scrolling, for example by scrolling to the relevant fragment identifier if the URL contains a fragment, or restoring the scroll position to the same place as last time if the page is reloaded or page in the history is revisited. You can turn this behavior off setting `scroll` to `manual`. The other available value is `after-transition`, which is the default. + +### Return value + +`undefined`. + +### Exceptions + +- `InvalidStateError` {{domxref("DOMException")}} + - : Thrown if the current {{domxref("Document")}} is not yet active, or if the navigation has been cancelled. +- `SecurityError` {{domxref("DOMException")}} + - : Thrown if the event was dispatched by a {{domxref("EventTarget.dispatchEvent", "dispatchEvent()")}} call, rather than the user agent, or if the navigation cannot be intercepted (i.e. {{domxref("NavigateEvent.canIntercept")}} is `false`). + +## Examples + +### 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); + }, + }); + } +}); +``` + +### Using `focusReset` and `scroll` + +Form submission can be detected by querying for the {{domxref("NavigateEvent.formData")}} property. The following example turns any form submission into one which stays on the current page. In this case, you don't update the DOM, so you can cancel any default reset and scroll behavior using `focusReset` and `scroll`. + +```js +navigation.addEventListener('navigate', event => { + if (event.formData && event.canIntercept) { + // User submitted a POST form to a same-domain URL + // (If canIntercept is false, the event is just informative: + // you can't intercept this request, although you could + // likely still call .preventDefault() to stop it completely). + + event.intercept({ + // Since we don't update the DOM in this navigation, + // don't allow focus or scrolling to reset: + focusReset: 'manual', + scroll: 'manual', + handler() { + await fetch(event.destination.url, { + method: 'POST', + body: event.formData, + }); + // You could navigate again with {history: 'replace'} to change the URL here, + // which might indicate "done" + }, + }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/navigateevent/index.md b/files/en-us/web/api/navigateevent/navigateevent/index.md new file mode 100644 index 000000000000000..0bc1224b7d9134e --- /dev/null +++ b/files/en-us/web/api/navigateevent/navigateevent/index.md @@ -0,0 +1,96 @@ +--- +title: NavigateEvent() +slug: Web/API/NavigateEvent/NavigateEvent +page-type: web-api-constructor +tags: + - API + - Constructor + - Experimental + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Reference + - Scroll + - Traversal +browser-compat: api.NavigateEvent.NavigateEvent +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`NavigateEvent()`** constructor creates a new +{{domxref("NavigateEvent")}} object instance. + +## Syntax + +```js-nolint +new NavigateEvent(type, init) +``` + +### Parameters + +- `type` + - : A string representing the type of event. In the case of `NavigateEvent` this is always `navigate`. +- `init` + - : An object containing the following properties: + - `canIntercept` {{optional_inline}} + - : A boolean defining whether the navigation can be intercepted or not (e.g. you can't intercept a cross-origin navigation). Defaults to `false`. + - `destination` + - : A {{domxref("NavigationDestination")}} object representing the location being navigated to. + - `downloadRequest` {{optional_inline}} + - : The filename of the file requested for download, in the case of a download navigation (e.g. an {{htmlelement("a")}} or {{htmlelement("area")}} element with a `download` attribute). Defaults to `null`. + - `formData` {{optional_inline}} + - : The {{domxref("FormData")}} object representing the submitted data in the case of a `POST` form submission. Defaults to `null`. + - `hashChange` {{optional_inline}} + - : A boolean defining if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document). Defaults to `false`. + - `info` {{optional_inline}} + - : The `info` data value passed by the initiating navigation operation (e.g. {{domxref("Navigation.back()")}}, or {{domxref("Navigation.navigate()")}}). + - `navigationType` {{optional_inline}} + - : The type of the navigation. Possible values — `push`, `reload`, `replace`, and `traverse`. Defaults to `push`. + - `signal` + - : An {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one). + - `userInitiated` {{optional_inline}} + - : A boolean defining whether the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons). Defaults to `false`. + +## Examples + +A developer would not use this constructor manually. A new `NavigateEvent` object is constructed when a handler is invoked as a result of the {{domxref("Navigation.navigate_event", "navigate")}} event firing. + +```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); + }, + }); + } +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/navigationtype/index.md b/files/en-us/web/api/navigateevent/navigationtype/index.md new file mode 100644 index 000000000000000..7e0685f7a6c9b8e --- /dev/null +++ b/files/en-us/web/api/navigateevent/navigationtype/index.md @@ -0,0 +1,87 @@ +--- +title: NavigateEvent.navigationType +slug: Web/API/NavigateEvent/navigationType +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - navigationType + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigateEvent.navigationType +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`navigationType`** read-only property of the +{{domxref("NavigateEvent")}} interface returns the type of the navigation — `push`, `reload`, `replace`, or `traverse`. + +## Value + +An enumerated value representing the type of navigation. + +The possible values are: + +- `push`: A new location is navigated to, causing a new entry to be pushed onto the history list. +- `reload`: The {{domxref("Navigation.currentEntry")}} is reloaded. +- `replace`: The {{domxref("Navigation.currentEntry")}} is replaced with a new history entry. This new entry will reuse the same {{domxref("NavigationHistoryEntry.key", "key")}}, but be assigned a different {{domxref("NavigationHistoryEntry.id", "id")}}. +- `traverse`: The browser navigates from one existing history entry to another existing history entry. + +## Examples + +### Async transitions with special back/forward handling + +Sometimes it's desirable to handle back/forward navigations specially, e.g. reusing cached views by transitioning them onto the screen. This can be done by branching as follows: + +```js +navigation.addEventListener("navigate", event => { + // Some navigations, e.g. cross-origin navigations, we + // cannot intercept. Let the browser handle those normally. + if (!event.canIntercept) { + return; + } + + // Don't intercept fragment navigations or downloads. + if (event.hashChange || event.downloadRequest !== null) { + return; + } + + event.intercept({ async handler() { + if (myFramework.currentPage) { + await myFramework.currentPage.transitionOut(); + } + + let { key } = event.destination; + + if (event.navigationType === "traverse" && myFramework.previousPages.has(key)) { + await myFramework.previousPages.get(key).transitionIn(); + } else { + // This will probably result in myFramework storing + // the rendered page in myFramework.previousPages. + await myFramework.renderPage(event.destination); + } + } }); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/scroll/index.md b/files/en-us/web/api/navigateevent/scroll/index.md new file mode 100644 index 000000000000000..a0369b076f7d566 --- /dev/null +++ b/files/en-us/web/api/navigateevent/scroll/index.md @@ -0,0 +1,80 @@ +--- +title: NavigateEvent.scroll() +slug: Web/API/NavigateEvent/scroll +page-type: web-api-instance-method +tags: + - API + - Experimental + - History + - Method + - NavigateEvent + - Navigation + - Navigation API + - Reference + - Scroll + - transition + - Traversal +browser-compat: api.NavigateEvent.scroll +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`scroll()`** method of the +{{domxref("NavigateEvent")}} interface can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed. + +## Syntax + +```js-nolint +scroll() +``` + +### Parameters + +None. + +### Return value + +`undefined`. + +### Exceptions + +- `InvalidStateError` {{domxref("DOMException")}} + - : Thrown if the current {{domxref("Document")}} is not yet active, if the navigation was not intercepted using {{domxref("NavigateEvent.intercept", "intercept()")}}, or if the default scroll behavior has already ocurred. + +## Examples + +### Handling scrolling using `scroll()` + +```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 + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/signal/index.md b/files/en-us/web/api/navigateevent/signal/index.md new file mode 100644 index 000000000000000..58b430eef74ab13 --- /dev/null +++ b/files/en-us/web/api/navigateevent/signal/index.md @@ -0,0 +1,63 @@ +--- +title: NavigateEvent.signal +slug: Web/API/NavigateEvent/signal +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - signal + - Traversal +browser-compat: api.NavigateEvent.signal +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`signal`** read-only property of the +{{domxref("NavigateEvent")}} interface returns an {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one). + +## Value + +An {{domxref("AbortSignal")}} object. + +## Examples + +The general idea here is that the `signal` property can be passed to an associated {{domxref("fetch()")}} operation so that if the navigation is cancelled, it can be safely aborted, avoiding wasting bandwidth on fetches that are no longer needed. + +```js +navigation.addEventListener("navigate", event => { + event.intercept({ async handler() { + + ... + + await fetch(`/img/some-image.jpg`, { signal: event.signal }); + + ... + + } }); +}); +``` + +> **Note:** See [Example: next/previous buttons](https://github.com/WICG/navigation-api#example-nextprevious-buttons) for a more detailed example. + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigateevent/userinitiated/index.md b/files/en-us/web/api/navigateevent/userinitiated/index.md new file mode 100644 index 000000000000000..8b5a71e9e1d9642 --- /dev/null +++ b/files/en-us/web/api/navigateevent/userinitiated/index.md @@ -0,0 +1,53 @@ +--- +title: NavigateEvent.userInitiated +slug: Web/API/NavigateEvent/userInitiated +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - NavigateEvent + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal + - userInitiated +browser-compat: api.NavigateEvent.userInitiated +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`userInitiated`** read-only property of the +{{domxref("NavigateEvent")}} interface returns `true` if the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons), or `false` otherwise. + +> **Note:** The table found at [Appendix: types of navigations](https://github.com/WICG/navigation-api#appendix-types-of-navigations) shows which navigation types are user-initiated. + +## Value + +A boolean value—`true` if the navigation is user-initiated, `false` if not. + +## Examples + +```js +navigation.addEventListener("navigate", event => { + console.log(event.userInitiated); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigation/navigate_event/index.md b/files/en-us/web/api/navigation/navigate_event/index.md index 654192aeb4132db..9b4e0392c37fa42 100644 --- a/files/en-us/web/api/navigation/navigate_event/index.md +++ b/files/en-us/web/api/navigation/navigate_event/index.md @@ -39,15 +39,15 @@ onnavigate = (event) => {}; ### Handling a navigation using `intercept()` ```js -navigation.addEventListener('navigate', navigateEvent => { +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(navigateEvent)) return; + if (shouldNotIntercept(event)) return; - const url = new URL(navigateEvent.destination.url); + const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { - navigateEvent.intercept({ + 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 @@ -67,16 +67,16 @@ navigation.addEventListener('navigate', navigateEvent => { ### Handling scrolling using `scroll()` ```js -navigation.addEventListener('navigate', navigateEvent => { +navigation.addEventListener('navigate', event => { if (shouldNotIntercept(navigateEvent)) return; - const url = new URL(navigateEvent.destination.url); + const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { - navigateEvent.intercept({ + event.intercept({ async handler() { const articleContent = await getArticleContent(url.pathname); renderArticlePage(articleContent); - navigateEvent.scroll(); + event.scroll(); const secondaryContent = await getSecondaryContent(url.pathname); addSecondaryContent(secondaryContent); diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 9b2868b57e87ded..cc4781eba07234e 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -110,15 +110,15 @@ There are a few perceived limitations with the Navigation API, which may or may ### Handling a navigation using `intercept()` ```js -navigation.addEventListener('navigate', navigateEvent => { +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(navigateEvent)) return; + if (shouldNotIntercept(event)) return; - const url = new URL(navigateEvent.destination.url); + const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { - navigateEvent.intercept({ + 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 @@ -136,16 +136,16 @@ navigation.addEventListener('navigate', navigateEvent => { ### Handling scrolling using `scroll()` ```js -navigation.addEventListener('navigate', navigateEvent => { - if (shouldNotIntercept(navigateEvent)) return; - const url = new URL(navigateEvent.destination.url); +navigation.addEventListener('navigate', event => { + if (shouldNotIntercept(event)) return; + const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { - navigateEvent.intercept({ + event.intercept({ async handler() { const articleContent = await getArticleContent(url.pathname); renderArticlePage(articleContent); - navigateEvent.scroll(); + event.scroll(); const secondaryContent = await getSecondaryContent(url.pathname); addSecondaryContent(secondaryContent); diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/from/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/from/index.md new file mode 100644 index 000000000000000..701b945f109ca9a --- /dev/null +++ b/files/en-us/web/api/navigationcurrententrychangeevent/from/index.md @@ -0,0 +1,50 @@ +--- +title: NavigationCurrentEntryChangeEvent.from +slug: Web/API/NavigationCurrentEntryChangeEvent/from +page-type: web-api-instance-property +tags: + - API + - Experimental + - from + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationCurrentEntryChangeEvent.from +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`from`** read-only property of the +{{domxref("NavigationCurrentEntryChangeEvent")}} interface returns the {{domxref("NavigationHistoryEntry")}} that was navigated from. + +## Value + +A {{domxref("NavigationHistoryEntry")}} object. + +## Examples + +```js +navigation.addEventListener("currententrychange", event => { + console.log(event.from); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md new file mode 100644 index 000000000000000..ce78c40116ada0a --- /dev/null +++ b/files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md @@ -0,0 +1,63 @@ +--- +title: NavigationCurrentEntryChangeEvent() +slug: Web/API/NavigationCurrentEntryChangeEvent/NavigationCurrentEntryChangeEvent +page-type: web-api-constructor +tags: + - API + - Constructor + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationCurrentEntryChangeEvent.NavigationCurrentEntryChangeEvent +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`NavigationCurrentEntryChangeEvent()`** constructor creates a new +{{domxref("NavigationCurrentEntryChangeEvent")}} object. + +## Syntax + +```js-nolint +new NavigationCurrentEntryChangeEvent(type, init) +``` + +### Parameters + +- `type` + - : A string representing the type of event. In the case of `NavigationCurrentEntryChangeEvent` this is always `event`. +- `init` + - : An object containing the following properties: + - `destination` + - : A {{domxref("NavigationHistoryEntry")}} object representing the location being navigated to. + - `navigationType` + - : The type of the navigation that resulted in the change. Possible values — `push`, `reload`, `replace`, and `traverse`. + +## Examples + +A developer would not use this constructor manually. A new `NavigationCurrentEntryChangeEvent` object is constructed when a handler is invoked as a result of the {{domxref("Navigation.currententrychange_event", "currententrychange")}} event firing. + +```js +navigation.addEventListener("currententrychange", event => { + console.log(event.navigationType); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md new file mode 100644 index 000000000000000..eeab118e8a9f413 --- /dev/null +++ b/files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md @@ -0,0 +1,57 @@ +--- +title: NavigationCurrentEntryChangeEvent.navigationType +slug: Web/API/NavigationCurrentEntryChangeEvent/navigationType +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - navigationType + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationCurrentEntryChangeEvent.navigationType +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`navigationType`** read-only property of the +{{domxref("NavigationCurrentEntryChangeEvent")}} interface returns the type of the navigation that resulted in the change. + +## Value + +An enumerated value representing the type of navigation. + +The possible values are: + +- `push`: A new location is navigated to, causing a new entry to be pushed onto the history list. +- `reload`: The {{domxref("Navigation.currentEntry")}} is reloaded. +- `replace`: The {{domxref("Navigation.currentEntry")}} is replaced with a new history entry. This new entry will reuse the same {{domxref("NavigationHistoryEntry.key", "key")}}, but be assigned a different {{domxref("NavigationHistoryEntry.id", "id")}}. +- `traverse`: The browser navigates from one existing history entry to another existing history entry. + +## Examples + +```js +navigation.addEventListener("currententrychange", event => { + console.log(event.navigationType); +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationdestination/getstate/index.md b/files/en-us/web/api/navigationdestination/getstate/index.md index 105d340ba94d378..a4cdeeab70c952e 100644 --- a/files/en-us/web/api/navigationdestination/getstate/index.md +++ b/files/en-us/web/api/navigationdestination/getstate/index.md @@ -46,8 +46,8 @@ None. ## Examples ```js -navigation.addEventListener('navigate', navigateEvent => { - console.log(navigateEvent.destination.getState()); +navigation.addEventListener('navigate', event => { + console.log(event.destination.getState()); }); ``` diff --git a/files/en-us/web/api/navigationdestination/id/index.md b/files/en-us/web/api/navigationdestination/id/index.md index 14ff12867883536..2b5469c3339af3f 100644 --- a/files/en-us/web/api/navigationdestination/id/index.md +++ b/files/en-us/web/api/navigationdestination/id/index.md @@ -32,8 +32,8 @@ A string representing the `id` of the destination {{domxref("NavigationHistoryEn ## Examples ```js -navigation.addEventListener('navigate', navigateEvent => { - console.log(navigateEvent.destination.id); +navigation.addEventListener('navigate', event => { + console.log(event.destination.id); }); ``` diff --git a/files/en-us/web/api/navigationdestination/index.md b/files/en-us/web/api/navigationdestination/index.md index 04eb392d6c0e998..875f89fee2fc895 100644 --- a/files/en-us/web/api/navigationdestination/index.md +++ b/files/en-us/web/api/navigationdestination/index.md @@ -46,17 +46,17 @@ It is accessed via the {{domxref("NavigateEvent.destination")}} property. ## Examples ```js -navigation.addEventListener('navigate', navigateEvent => { +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(navigateEvent)) return; + if (shouldNotIntercept(event)) return; // Returns a URL() object constructed from the // NavigationDestination.url value - const url = new URL(navigateEvent.destination.url); + const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { - navigateEvent.intercept({ + 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 diff --git a/files/en-us/web/api/navigationdestination/index/index.md b/files/en-us/web/api/navigationdestination/index/index.md index 599e18916c8c7a9..e2c9cb8cce11fbc 100644 --- a/files/en-us/web/api/navigationdestination/index/index.md +++ b/files/en-us/web/api/navigationdestination/index/index.md @@ -30,8 +30,8 @@ A number representing the `index` of the destination {{domxref("NavigationHistor ## Examples ```js -navigation.addEventListener('navigate', navigateEvent => { - console.log(navigateEvent.destination.index); +navigation.addEventListener('navigate', event => { + console.log(event.destination.index); }); ``` diff --git a/files/en-us/web/api/navigationdestination/key/index.md b/files/en-us/web/api/navigationdestination/key/index.md index 99b2c15a952f473..6d14c893b78b6aa 100644 --- a/files/en-us/web/api/navigationdestination/key/index.md +++ b/files/en-us/web/api/navigationdestination/key/index.md @@ -32,8 +32,8 @@ A string representing the `key` of the destination {{domxref("NavigationHistoryE ## Examples ```js -navigation.addEventListener('navigate', navigateEvent => { - console.log(navigateEvent.destination.key); +navigation.addEventListener('navigate', event => { + console.log(event.destination.key); }); ``` diff --git a/files/en-us/web/api/navigationdestination/samedocument/index.md b/files/en-us/web/api/navigationdestination/samedocument/index.md index c02a746bc15911e..90c2e9d1991cbd5 100644 --- a/files/en-us/web/api/navigationdestination/samedocument/index.md +++ b/files/en-us/web/api/navigationdestination/samedocument/index.md @@ -32,8 +32,8 @@ A boolean. ## Examples ```js -navigation.addEventListener('navigate', navigateEvent => { - console.log(navigateEvent.destination.sameDocument); +navigation.addEventListener('navigate', event => { + console.log(event.destination.sameDocument); }); ``` diff --git a/files/en-us/web/api/navigationdestination/url/index.md b/files/en-us/web/api/navigationdestination/url/index.md index 95f59facdbc0e08..535be31e24551fe 100644 --- a/files/en-us/web/api/navigationdestination/url/index.md +++ b/files/en-us/web/api/navigationdestination/url/index.md @@ -32,15 +32,15 @@ A string. ### Handling a navigation using `intercept()` ```js -navigation.addEventListener('navigate', navigateEvent => { +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(navigateEvent)) return; + if (shouldNotIntercept(event)) return; - const url = new URL(navigateEvent.destination.url); + const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { - navigateEvent.intercept({ + 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 diff --git a/files/en-us/web/api/navigationtransition/finished/index.md b/files/en-us/web/api/navigationtransition/finished/index.md new file mode 100644 index 000000000000000..8f35b1f2bac5181 --- /dev/null +++ b/files/en-us/web/api/navigationtransition/finished/index.md @@ -0,0 +1,50 @@ +--- +title: NavigationTransition.finished +slug: Web/API/NavigationTransition/finished +page-type: web-api-instance-property +tags: + - API + - Experimental + - finished + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationTransition.finished +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`finished`** read-only property of the +{{domxref("NavigationTransition")}} interface returns a {{jsxref("Promise")}} that fulfills at the same time the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, or rejects at the same time the {{domxref("Navigation/navigateerror_event", "navigateerror")}} event fires. + +## Value + +A {{jsxref("Promise")}} that resolves to `undefined`. + +## Examples + +```js +await navigation.transition.finished; +// Navigation has completed successfully +// Cleanup any ongoing monitoring +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationtransition/from/index.md b/files/en-us/web/api/navigationtransition/from/index.md new file mode 100644 index 000000000000000..2198a9ec993d6f7 --- /dev/null +++ b/files/en-us/web/api/navigationtransition/from/index.md @@ -0,0 +1,48 @@ +--- +title: NavigationTransition.from +slug: Web/API/NavigationTransition/from +page-type: web-api-instance-property +tags: + - API + - Experimental + - from + - History + - Navigate + - Navigation + - Navigation API + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationTransition.from +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`from`** read-only property of the +{{domxref("NavigationTransition")}} interface returns the {{domxref("NavigationHistoryEntry")}} that the transition is coming from. + +## Value + +A {{domxref("NavigationHistoryEntry")}} object. + +## Examples + +```js +console.log(navigation.transition.from); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) diff --git a/files/en-us/web/api/navigationtransition/index.md b/files/en-us/web/api/navigationtransition/index.md index c54b36f3bf3f284..95e8243a68855f1 100644 --- a/files/en-us/web/api/navigationtransition/index.md +++ b/files/en-us/web/api/navigationtransition/index.md @@ -27,12 +27,12 @@ It is accessed via the {{domxref("Navigation.transition")}} property. ## Instance properties -- {{domxref("NavigationTransition.navigationType", "navigationType")}} {{ReadOnlyInline}} - - : Returns the type of the ongoing navigation. -- {{domxref("NavigationTransition.from", "from")}} {{ReadOnlyInline}} - - : Returns the {{domxref("NavigationHistoryEntry")}} that the transition is coming from. - {{domxref("NavigationTransition.finished", "finished")}} {{ReadOnlyInline}} - : Returns a {{jsxref("Promise")}} that fulfills at the same time the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, or rejects at the same time the {{domxref("Navigation/navigateerror_event", "navigateerror")}} event fires. +- {{domxref("NavigationTransition.from", "from")}} {{ReadOnlyInline}} + - : Returns the {{domxref("NavigationHistoryEntry")}} that the transition is coming from. +- {{domxref("NavigationTransition.navigationType", "navigationType")}} {{ReadOnlyInline}} + - : Returns the type of the ongoing navigation. ## Examples diff --git a/files/en-us/web/api/navigationtransition/navigationtype/index.md b/files/en-us/web/api/navigationtransition/navigationtype/index.md new file mode 100644 index 000000000000000..c9257240dcb4463 --- /dev/null +++ b/files/en-us/web/api/navigationtransition/navigationtype/index.md @@ -0,0 +1,55 @@ +--- +title: NavigationTransition.navigationType +slug: Web/API/NavigationTransition/navigationType +page-type: web-api-instance-property +tags: + - API + - Experimental + - History + - Navigate + - Navigation + - Navigation API + - navigationType + - Property + - Read-only + - Reference + - Scroll + - Traversal +browser-compat: api.NavigationTransition.navigationType +--- + +{{APIRef("Navigation API")}}{{seecompattable}} + +The **`navigationType`** read-only property of the +{{domxref("NavigationTransition")}} interface returns the type of the ongoing navigation. + +## Value + +An enumerated value representing the type of ongoing navigation. + +The possible values are: + +- `push`: A new location is navigated to, causing a new entry to be pushed onto the history list. +- `reload`: The {{domxref("Navigation.currentEntry")}} is reloaded. +- `replace`: The {{domxref("Navigation.currentEntry")}} is replaced with a new history entry. This new entry will reuse the same {{domxref("NavigationHistoryEntry.key", "key")}}, but be assigned a different {{domxref("NavigationHistoryEntry.id", "id")}}. +- `traverse`: The browser navigates from one existing history entry to another existing history entry. + +## Examples + +```js +console.log(navigation.transition.navigationType); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) +- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) +- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) From 1e96c03f99eedfcc953c698166dea32a06914f6d Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 8 Nov 2022 07:22:42 +0000 Subject: [PATCH 14/50] adding description of when disposal occurs --- .../web/api/navigationhistoryentry/dispose_event/index.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md b/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md index 061963981e7bb34..1e44e9ce7e4f622 100644 --- a/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md +++ b/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md @@ -24,6 +24,12 @@ browser-compat: api.NavigationHistoryEntry.dispose_event The **`dispose`** event of the {{domxref("NavigationHistoryEntry")}} interface is fired when the entry is no longer part of the history entry list. +Disposal occurs when: + +- Forward history entries are cleared. See the example at [Notifications on entry disposal](https://github.com/wicg/navigation-api#notifications-on-entry-disposal) for more information. +- The user clears their browser history using settings or provided UI controls. +- The 50-page history limit is exceeded. This is not specified anywhere, but it is widely implemented. See the discussion in [How to Manipulate history.length and set it to more than 50](https://stackoverflow.com/questions/25275418/how-to-manipulate-history-length-and-set-it-to-more-than-50). + ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. From de7f600aaf5e1cb8f15661b08292d0cf773e64c5 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:34:59 +0000 Subject: [PATCH 15/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index cc4781eba07234e..9098d9e5e9bd3e9 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -22,7 +22,7 @@ browser-compat: {{seecompattable}}{{DefaultAPISidebar("Navigation API")}} -The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also introspect an application's history entries. This is a successor to previous web platform features such as [The History API](/en-US/docs/Web/API/History_API) and {{domxref("window.location")}}, which solves their shortcomings and is specifically aimed at the needs of {{glossary("SPA", "single-page applications (SPAs)")}}. +The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also examine an application's history entries. This is a successor to previous web platform features such as the [History API](/en-US/docs/Web/API/History_API) and {{domxref("window.location")}}, which solves their shortcomings and is specifically aimed at the needs of {{glossary("SPA", "single-page applications (SPAs)")}}. ## Concepts and Usage From 43f9c1f7034e7d22967a61131c4832a51470a4e4 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:35:09 +0000 Subject: [PATCH 16/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 9098d9e5e9bd3e9..eec39620cc0d9b0 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -24,7 +24,7 @@ browser-compat: The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also examine an application's history entries. This is a successor to previous web platform features such as the [History API](/en-US/docs/Web/API/History_API) and {{domxref("window.location")}}, which solves their shortcomings and is specifically aimed at the needs of {{glossary("SPA", "single-page applications (SPAs)")}}. -## Concepts and Usage +## Concepts and usage In SPAs, the page template tends to stay the same during usage, and the content is dynamically rewritten as the user visits different pages or features. As a result, only one distinct page is loaded in the browser, which breaks the expected user experience of navigating back and forth between different locations in the viewing history. This problem can be solved to a degree via [The History API](/en-US/docs/Web/API/History_API), but it is not designed for the needs of SPAs. The Navigation API aims to bridge that gap. From f3e94dbc958159b60f81018e1ffaac96011338db Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:35:33 +0000 Subject: [PATCH 17/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index eec39620cc0d9b0..621ca63fab3bb88 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -26,7 +26,7 @@ The **Navigation API** provides the ability to initiate, intercept, and manage b ## Concepts and usage -In SPAs, the page template tends to stay the same during usage, and the content is dynamically rewritten as the user visits different pages or features. As a result, only one distinct page is loaded in the browser, which breaks the expected user experience of navigating back and forth between different locations in the viewing history. This problem can be solved to a degree via [The History API](/en-US/docs/Web/API/History_API), but it is not designed for the needs of SPAs. The Navigation API aims to bridge that gap. +In SPAs, the page template tends to stay the same during usage, and the content is dynamically rewritten as the user visits different pages or features. As a result, only one distinct page is loaded in the browser, which breaks the expected user experience of navigating back and forth between different locations in the viewing history. This problem can be solved to a degree via the [History API](/en-US/docs/Web/API/History_API), but it is not designed for the needs of SPAs. The Navigation API aims to bridge that gap. The API is accessed via the {{domxref("Window.navigation")}} property, which returns a reference to a global {{domxref("Navigation")}} object. Each `window` object has its own corresponding `navigation` instance. From 5a47f9eb478405219fb14ef6aac37c4c2fdfef6c Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:36:05 +0000 Subject: [PATCH 18/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 621ca63fab3bb88..4d4fb1cd38d8947 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -34,7 +34,7 @@ The API is accessed via the {{domxref("Window.navigation")}} property, which ret `navigation` has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the {{domxref("History API")}}, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event has an event object of type {{domxref("NavigateEvent")}}, which contains detailed information including details around the navigation's destination, type, whether it contains `POST` form data or a download request, and more. -It also contains two methods: +The `NavigationEvent` object also provides two methods: - {{domxref("NavigateEvent.intercept", "intercept()")}} allows you to control what happens when the navigation is initiated using a callback handler function, which should return a promise. For example, in the case of an SPA, it can be used to load relevant new content into the UI based on the path of the URL navigated to. - {{domxref("NavigateEvent.scroll", "scroll()")}} allows you to manually initiate the browser's scroll behavior (e.g. to a fragment identifier in the URL), if it makes sense for your code, rather than waiting for the browser to handle it automatically. From b4a42f31183aee91fe00d04503fc43784543628c Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:37:33 +0000 Subject: [PATCH 19/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 4d4fb1cd38d8947..0db49bccacc7dc5 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -32,7 +32,7 @@ The API is accessed via the {{domxref("Window.navigation")}} property, which ret ### Handling navigations -`navigation` has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the {{domxref("History API")}}, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event has an event object of type {{domxref("NavigateEvent")}}, which contains detailed information including details around the navigation's destination, type, whether it contains `POST` form data or a download request, and more. +The `navigation` interface has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the {{domxref("History API")}}, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event handler is passed a {{domxref("NavigateEvent")}} object, which contains detailed information including details around the navigation's destination, type, whether it contains `POST` form data or a download request, and more. The `NavigationEvent` object also provides two methods: From 40f93b0f2cb3bd517b1f5a3655096bda6be72f3f Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:39:01 +0000 Subject: [PATCH 20/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 0db49bccacc7dc5..e793fb2358aaf0a 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -45,7 +45,7 @@ Once a navigation is initiated, and your `intercept()` handler is called, a {{do > **Note:** You can also call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely in most cases. This works today for most push, reload, and replace navigations; cancellation of traverse navigations is not yet implemented. -When the `intercept()` handler function's promise fulfills, the `Navigate` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases if it is needed. +When the `intercept()` handler function's promise fulfills, the `Navigation` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases. > **Note:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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. From dc435dac014a1033535c6cb67ca9f72df4f58444 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:39:36 +0000 Subject: [PATCH 21/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index e793fb2358aaf0a..864746879a23c02 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -47,7 +47,7 @@ Once a navigation is initiated, and your `intercept()` handler is called, a {{do When the `intercept()` handler function's promise fulfills, the `Navigation` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases. -> **Note:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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. +> **Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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. ### Programmatically updating and traversing the navigation history From 12a51d25c719769685ac2a8cf766548f50ccede0 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:41:00 +0000 Subject: [PATCH 22/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 864746879a23c02..0eb4ee267bd7f10 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -77,7 +77,7 @@ To get a {{domxref("NavigationHistoryEntry")}}'s state, you call its {{domxref(" Setting state is a bit more nuanced. You can't retrieve the state value and then update it directly — the copy stored on the entry will not change. Instead, you update it while performing a {{domxref("Navigation.navigate", "navigate()")}} or {{domxref("Navigation.reload", "reload()")}} — each one of these optionally takes an options object parameter, which includes a `state` property containing the new state to set on the history entry. When these navigations commit, the state change will be automatically applied. -In some cases however, a state change will be independent from a navigation or reload — for example when a page contains an expandable/collapsible {{htmlelement("details")}} element. In this case, you might want to store the expanded/collapsed state in your history entry, so you can restore it when the user returns to the page or restarts their browser. Cases like this are handled using {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}. The {{domxref("Navigation/currententrychange_event", "currententrychange")}} will fire when the current entry change is complete. +In some cases however, a state change will be independent from a navigation or reload — for example when a page contains an expandable/collapsible {{htmlelement("details")}} element. In this case, you might want to store the expanded/collapsed state in your history entry, so you can restore it when the user returns to the page or restarts their browser. Cases like this are handled using {{domxref("Navigation.updateCurrentEntry()")}}. The {{domxref("Navigation/currententrychange_event", "currententrychange")}} will fire when the current entry change is complete. ### Limitations From 33a7e8e931b9fe2723f5f9c3f3df2f3a93f1a42f Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 07:59:52 +0000 Subject: [PATCH 23/50] Update files/en-us/web/api/navigation_api/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation_api/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 0eb4ee267bd7f10..752e88394b41e52 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -51,7 +51,7 @@ When the `intercept()` handler function's promise fulfills, the `Navigation` obj ### Programmatically updating and traversing the navigation history -As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct {{domxref("NavigationHistoryEntry")}} object instance. These contain several useful properties such as the entry's key, URL, and state information. You can return the entry that the user is currently navigated to right now using {{domxref("Navigation.currentEntry","currentEntry")}}, and an array of all existing history entries using {{domxref("Navigation.entries", "entries()")}}. Each `NavigationHistoryEntry` object has a {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} event, which fires when the entry is no longer part of the browser history (e.g. navigate back three times, then navigate forwards to somewhere else. Those three history entries will be disposed). +As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct {{domxref("NavigationHistoryEntry")}} object instance. These contain several properties such as the entry's key, URL, and state information. You can get the entry that the user is currently on right now using {{domxref("Navigation.currentEntry")}}, and an array of all existing history entries using {{domxref("Navigation.entries()")}}. Each `NavigationHistoryEntry` object has a {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} event, which fires when the entry is no longer part of the browser history. For example, if the user navigates back three times, then navigates forward to somewhere else, those three history entries will be disposed of). > **Note:** The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. From 5938b370d4c410c9ecaa849b3741506d39bcb874 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 08:00:48 +0000 Subject: [PATCH 24/50] adding fixes for wbamberg comments --- files/en-us/web/api/navigation_api/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 0eb4ee267bd7f10..c1293c3689907f4 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -36,14 +36,14 @@ The `navigation` interface has several associated events, the most notable being The `NavigationEvent` object also provides two methods: -- {{domxref("NavigateEvent.intercept", "intercept()")}} allows you to control what happens when the navigation is initiated using a callback handler function, which should return a promise. For example, in the case of an SPA, it can be used to load relevant new content into the UI based on the path of the URL navigated to. +- {{domxref("NavigateEvent.intercept", "intercept()")}} takes as an argument a callback handler function returning a promise. It allows you to control what happens when the navigation is initiated. For example, in the case of an SPA, it can be used to load relevant new content into the UI based on the path of the URL navigated to. - {{domxref("NavigateEvent.scroll", "scroll()")}} allows you to manually initiate the browser's scroll behavior (e.g. to a fragment identifier in the URL), if it makes sense for your code, rather than waiting for the browser to handle it automatically. Once a navigation is initiated, and your `intercept()` handler is called, a {{domxref("NavigationTransition")}} object instance is created (accessible via {{domxref("Navigation.transition")}}), which can be used used to track the process of the ongoing navigation. > **Note:** In this context "transition" refers to the transition between one history entry and another. It isn't related to CSS transitions. -> **Note:** You can also call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely in most cases. This works today for most push, reload, and replace navigations; cancellation of traverse navigations is not yet implemented. +> **Note:** You can also call {{domxref("Event.preventDefault", "preventDefault()")}} to stop the navigation entirely for most [navigation types](/en-US/docs/Web/API/NavigateEvent/navigationType#value); cancellation of traverse navigations is not yet implemented. When the `intercept()` handler function's promise fulfills, the `Navigation` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case. There is also a {{domxref("NavigationTransition.finished", "finished")}} property on the `NavigationTransition` object, which fullfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases. From 6333b97e973d97aa262b89965698ab01b6922b62 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 9 Nov 2022 08:59:46 +0000 Subject: [PATCH 25/50] adding fixes for wbamberg comments --- files/en-us/web/api/navigation_api/index.md | 15 +++++++++------ files/jsondata/GroupData.json | 13 ------------- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 17c93d110903820..15b0313b83b03e3 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -17,7 +17,6 @@ tags: browser-compat: - api.Navigation - api.NavigateEvent - - api.Window.navigation --- {{seecompattable}}{{DefaultAPISidebar("Navigation API")}} @@ -51,9 +50,9 @@ When the `intercept()` handler function's promise fulfills, the `Navigation` obj ### Programmatically updating and traversing the navigation history -As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct {{domxref("NavigationHistoryEntry")}} object instance. These contain several properties such as the entry's key, URL, and state information. You can get the entry that the user is currently on right now using {{domxref("Navigation.currentEntry")}}, and an array of all existing history entries using {{domxref("Navigation.entries()")}}. Each `NavigationHistoryEntry` object has a {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} event, which fires when the entry is no longer part of the browser history. For example, if the user navigates back three times, then navigates forward to somewhere else, those three history entries will be disposed of). +As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct {{domxref("NavigationHistoryEntry")}} object instance. These contain several properties such as the entry's key, URL, and state information. You can get the entry that the user is currently on right now using {{domxref("Navigation.currentEntry")}}, and an array of all existing history entries using {{domxref("Navigation.entries()")}}. Each `NavigationHistoryEntry` object has a {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} event, which fires when the entry is no longer part of the browser history. For example, if the user navigates back three times, then navigates forward to somewhere else, those three history entries will be disposed of. -> **Note:** The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. +> **Note:** The Navigation API only exposes history entries created directly by the application's top-level context (e.g. not navigations inside embedded {{htmlelement("iframe")}}s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. The `Navigation` object contains all the methods you'll need to update and traverse through the navigation history: @@ -81,12 +80,16 @@ In some cases however, a state change will be independent from a navigation or r ### Limitations -There are a few perceived limitations with the Navigation API, which may or may not be limiting depending on how your app is set up. Find out about these by reading [Modern client-side routing: the Navigation API > What's missing?](https://developer.chrome.com/docs/web-platform/navigation-api/#whats-missing) +There are a few perceived limitations with the Navigation API: + +1. The current specification doesn't trigger {{domxref("Navigation.navigate_event", "navigate")}} on a page's first load. This might be fine for sites that use Server Side Rendering (SSR)—your server could return the correct initial state, which is the fastest way to get content to your users. But sites that leverage client-side code to create their pages may need an additional function to initialize the page. +2. The Navigation API operates only within a single frame—the top-level page, or a single specific {{htmlelement("iframe")}}. This has some interesting implications that are [further documented in the spec](https://github.com/WICG/navigation-api#warning-backforward-are-not-always-opposites), but in practice, will reduce developer confusion. The previous History API has several confusing edge cases, like support for frames, which the Navigation API handles up-front. +3. You can't currently use the Navigation API to programmatically modify or rearrange the history list. It might be useful to have a temporary state, for example navigating the user to a temporary modal that asks them for some information, then going back to the previous URL. In this case, you'd want to delete the temporary modal navigation entry so the user cannot mess up the application flow by hitting the forward button and opening it again. ## Interfaces - {{domxref("Navigation")}} - - : Allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, introspecting navigation history entries, and managing navigations as they happen. + - : Allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, examining navigation history entries, and managing navigations as they happen. - {{domxref("NavigationDestination")}} - : Represents the destination being navigated to in the current navigation. - {{domxref("NavigationHistoryEntry")}} @@ -98,7 +101,7 @@ There are a few perceived limitations with the Navigation API, which may or may - {{domxref("NavigateEvent")}} - : Event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated. It provides access to information about that navigation, and most notably the {{domxref("NavigateEvent.intercept", "intercept()")}}, which allows you to control what happens when the navigation is initiated. -## Extensions to the `Window` interface +## Extensions to other interfaces - {{domxref("Window.navigation")}} - : Returns the current `window`'s associated {{domxref("Navigation")}} object. Entry point for the API. diff --git a/files/jsondata/GroupData.json b/files/jsondata/GroupData.json index cc5657cf8d6d79a..0b74cb971b85c03 100644 --- a/files/jsondata/GroupData.json +++ b/files/jsondata/GroupData.json @@ -859,19 +859,6 @@ "properties": ["Window.navigation"], "events": [] }, - "Navigation Timing": { - "overview": ["Navigation timing API"], - "guides": ["/docs/Web/API/Navigation_timing_API/Using_Navigation_Timing"], - "interfaces": [ - "Performance", - "PerformanceNavigation", - "PerformanceTiming", - "PerformanceNavigationTiming" - ], - "methods": [], - "properties": ["performance_property"], - "events": [] - }, "Network Information API": { "overview": ["Network Information API"], "interfaces": ["NetworkInformation"], From 8725f8e4d6ffe035e612351881a2c6cceafed1a9 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:23:40 +0000 Subject: [PATCH 26/50] making fixes for wbamberg comments --- .../api/navigateevent/destination/index.md | 6 +- .../navigateevent/downloadrequest/index.md | 2 +- .../web/api/navigateevent/formdata/index.md | 2 +- .../web/api/navigateevent/hashchange/index.md | 2 +- files/en-us/web/api/navigateevent/index.md | 2 +- .../en-us/web/api/navigateevent/info/index.md | 2 +- .../web/api/navigateevent/intercept/index.md | 4 +- .../api/navigateevent/navigateevent/index.md | 6 +- .../api/navigateevent/navigationtype/index.md | 2 +- .../web/api/navigateevent/scroll/index.md | 6 +- .../web/api/navigateevent/signal/index.md | 6 +- .../api/navigateevent/userinitiated/index.md | 2 +- files/en-us/web/api/navigation/back/index.md | 30 +++++----- .../web/api/navigation/cangoback/index.md | 30 +++++----- .../web/api/navigation/cangoforward/index.md | 30 +++++----- .../web/api/navigation/currententry/index.md | 18 +++--- .../currententrychange_event/index.md | 8 ++- .../en-us/web/api/navigation/forward/index.md | 30 +++++----- files/en-us/web/api/navigation/index.md | 58 ++++++++++--------- .../web/api/navigation/navigate/index.md | 22 ++++--- .../api/navigation/navigate_event/index.md | 20 +++++-- .../navigation/navigateerror_event/index.md | 10 +++- .../navigation/navigatesuccess_event/index.md | 10 ++-- .../en-us/web/api/navigation/reload/index.md | 12 +++- .../web/api/navigation/transition/index.md | 12 ++-- .../web/api/navigation/traverseto/index.md | 18 +++--- files/en-us/web/api/navigation_api/index.md | 30 +++++----- .../from/index.md | 2 +- .../index.md | 4 +- .../index.md | 2 +- .../navigationtype/index.md | 2 +- .../navigationdestination/getstate/index.md | 2 +- .../web/api/navigationdestination/id/index.md | 2 +- .../web/api/navigationdestination/index.md | 8 ++- .../api/navigationdestination/index/index.md | 2 +- .../api/navigationdestination/key/index.md | 2 +- .../samedocument/index.md | 2 +- .../api/navigationdestination/url/index.md | 6 +- .../dispose_event/index.md | 4 +- .../web/api/navigationhistoryentry/index.md | 32 +++++----- .../api/navigationhistoryentry/key/index.md | 18 +++--- .../navigationtransition/finished/index.md | 8 ++- .../web/api/navigationtransition/index.md | 10 ++-- 43 files changed, 283 insertions(+), 203 deletions(-) diff --git a/files/en-us/web/api/navigateevent/destination/index.md b/files/en-us/web/api/navigateevent/destination/index.md index c49269914dd0236..4f75521707d6cdd 100644 --- a/files/en-us/web/api/navigateevent/destination/index.md +++ b/files/en-us/web/api/navigateevent/destination/index.md @@ -31,10 +31,12 @@ A {{domxref("NavigationDestination")}} object. ## Examples ```js -navigation.addEventListener('navigate', event => { +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; + if (shouldNotIntercept(event)) { + return; + } const url = new URL(event.destination.url); diff --git a/files/en-us/web/api/navigateevent/downloadrequest/index.md b/files/en-us/web/api/navigateevent/downloadrequest/index.md index 9823db9d31aed6d..d99b907fa589379 100644 --- a/files/en-us/web/api/navigateevent/downloadrequest/index.md +++ b/files/en-us/web/api/navigateevent/downloadrequest/index.md @@ -31,7 +31,7 @@ A string containing the filename of the file requested for download, or `null`. ## Examples ```js -navigation.addEventListener("navigate", event => { +navigation.addEventListener("navigate", (event) => { // Some navigations, e.g. cross-origin navigations, we // cannot intercept. Let the browser handle those normally. if (!event.canIntercept) { diff --git a/files/en-us/web/api/navigateevent/formdata/index.md b/files/en-us/web/api/navigateevent/formdata/index.md index 4c8eea4e055b17e..700bf282b07b142 100644 --- a/files/en-us/web/api/navigateevent/formdata/index.md +++ b/files/en-us/web/api/navigateevent/formdata/index.md @@ -31,7 +31,7 @@ A {{domxref("FormData")}} object, or `null`. ## Examples ```js -navigation.addEventListener("navigate", event => { +navigation.addEventListener("navigate", (event) => { // Some navigations, e.g. cross-origin navigations, we // cannot intercept. Let the browser handle those normally. if (!event.canIntercept) { diff --git a/files/en-us/web/api/navigateevent/hashchange/index.md b/files/en-us/web/api/navigateevent/hashchange/index.md index 08b0586a846f633..519b3578f0a3e2b 100644 --- a/files/en-us/web/api/navigateevent/hashchange/index.md +++ b/files/en-us/web/api/navigateevent/hashchange/index.md @@ -31,7 +31,7 @@ A boolean value—`true` if the navigation is a fragment navigation, `false` if ## Examples ```js -navigation.addEventListener("navigate", event => { +navigation.addEventListener("navigate", (event) => { // Some navigations, e.g. cross-origin navigations, we // cannot intercept. Let the browser handle those normally. if (!event.canIntercept) { diff --git a/files/en-us/web/api/navigateevent/index.md b/files/en-us/web/api/navigateevent/index.md index 31693951c3a8e9e..6e289d6ba5f22fe 100644 --- a/files/en-us/web/api/navigateevent/index.md +++ b/files/en-us/web/api/navigateevent/index.md @@ -19,7 +19,7 @@ browser-compat: api.NavigateEvent {{APIRef("Navigation API")}}{{seecompattable}} -The **`NavigateEvent`** interface of the {{domxref("Navigation API")}} is the event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated (this includes usage of History API features like {{domxref("History.go()")}}). `NavigateEvent` provides access to information about that navigation, and allows developers to intercept and control the navigation handling. +The **`NavigateEvent`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} is the event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated (this includes usage of {{domxref("History API", "History API", "", "nocode")}} features like {{domxref("History.go()")}}). `NavigateEvent` provides access to information about that navigation, and allows developers to intercept and control the navigation handling. {{InheritanceDiagram}} diff --git a/files/en-us/web/api/navigateevent/info/index.md b/files/en-us/web/api/navigateevent/info/index.md index 1baae5839663977..c73a6ec75aea58f 100644 --- a/files/en-us/web/api/navigateevent/info/index.md +++ b/files/en-us/web/api/navigateevent/info/index.md @@ -33,7 +33,7 @@ Any data type representing the `info` value, or `false` if none was passed. One example of how `info` might be used is to trigger different single-page navigation renderings depending on how a certain route was reached. For example, consider a photo gallery app, where you can reach the same photo URL and state via various routes. You might want to use a different animation to show the photo for each route. ```js -navigation.addEventListener("navigate", event => { +navigation.addEventListener("navigate", (event) => { if (isPhotoNavigation(event)) { event.intercept({ async handler() { switch (event.info.?via) { diff --git a/files/en-us/web/api/navigateevent/intercept/index.md b/files/en-us/web/api/navigateevent/intercept/index.md index 37039d98fa2610c..244cc78fd96dc4c 100644 --- a/files/en-us/web/api/navigateevent/intercept/index.md +++ b/files/en-us/web/api/navigateevent/intercept/index.md @@ -84,7 +84,7 @@ navigation.addEventListener('navigate', event => { Form submission can be detected by querying for the {{domxref("NavigateEvent.formData")}} property. The following example turns any form submission into one which stays on the current page. In this case, you don't update the DOM, so you can cancel any default reset and scroll behavior using `focusReset` and `scroll`. ```js -navigation.addEventListener('navigate', event => { +navigation.addEventListener('navigate', (event) => { if (event.formData && event.canIntercept) { // User submitted a POST form to a same-domain URL // (If canIntercept is false, the event is just informative: @@ -96,7 +96,7 @@ navigation.addEventListener('navigate', event => { // don't allow focus or scrolling to reset: focusReset: 'manual', scroll: 'manual', - handler() { + async handler() { await fetch(event.destination.url, { method: 'POST', body: event.formData, diff --git a/files/en-us/web/api/navigateevent/navigateevent/index.md b/files/en-us/web/api/navigateevent/navigateevent/index.md index 0bc1224b7d9134e..ce5ebdcd857d771 100644 --- a/files/en-us/web/api/navigateevent/navigateevent/index.md +++ b/files/en-us/web/api/navigateevent/navigateevent/index.md @@ -58,10 +58,12 @@ new NavigateEvent(type, init) A developer would not use this constructor manually. A new `NavigateEvent` object is constructed when a handler is invoked as a result of the {{domxref("Navigation.navigate_event", "navigate")}} event firing. ```js -navigation.addEventListener('navigate', event => { +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; + if (shouldNotIntercept(event)) { + return; + } const url = new URL(event.destination.url); diff --git a/files/en-us/web/api/navigateevent/navigationtype/index.md b/files/en-us/web/api/navigateevent/navigationtype/index.md index 7e0685f7a6c9b8e..ee09d9ea28a3e61 100644 --- a/files/en-us/web/api/navigateevent/navigationtype/index.md +++ b/files/en-us/web/api/navigateevent/navigationtype/index.md @@ -42,7 +42,7 @@ The possible values are: Sometimes it's desirable to handle back/forward navigations specially, e.g. reusing cached views by transitioning them onto the screen. This can be done by branching as follows: ```js -navigation.addEventListener("navigate", event => { +navigation.addEventListener("navigate", (event) => { // Some navigations, e.g. cross-origin navigations, we // cannot intercept. Let the browser handle those normally. if (!event.canIntercept) { diff --git a/files/en-us/web/api/navigateevent/scroll/index.md b/files/en-us/web/api/navigateevent/scroll/index.md index a0369b076f7d566..74eb073d3aab273 100644 --- a/files/en-us/web/api/navigateevent/scroll/index.md +++ b/files/en-us/web/api/navigateevent/scroll/index.md @@ -46,8 +46,10 @@ None. ### Handling scrolling using `scroll()` ```js -navigation.addEventListener('navigate', event => { - if (shouldNotIntercept(navigateEvent)) return; +navigation.addEventListener('navigate', (event) => { + if (shouldNotIntercept(navigateEvent)) { + return; + } const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { diff --git a/files/en-us/web/api/navigateevent/signal/index.md b/files/en-us/web/api/navigateevent/signal/index.md index 58b430eef74ab13..a2c48693cb9afc1 100644 --- a/files/en-us/web/api/navigateevent/signal/index.md +++ b/files/en-us/web/api/navigateevent/signal/index.md @@ -33,14 +33,14 @@ An {{domxref("AbortSignal")}} object. The general idea here is that the `signal` property can be passed to an associated {{domxref("fetch()")}} operation so that if the navigation is cancelled, it can be safely aborted, avoiding wasting bandwidth on fetches that are no longer needed. ```js -navigation.addEventListener("navigate", event => { +navigation.addEventListener("navigate", (event) => { event.intercept({ async handler() { - ... + // ... await fetch(`/img/some-image.jpg`, { signal: event.signal }); - ... + // ... } }); }); diff --git a/files/en-us/web/api/navigateevent/userinitiated/index.md b/files/en-us/web/api/navigateevent/userinitiated/index.md index 8b5a71e9e1d9642..57a3fa502d3fd47 100644 --- a/files/en-us/web/api/navigateevent/userinitiated/index.md +++ b/files/en-us/web/api/navigateevent/userinitiated/index.md @@ -33,7 +33,7 @@ A boolean value—`true` if the navigation is user-initiated, `false` if not. ## Examples ```js -navigation.addEventListener("navigate", event => { +navigation.addEventListener("navigate", (event) => { console.log(event.userInitiated); }); ``` diff --git a/files/en-us/web/api/navigation/back/index.md b/files/en-us/web/api/navigation/back/index.md index f061a864c60c1cf..2da0f19e5ad1298 100644 --- a/files/en-us/web/api/navigation/back/index.md +++ b/files/en-us/web/api/navigation/back/index.md @@ -52,22 +52,24 @@ An object containing two promises — `{ committed, finished }`. This allows the ## Examples ```js -if(navigation.canGoBack) { - await navigation.back( { info: "swipe-right" } ).finished; - // Handle any required clean-up after - // navigation has finished -} else { - displayBanner('You are on the first page'); +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'); + } } - ... - -if(navigation.canGoForward) { - await navigation.forward( { info: "swipe-right" } ).finished; - // Handle any required clean-up after - // navigation has finished -} else { - displayBanner('You are on the last 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'); + } } ``` diff --git a/files/en-us/web/api/navigation/cangoback/index.md b/files/en-us/web/api/navigation/cangoback/index.md index 187dd1c528f6dd8..eff3b34a3136c4c 100644 --- a/files/en-us/web/api/navigation/cangoback/index.md +++ b/files/en-us/web/api/navigation/cangoback/index.md @@ -34,22 +34,24 @@ A boolean value—`true` if it is possible to navigate backwards in the navigati ## Examples ```js -if(navigation.canGoBack) { - await navigation.back( { info: "swipe-right" } ).finished; - // Handle any required clean-up after - // navigation has finished -} else { - displayBanner('You are on the first page'); +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'); + } } - ... - -if(navigation.canGoForward) { - await navigation.forward( { info: "swipe-right" } ).finished; - // Handle any required clean-up after - // navigation has finished -} else { - displayBanner('You are on the last 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'); + } } ``` diff --git a/files/en-us/web/api/navigation/cangoforward/index.md b/files/en-us/web/api/navigation/cangoforward/index.md index 1cf05294150cc05..54290aeb4060659 100644 --- a/files/en-us/web/api/navigation/cangoforward/index.md +++ b/files/en-us/web/api/navigation/cangoforward/index.md @@ -32,22 +32,24 @@ A boolean value—`true` if it is possible to navigate forwards in the navigatio ## Examples ```js -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 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'); + } } - ... - -if(navigation.canGoForward) { - await navigation.forward().finished; - // Handle any required clean-up after - // navigation has finished -} else { - displayBanner('You are on the last 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'); + } } ``` diff --git a/files/en-us/web/api/navigation/currententry/index.md b/files/en-us/web/api/navigation/currententry/index.md index 021bdf7d0e97290..2e54debef6b5183 100644 --- a/files/en-us/web/api/navigation/currententry/index.md +++ b/files/en-us/web/api/navigation/currententry/index.md @@ -31,13 +31,17 @@ A {{domxref("NavigationHistoryEntry")}} object. ## Examples ```js -// On JS startup, get the key of the first loaded page -// so the user can always go back there. -const {key} = navigation.currentEntry; -backToHomeButton.onclick = () => navigation.traverseTo(key); - -// Navigate away, but the button will always work. -await navigation.navigate('/another_url').finished; +async function initHomeBtn() { + // Get the key of the first loaded page + // so the user can always go back there. + const {key} = navigation.currentEntry; + backToHomeButton.onclick = () => navigation.traverseTo(key); +} + +async function handleNavigate(url) { + // Navigate away, but the button will always work. + await navigation.navigate(url).finished; +} ``` ## Specifications diff --git a/files/en-us/web/api/navigation/currententrychange_event/index.md b/files/en-us/web/api/navigation/currententrychange_event/index.md index 71a19fabfa8f3b3..6ac08dd4929f301 100644 --- a/files/en-us/web/api/navigation/currententrychange_event/index.md +++ b/files/en-us/web/api/navigation/currententrychange_event/index.md @@ -23,7 +23,7 @@ browser-compat: api.Navigation.currententrychange_event The **`currententrychange`** event of the {{domxref("Navigation")}} interface is fired when the {{domxref("Navigation.currentEntry")}} has changed. -This event will fire for same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}), replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`), or other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API")}}'s {{domxref("History.replaceState()")}}). +This event will fire for same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}), replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`), or other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API", "History API", "", "nocode")}}'s {{domxref("History.replaceState()")}}). This event fires after the navigation is committed, meaning that the visible URL has changed and the {{domxref("NavigationHistoryEntry")}} update has occurred. It is useful for migrating from usage of older API features like the {{domxref("Window/hashchange_event", "hashchange")}} or {{domxref("Window/popstate_event", "popstate")}} events. @@ -37,7 +37,11 @@ addEventListener("currententrychange", (event) => {}); oncurrententrychange = (event) => {}; ``` -> **Note:** The event object is of type {{domxref("NavigationCurrentEntryChangeEvent")}}. +## Event type + +An {{domxref("NavigationCurrentEntryChangeEvent")}}. Inherits from {{domxref("Event")}}. + +{{InheritanceDiagram("NavigationCurrentEntryChangeEvent")}} ## Examples diff --git a/files/en-us/web/api/navigation/forward/index.md b/files/en-us/web/api/navigation/forward/index.md index 454cfe1420cc97c..9fc33f43df0fe61 100644 --- a/files/en-us/web/api/navigation/forward/index.md +++ b/files/en-us/web/api/navigation/forward/index.md @@ -52,22 +52,24 @@ An object containing two promises — `{ committed, finished }`. This allows the ## Examples ```js -if(navigation.canGoBack) { - await navigation.back( { info: "swipe-right" } ).finished; - // Handle any required clean-up after - // navigation has finished -} else { - displayBanner('You are on the first page'); +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'); + } } - ... - -if(navigation.canGoForward) { - await navigation.forward( { info: "swipe-right" } ).finished; - // Handle any required clean-up after - // navigation has finished -} else { - displayBanner('You are on the last 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'); + } } ``` diff --git a/files/en-us/web/api/navigation/index.md b/files/en-us/web/api/navigation/index.md index c8d95d65d7ce10d..1ddcc00109bf3c7 100644 --- a/files/en-us/web/api/navigation/index.md +++ b/files/en-us/web/api/navigation/index.md @@ -19,11 +19,11 @@ browser-compat: api.Navigation {{APIRef("Navigation API")}}{{seecompattable}} -The **`Navigation`** interface of the {{domxref("Navigation API")}} allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, introspecting navigation history entries, and managing navigations as they happen. +The **`Navigation`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, examining navigation history entries, and managing navigations as they happen. It is accessed via the {{domxref("Window.navigation")}} property. -The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. +The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded {{htmlelement("iframe")}}s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older {{domxref("History API", "History API", "", "nocode")}}. {{InheritanceDiagram}} @@ -44,18 +44,7 @@ _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ navigated to right now. - {{domxref("Navigation.transition", "transition")}} {{ReadOnlyInline}} - : Returns a {{domxref("NavigationTransition")}} object representing the status of an in-progress navigation, - which can be used to track it. Returns `null` in no navigation is currently in progress. - -### `Navigation` events - -- {{domxref("Navigation/currententrychange_event", "currententrychange")}} - - : Fired when the {{domxref("Navigation.currentEntry")}} has changed. -- {{domxref("Navigation/navigate_event", "navigate")}} - - : Fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, allowing you to intercept as required. -- {{domxref("Navigation/navigateerror_event", "navigateerror")}} - - : Fired when a navigation fails. -- {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} - - : Fired when a successful navigation has finished. + which can be used to track it. Returns `null` if no navigation is currently in progress. ## Instance methods @@ -77,27 +66,40 @@ _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - : Updates the state of the {{domxref("Navigation.currentEntry","currentEntry")}}; used in cases where the state change will be independent from a navigation or reload. +## Events + +- {{domxref("Navigation/currententrychange_event", "currententrychange")}} + - : Fired when the {{domxref("Navigation.currentEntry")}} has changed. +- {{domxref("Navigation/navigate_event", "navigate")}} + - : Fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, allowing you to intercept as required. +- {{domxref("Navigation/navigateerror_event", "navigateerror")}} + - : Fired when a navigation fails. +- {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} + - : Fired when a successful navigation has finished. + ## Examples ### Moving forwards and backwards in the history ```js -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 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'); + } } - ... - -if(navigation.canGoForward) { - await navigation.forward().finished; - // Handle any required clean-up after - // navigation has finished -} else { - displayBanner('You are on the last 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'); + } } ``` diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index 623303eed2006cb..520ee02e9d2c610 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -68,13 +68,17 @@ An object containing two promises — `{ committed, finished }`. This allows the ### Set up home button ```js -// On JS startup, get the key of the first loaded page -// so the user can always go back there. -const {key} = navigation.currentEntry; -backToHomeButton.onclick = () => navigation.traverseTo(key); - -// Navigate away, but the button will always work. -await navigation.navigate('/another_url').finished; +async function initHomeBtn() { + // Get the key of the first loaded page + // so the user can always go back there. + const {key} = navigation.currentEntry; + backToHomeButton.onclick = () => navigation.traverseTo(key); +} + +async function handleNavigate(url) { + // Navigate away, but the button will always work. + await navigation.navigate(url).finished; +} ``` ### A smart back button @@ -96,7 +100,9 @@ backButtonEl.addEventListener("click", () => { ### Usage of info and state ```js -await navigation.navigate(url, { info: { animation: "swipe-right" }, state: { infoPaneOpen: true } } ); +async function navigateHandler() { + await navigation.navigate(url, { info: { animation: "swipe-right" }, state: { infoPaneOpen: true } } ); +} ``` ## Specifications diff --git a/files/en-us/web/api/navigation/navigate_event/index.md b/files/en-us/web/api/navigation/navigate_event/index.md index 9b4e0392c37fa42..943d7d34761f998 100644 --- a/files/en-us/web/api/navigation/navigate_event/index.md +++ b/files/en-us/web/api/navigation/navigate_event/index.md @@ -32,17 +32,23 @@ addEventListener("navigate", (event) => {}); onnavigate = (event) => {}; ``` -> **Note:** The event object is of type {{domxref("NavigateEvent")}}. +## Event type + +An {{domxref("NavigateEvent")}}. Inherits from {{domxref("Event")}}. + +{{InheritanceDiagram("NavigateEvent")}} ## Examples ### Handling a navigation using `intercept()` ```js -navigation.addEventListener('navigate', event => { +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; + if (shouldNotIntercept(event)) { + return; + } const url = new URL(event.destination.url); @@ -62,13 +68,15 @@ navigation.addEventListener('navigate', event => { }); ``` -> **Note:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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. +> **Note:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `event.preventDefault()`, perform the appropriate {{domxref("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()` ```js -navigation.addEventListener('navigate', event => { - if (shouldNotIntercept(navigateEvent)) return; +navigation.addEventListener('navigate', (event) => { + if (shouldNotIntercept(navigateEvent)) { + return; + } const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { diff --git a/files/en-us/web/api/navigation/navigateerror_event/index.md b/files/en-us/web/api/navigation/navigateerror_event/index.md index 5b1f937eabdcdc5..21dcc0767ee5849 100644 --- a/files/en-us/web/api/navigation/navigateerror_event/index.md +++ b/files/en-us/web/api/navigation/navigateerror_event/index.md @@ -35,14 +35,18 @@ addEventListener("navigateerror", (event) => {}); onnavigateerror = (event) => {}; ``` -> **Note:** The event object is of type {{domxref("ErrorEvent")}}. +## Event type + +An {{domxref("ErrorEvent")}}. Inherits from {{domxref("Event")}}. + +{{InheritanceDiagram("ErrorEvent")}} ## Examples You might deal with a successful navigation by hiding a previously displayed progress indicator, like this: ```js -navigation.addEventListener('navigatesuccess', event => { +navigation.addEventListener('navigatesuccess', (event) => { loadingIndicator.hidden = true; }); ``` @@ -50,7 +54,7 @@ navigation.addEventListener('navigatesuccess', event => { Or you might show an error message on failure: ```js -navigation.addEventListener('navigateerror', event => { +navigation.addEventListener('navigateerror', (event) => { loadingIndicator.hidden = true; // also hide indicator showMessage(`Failed to load page: ${event.message}`); }); diff --git a/files/en-us/web/api/navigation/navigatesuccess_event/index.md b/files/en-us/web/api/navigation/navigatesuccess_event/index.md index 1e168d90b8d13a3..dcb48da359872c3 100644 --- a/files/en-us/web/api/navigation/navigatesuccess_event/index.md +++ b/files/en-us/web/api/navigation/navigatesuccess_event/index.md @@ -23,7 +23,7 @@ browser-compat: api.Navigation.navigatesuccess_event The **`navigatesuccess`** event of the {{domxref("Navigation")}} interface is fired when a successful navigation has finished. -This means that all promises returned by your `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling. +In the case of an intercepted navigation, this would occur after any promises returned by your {{domxref("NavigateEvent.intercept", "intercept()")}} handler are fulfilled. The {{domxref("NavigationTransition.finished")}} promise will also fulfill at the same time. ## Syntax @@ -35,14 +35,16 @@ addEventListener("navigatesuccess", (event) => {}); onnavigatesuccess = (event) => {}; ``` -> **Note:** The event object is of type {{domxref("Event")}}. +## Event type + +A generic {{domxref("Event")}}. ## Examples You might deal with a successful navigation by hiding a previously displayed progress indicator, like this: ```js -navigation.addEventListener('navigatesuccess', event => { +navigation.addEventListener('navigatesuccess', (event) => { loadingIndicator.hidden = true; }); ``` @@ -50,7 +52,7 @@ navigation.addEventListener('navigatesuccess', event => { Or you might show an error message on failure: ```js -navigation.addEventListener('navigateerror', event => { +navigation.addEventListener('navigateerror', (event) => { loadingIndicator.hidden = true; // also hide indicator showMessage(`Failed to load page: ${event.message}`); }); diff --git a/files/en-us/web/api/navigation/reload/index.md b/files/en-us/web/api/navigation/reload/index.md index 5b0ca2968a9159d..46818b98e88eef5 100644 --- a/files/en-us/web/api/navigation/reload/index.md +++ b/files/en-us/web/api/navigation/reload/index.md @@ -55,13 +55,21 @@ None. Usage of info and state ```js -await navigation.reload({ info: { animation: "fade-in" }, state: { infoPaneOpen: true } } ); +async function handleReload() { + await navigation.reload({ info: { animation: "fade-in" }, state: { infoPaneOpen: true } } ); + + // ... +} ``` Reload page and add a new state item: ```js -await navigation.reload({ state: { ...navigation.currentEntry.getState(), newState: 3 } }); +async function handleReload() { + await navigation.reload({ state: { ...navigation.currentEntry.getState(), newState: 3 } }); + + // ... +} ``` ## Specifications diff --git a/files/en-us/web/api/navigation/transition/index.md b/files/en-us/web/api/navigation/transition/index.md index d88fb80cb0c6f74..776626ab6c8ee2d 100644 --- a/files/en-us/web/api/navigation/transition/index.md +++ b/files/en-us/web/api/navigation/transition/index.md @@ -26,15 +26,17 @@ The **`transition`** read-only property of the ## Value -A {{domxref("NavigationTransition")}} object, or `null` in no navigation is currently in progress. +A {{domxref("NavigationTransition")}} object, or `null` if no navigation is currently in progress. ## Examples ```js -if(navigation.transition) { - showLoadingSpinner(); - await navigation.transition.finished; - hideLoadingSpinner(); +async function handleTransition() { + if(navigation.transition) { + showLoadingSpinner(); + await navigation.transition.finished; + hideLoadingSpinner(); + } } ``` diff --git a/files/en-us/web/api/navigation/traverseto/index.md b/files/en-us/web/api/navigation/traverseto/index.md index 5fcf7ecd1d7c70e..2010eaad08c2498 100644 --- a/files/en-us/web/api/navigation/traverseto/index.md +++ b/files/en-us/web/api/navigation/traverseto/index.md @@ -56,13 +56,17 @@ An object containing two promises — `{ committed, finished }`. This allows the ### Set up home button ```js -// On JS startup, get the key of the first loaded page -// so the user can always go back there. -const {key} = navigation.currentEntry; -backToHomeButton.onclick = () => navigation.traverseTo(key); - -// Navigate away, but the button will always work. -await navigation.navigate('/another_url').finished; +async function initHomeBtn() { + // Get the key of the first loaded page + // so the user can always go back there. + const {key} = navigation.currentEntry; + backToHomeButton.onclick = () => navigation.traverseTo(key); +} + +async function handleNavigate(url) { + // Navigate away, but the button will always work. + await navigation.navigate(url).finished; +} ``` ## Specifications diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index 15b0313b83b03e3..fefe3140aa86115 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -21,17 +21,17 @@ browser-compat: {{seecompattable}}{{DefaultAPISidebar("Navigation API")}} -The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also examine an application's history entries. This is a successor to previous web platform features such as the [History API](/en-US/docs/Web/API/History_API) and {{domxref("window.location")}}, which solves their shortcomings and is specifically aimed at the needs of {{glossary("SPA", "single-page applications (SPAs)")}}. +The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also examine an application's history entries. This is a successor to previous web platform features such as the {{domxref("History API", "History API", "", "nocode")}} and {{domxref("window.location")}}, which solves their shortcomings and is specifically aimed at the needs of {{glossary("SPA", "single-page applications (SPAs)")}}. ## Concepts and usage -In SPAs, the page template tends to stay the same during usage, and the content is dynamically rewritten as the user visits different pages or features. As a result, only one distinct page is loaded in the browser, which breaks the expected user experience of navigating back and forth between different locations in the viewing history. This problem can be solved to a degree via the [History API](/en-US/docs/Web/API/History_API), but it is not designed for the needs of SPAs. The Navigation API aims to bridge that gap. +In SPAs, the page template tends to stay the same during usage, and the content is dynamically rewritten as the user visits different pages or features. As a result, only one distinct page is loaded in the browser, which breaks the expected user experience of navigating back and forth between different locations in the viewing history. This problem can be solved to a degree via the {{domxref("History API", "History API", "", "nocode")}}, but it is not designed for the needs of SPAs. The Navigation API aims to bridge that gap. The API is accessed via the {{domxref("Window.navigation")}} property, which returns a reference to a global {{domxref("Navigation")}} object. Each `window` object has its own corresponding `navigation` instance. ### Handling navigations -The `navigation` interface has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the {{domxref("History API")}}, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event handler is passed a {{domxref("NavigateEvent")}} object, which contains detailed information including details around the navigation's destination, type, whether it contains `POST` form data or a download request, and more. +The `navigation` interface has several associated events, the most notable being the {{domxref("Navigation/navigate_event", "navigate")}} event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the {{domxref("History API", "History API", "", "nocode")}}, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event handler is passed a {{domxref("NavigateEvent")}} object, which contains detailed information including details around the navigation's destination, type, whether it contains `POST` form data or a download request, and more. The `NavigationEvent` object also provides two methods: @@ -52,7 +52,7 @@ When the `intercept()` handler function's promise fulfills, the `Navigation` obj As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct {{domxref("NavigationHistoryEntry")}} object instance. These contain several properties such as the entry's key, URL, and state information. You can get the entry that the user is currently on right now using {{domxref("Navigation.currentEntry")}}, and an array of all existing history entries using {{domxref("Navigation.entries()")}}. Each `NavigationHistoryEntry` object has a {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} event, which fires when the entry is no longer part of the browser history. For example, if the user navigates back three times, then navigates forward to somewhere else, those three history entries will be disposed of. -> **Note:** The Navigation API only exposes history entries created directly by the application's top-level context (e.g. not navigations inside embedded {{htmlelement("iframe")}}s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. +> **Note:** The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded {{htmlelement("iframe")}}s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older {{domxref("History API", "History API", "", "nocode")}}. The `Navigation` object contains all the methods you'll need to update and traverse through the navigation history: @@ -83,23 +83,23 @@ In some cases however, a state change will be independent from a navigation or r There are a few perceived limitations with the Navigation API: 1. The current specification doesn't trigger {{domxref("Navigation.navigate_event", "navigate")}} on a page's first load. This might be fine for sites that use Server Side Rendering (SSR)—your server could return the correct initial state, which is the fastest way to get content to your users. But sites that leverage client-side code to create their pages may need an additional function to initialize the page. -2. The Navigation API operates only within a single frame—the top-level page, or a single specific {{htmlelement("iframe")}}. This has some interesting implications that are [further documented in the spec](https://github.com/WICG/navigation-api#warning-backforward-are-not-always-opposites), but in practice, will reduce developer confusion. The previous History API has several confusing edge cases, like support for frames, which the Navigation API handles up-front. +2. The Navigation API operates only within a single frame—the top-level page, or a single specific {{htmlelement("iframe")}}. This has some interesting implications that are [further documented in the spec](https://github.com/WICG/navigation-api#warning-backforward-are-not-always-opposites), but in practice, will reduce developer confusion. The previous {{domxref("History API", "History API", "", "nocode")}} has several confusing edge cases, like support for frames, which the Navigation API handles up-front. 3. You can't currently use the Navigation API to programmatically modify or rearrange the history list. It might be useful to have a temporary state, for example navigating the user to a temporary modal that asks them for some information, then going back to the previous URL. In this case, you'd want to delete the temporary modal navigation entry so the user cannot mess up the application flow by hitting the forward button and opening it again. ## Interfaces +- {{domxref("NavigateEvent")}} + - : Event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated. It provides access to information about that navigation, and most notably the {{domxref("NavigateEvent.intercept", "intercept()")}}, which allows you to control what happens when the navigation is initiated. - {{domxref("Navigation")}} - : Allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, examining navigation history entries, and managing navigations as they happen. +- {{domxref("NavigationCurrentEntryChangeEvent")}} + - : Event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the {{domxref("Navigation.currentEntry")}} has changed. It provides access to the navigation type, and the previous history entry that was navigated from. - {{domxref("NavigationDestination")}} - : Represents the destination being navigated to in the current navigation. - {{domxref("NavigationHistoryEntry")}} - : Represents a single navigation history entry. - {{domxref("NavigationTransition")}} - : Represents an ongoing navigation. -- {{domxref("NavigationCurrentEntryChangeEvent")}} - - : Event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the {{domxref("Navigation.currentEntry")}} has changed. It provides access to the navigation type, and the previous history entry that was navigated from. -- {{domxref("NavigateEvent")}} - - : Event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated. It provides access to information about that navigation, and most notably the {{domxref("NavigateEvent.intercept", "intercept()")}}, which allows you to control what happens when the navigation is initiated. ## Extensions to other interfaces @@ -113,10 +113,12 @@ There are a few perceived limitations with the Navigation API: ### Handling a navigation using `intercept()` ```js -navigation.addEventListener('navigate', event => { +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; + if (shouldNotIntercept(event)) { + return; + } const url = new URL(event.destination.url); @@ -139,8 +141,10 @@ navigation.addEventListener('navigate', event => { ### Handling scrolling using `scroll()` ```js -navigation.addEventListener('navigate', event => { - if (shouldNotIntercept(event)) return; +navigation.addEventListener('navigate', (event) => { + if (shouldNotIntercept(event)) { + return; + } const url = new URL(event.destination.url); if (url.pathname.startsWith('/articles/')) { diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/from/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/from/index.md index 701b945f109ca9a..54c0d42552f6739 100644 --- a/files/en-us/web/api/navigationcurrententrychangeevent/from/index.md +++ b/files/en-us/web/api/navigationcurrententrychangeevent/from/index.md @@ -30,7 +30,7 @@ A {{domxref("NavigationHistoryEntry")}} object. ## Examples ```js -navigation.addEventListener("currententrychange", event => { +navigation.addEventListener("currententrychange", (event) => { console.log(event.from); }); ``` diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/index.md index ae36e90c77b5aa3..c96c97d4a2c3c41 100644 --- a/files/en-us/web/api/navigationcurrententrychangeevent/index.md +++ b/files/en-us/web/api/navigationcurrententrychangeevent/index.md @@ -19,9 +19,9 @@ browser-compat: api.NavigationCurrentEntryChangeEvent {{APIRef("Navigation API")}}{{seecompattable}} -The **`NavigationCurrentEntryChangeEvent`** interface of the {{domxref("Navigation API")}} is the event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the {{domxref("Navigation.currentEntry")}} has changed. +The **`NavigationCurrentEntryChangeEvent`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} is the event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the {{domxref("Navigation.currentEntry")}} has changed. -This event will fire for same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}), replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`), or other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API")}}'s {{domxref("History.replaceState()")}}). +This event will fire for same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}), replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`), or other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API", "History API", "", "nocode")}}'s {{domxref("History.replaceState()")}}). This event fires after the navigation is committed, meaning that the visible URL has changed and the {{domxref("NavigationHistoryEntry")}} update has occurred. It is useful for migrating from usage of older API features like the {{domxref("Window/hashchange_event", "hashchange")}} or {{domxref("Window/popstate_event", "popstate")}} events. diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md index ce78c40116ada0a..b12ce6fca7f3e0b 100644 --- a/files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md +++ b/files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md @@ -43,7 +43,7 @@ new NavigationCurrentEntryChangeEvent(type, init) A developer would not use this constructor manually. A new `NavigationCurrentEntryChangeEvent` object is constructed when a handler is invoked as a result of the {{domxref("Navigation.currententrychange_event", "currententrychange")}} event firing. ```js -navigation.addEventListener("currententrychange", event => { +navigation.addEventListener("currententrychange", (event) => { console.log(event.navigationType); }); ``` diff --git a/files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md b/files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md index eeab118e8a9f413..b432e10cb263784 100644 --- a/files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md +++ b/files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md @@ -37,7 +37,7 @@ The possible values are: ## Examples ```js -navigation.addEventListener("currententrychange", event => { +navigation.addEventListener("currententrychange", (event) => { console.log(event.navigationType); }); ``` diff --git a/files/en-us/web/api/navigationdestination/getstate/index.md b/files/en-us/web/api/navigationdestination/getstate/index.md index a4cdeeab70c952e..8407adbac9e52e4 100644 --- a/files/en-us/web/api/navigationdestination/getstate/index.md +++ b/files/en-us/web/api/navigationdestination/getstate/index.md @@ -46,7 +46,7 @@ None. ## Examples ```js -navigation.addEventListener('navigate', event => { +navigation.addEventListener('navigate', (event) => { console.log(event.destination.getState()); }); ``` diff --git a/files/en-us/web/api/navigationdestination/id/index.md b/files/en-us/web/api/navigationdestination/id/index.md index 2b5469c3339af3f..892e365911d9588 100644 --- a/files/en-us/web/api/navigationdestination/id/index.md +++ b/files/en-us/web/api/navigationdestination/id/index.md @@ -32,7 +32,7 @@ A string representing the `id` of the destination {{domxref("NavigationHistoryEn ## Examples ```js -navigation.addEventListener('navigate', event => { +navigation.addEventListener('navigate', (event) => { console.log(event.destination.id); }); ``` diff --git a/files/en-us/web/api/navigationdestination/index.md b/files/en-us/web/api/navigationdestination/index.md index 875f89fee2fc895..48491c360bfb77e 100644 --- a/files/en-us/web/api/navigationdestination/index.md +++ b/files/en-us/web/api/navigationdestination/index.md @@ -19,7 +19,7 @@ browser-compat: api.NavigationDestination {{APIRef("Navigation API")}}{{seecompattable}} -The **`NavigationDestination`** interface of the {{domxref("Navigation API")}} represents the destination being navigated to in the current navigation. +The **`NavigationDestination`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} represents the destination being navigated to in the current navigation. It is accessed via the {{domxref("NavigateEvent.destination")}} property. @@ -46,10 +46,12 @@ It is accessed via the {{domxref("NavigateEvent.destination")}} property. ## Examples ```js -navigation.addEventListener('navigate', event => { +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; + if (shouldNotIntercept(event)) { + return; + } // Returns a URL() object constructed from the // NavigationDestination.url value diff --git a/files/en-us/web/api/navigationdestination/index/index.md b/files/en-us/web/api/navigationdestination/index/index.md index e2c9cb8cce11fbc..460a49b6f6c7971 100644 --- a/files/en-us/web/api/navigationdestination/index/index.md +++ b/files/en-us/web/api/navigationdestination/index/index.md @@ -30,7 +30,7 @@ A number representing the `index` of the destination {{domxref("NavigationHistor ## Examples ```js -navigation.addEventListener('navigate', event => { +navigation.addEventListener('navigate', (event) => { console.log(event.destination.index); }); ``` diff --git a/files/en-us/web/api/navigationdestination/key/index.md b/files/en-us/web/api/navigationdestination/key/index.md index 6d14c893b78b6aa..8d08ef44c7b1b8a 100644 --- a/files/en-us/web/api/navigationdestination/key/index.md +++ b/files/en-us/web/api/navigationdestination/key/index.md @@ -32,7 +32,7 @@ A string representing the `key` of the destination {{domxref("NavigationHistoryE ## Examples ```js -navigation.addEventListener('navigate', event => { +navigation.addEventListener('navigate', (event) => { console.log(event.destination.key); }); ``` diff --git a/files/en-us/web/api/navigationdestination/samedocument/index.md b/files/en-us/web/api/navigationdestination/samedocument/index.md index 90c2e9d1991cbd5..84b5f5f9d86d9eb 100644 --- a/files/en-us/web/api/navigationdestination/samedocument/index.md +++ b/files/en-us/web/api/navigationdestination/samedocument/index.md @@ -32,7 +32,7 @@ A boolean. ## Examples ```js -navigation.addEventListener('navigate', event => { +navigation.addEventListener('navigate', (event) => { console.log(event.destination.sameDocument); }); ``` diff --git a/files/en-us/web/api/navigationdestination/url/index.md b/files/en-us/web/api/navigationdestination/url/index.md index 535be31e24551fe..8723a19a7e714c1 100644 --- a/files/en-us/web/api/navigationdestination/url/index.md +++ b/files/en-us/web/api/navigationdestination/url/index.md @@ -32,10 +32,12 @@ A string. ### Handling a navigation using `intercept()` ```js -navigation.addEventListener('navigate', event => { +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; + if (shouldNotIntercept(event)) { + return; + } const url = new URL(event.destination.url); diff --git a/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md b/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md index 1e44e9ce7e4f622..8de4df1c1a94a26 100644 --- a/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md +++ b/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md @@ -40,7 +40,9 @@ addEventListener("dispose", (event) => {}); ondispose = (event) => {}; ``` -> **Note:** The event object is of type {{domxref("Event")}}. +## Event type + +A generic {{domxref("Event")}}. ## Examples diff --git a/files/en-us/web/api/navigationhistoryentry/index.md b/files/en-us/web/api/navigationhistoryentry/index.md index d70bc3118107e57..a343b9a79bb8d91 100644 --- a/files/en-us/web/api/navigationhistoryentry/index.md +++ b/files/en-us/web/api/navigationhistoryentry/index.md @@ -19,11 +19,11 @@ browser-compat: api.NavigationHistoryEntry {{APIRef("Navigation API")}}{{seecompattable}} -The **`NavigationHistoryEntry`** interface of the {{domxref("Navigation API")}} represents a single navigation history entry. +The **`NavigationHistoryEntry`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} represents a single navigation history entry. These objects are commonly accessed via the {{domxref("Navigation.currentEntry")}} property and {{domxref("Navigation.entries()")}} method. -The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API")}}. +The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API", "History API", "", "nocode")}}. {{InheritanceDiagram}} @@ -42,11 +42,6 @@ _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("NavigationHistoryEntry.url", "url")}} {{ReadOnlyInline}} - : Returns the absolute URL of this history entry. -## `NavigationHistoryEntry` events - -- {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} - - : Fires when the entry is no longer part of the history entry list. - ## Instance methods _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ @@ -54,16 +49,25 @@ _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("NavigationHistoryEntry.getState", "getState()")}} - : Returns a clone of the available state associated with this history entry. +## Events + +- {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} + - : Fires when the entry is no longer part of the history entry list. + ## Examples ```js -// On JS startup, get the key of the first loaded page -// so the user can always go back there. -const {key} = navigation.currentEntry; -backToHomeButton.onclick = () => navigation.traverseTo(key); - -// Navigate away, but the button will always work. -await navigation.navigate('/another_url').finished; +async function initHomeBtn() { + // Get the key of the first loaded page + // so the user can always go back there. + const {key} = navigation.currentEntry; + backToHomeButton.onclick = () => navigation.traverseTo(key); +} + +async function handleNavigate(url) { + // Navigate away, but the button will always work. + await navigation.navigate(url).finished; +} ``` ## Specifications diff --git a/files/en-us/web/api/navigationhistoryentry/key/index.md b/files/en-us/web/api/navigationhistoryentry/key/index.md index 3eaa6c19b209482..74d28997316e77c 100644 --- a/files/en-us/web/api/navigationhistoryentry/key/index.md +++ b/files/en-us/web/api/navigationhistoryentry/key/index.md @@ -39,13 +39,17 @@ console.log(current.key); ### Set up a home button ```js -// On JS startup, get the key of the first loaded page -// so the user can always go back there. -const {key} = navigation.currentEntry; -backToHomeButton.onclick = () => navigation.traverseTo(key); - -// Navigate away, but the button will always work. -await navigation.navigate('/another_url').finished; +async function initHomeBtn() { + // Get the key of the first loaded page + // so the user can always go back there. + const {key} = navigation.currentEntry; + backToHomeButton.onclick = () => navigation.traverseTo(key); +} + +async function handleNavigate(url) { + // Navigate away, but the button will always work. + await navigation.navigate(url).finished; +} ``` ## Specifications diff --git a/files/en-us/web/api/navigationtransition/finished/index.md b/files/en-us/web/api/navigationtransition/finished/index.md index 8f35b1f2bac5181..a62be69cc121bd1 100644 --- a/files/en-us/web/api/navigationtransition/finished/index.md +++ b/files/en-us/web/api/navigationtransition/finished/index.md @@ -30,9 +30,11 @@ A {{jsxref("Promise")}} that resolves to `undefined`. ## Examples ```js -await navigation.transition.finished; -// Navigation has completed successfully -// Cleanup any ongoing monitoring +async function cleanupNavigation() { + await navigation.transition.finished; + // Navigation has completed successfully + // Cleanup any ongoing monitoring +} ``` ## Specifications diff --git a/files/en-us/web/api/navigationtransition/index.md b/files/en-us/web/api/navigationtransition/index.md index 95e8243a68855f1..fadea7e483b4f74 100644 --- a/files/en-us/web/api/navigationtransition/index.md +++ b/files/en-us/web/api/navigationtransition/index.md @@ -19,7 +19,7 @@ browser-compat: api.NavigationTransition {{APIRef("Navigation API")}}{{seecompattable}} -The **`NavigationTransition`** interface of the {{domxref("Navigation API")}} represents an ongoing navigation, that is, a navigation that hasn't yet reached the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} or {{domxref("Navigation/navigateerror_event", "navigateerror")}} stage. +The **`NavigationTransition`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} represents an ongoing navigation, that is, a navigation that hasn't yet reached the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} or {{domxref("Navigation/navigateerror_event", "navigateerror")}} stage. It is accessed via the {{domxref("Navigation.transition")}} property. @@ -37,9 +37,11 @@ It is accessed via the {{domxref("Navigation.transition")}} property. ## Examples ```js -await navigation.transition.finished; -// Navigation has completed successfully -// Cleanup any ongoing monitoring +async function cleanupNavigation() { + await navigation.transition.finished; + // Navigation has completed successfully + // Cleanup any ongoing monitoring +} ``` ## Specifications From 03efe1e4518d82ba9ae8485eb036b5460ae2008b Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:25:35 +0000 Subject: [PATCH 27/50] Update files/en-us/web/api/navigation/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation/index.md b/files/en-us/web/api/navigation/index.md index 1ddcc00109bf3c7..4edd8bad7f90a04 100644 --- a/files/en-us/web/api/navigation/index.md +++ b/files/en-us/web/api/navigation/index.md @@ -61,7 +61,7 @@ _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("Navigation.reload", "reload()")}} - : Reloads the current URL, updating any provided state in the history entries list. - {{domxref("Navigation.traverseTo", "traverseTo()")}} - - : Navigates to a specific {{domxref("NavigationHistoryEntry")}} by {{domxref("NavigationHistoryEntry.key", "key")}}. + - : Navigates to a specific {{domxref("NavigationHistoryEntry")}} identified by {{domxref("NavigationHistoryEntry.key", "key")}}. - {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}} - : Updates the state of the {{domxref("Navigation.currentEntry","currentEntry")}}; used in cases where the state change will be independent from a navigation or reload. From fa2f482ae99415940e3d4043c8a1c2f7b792d214 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:25:53 +0000 Subject: [PATCH 28/50] Update files/en-us/web/api/navigation/updatecurrententry/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/updatecurrententry/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation/updatecurrententry/index.md b/files/en-us/web/api/navigation/updatecurrententry/index.md index 1cad31fe654a02c..5f960c0f7e8a5ce 100644 --- a/files/en-us/web/api/navigation/updatecurrententry/index.md +++ b/files/en-us/web/api/navigation/updatecurrententry/index.md @@ -48,7 +48,7 @@ updateCurrentEntry(options) ## Examples -You could use something like the following to update the open/closed state of a {{htmlelement("details")}} element so that the state can be restored when reloading the page, or navigating back from somewhere else. +You could use something like the following to update the open/closed state of a {{htmlelement("details")}} element so that the state can be restored when reloading the page or navigating back from somewhere else. ```js detailsElem.addEventListener('toggle', () => { From 3bb1bed1f3a8e866d88376b79e7f0506781db928 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:26:06 +0000 Subject: [PATCH 29/50] Update files/en-us/web/api/navigation/updatecurrententry/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/updatecurrententry/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation/updatecurrententry/index.md b/files/en-us/web/api/navigation/updatecurrententry/index.md index 5f960c0f7e8a5ce..7f947665a8f2bf3 100644 --- a/files/en-us/web/api/navigation/updatecurrententry/index.md +++ b/files/en-us/web/api/navigation/updatecurrententry/index.md @@ -39,7 +39,7 @@ updateCurrentEntry(options) ### Return value -`undefined`. +None (`undefined`). ### Exceptions From 251848fe722543b17522da42309c315f28e8fda5 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:26:19 +0000 Subject: [PATCH 30/50] Update files/en-us/web/api/navigation/updatecurrententry/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/updatecurrententry/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/files/en-us/web/api/navigation/updatecurrententry/index.md b/files/en-us/web/api/navigation/updatecurrententry/index.md index 7f947665a8f2bf3..9e679efe1bb87e0 100644 --- a/files/en-us/web/api/navigation/updatecurrententry/index.md +++ b/files/en-us/web/api/navigation/updatecurrententry/index.md @@ -27,6 +27,7 @@ The **`updateCurrentEntry()`** method of the ## Syntax ```js-nolint +updateCurrentEntry() updateCurrentEntry(options) ``` From b16a267facee506540a4e831531f298e6c2803cd Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:27:33 +0000 Subject: [PATCH 31/50] Update files/en-us/web/api/navigation/updatecurrententry/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/updatecurrententry/index.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/files/en-us/web/api/navigation/updatecurrententry/index.md b/files/en-us/web/api/navigation/updatecurrententry/index.md index 9e679efe1bb87e0..a166862b6f55796 100644 --- a/files/en-us/web/api/navigation/updatecurrententry/index.md +++ b/files/en-us/web/api/navigation/updatecurrententry/index.md @@ -20,9 +20,7 @@ browser-compat: api.Navigation.updateCurrentEntry {{APIRef("Navigation API")}}{{seecompattable}} -The **`updateCurrentEntry()`** method of the -{{domxref("Navigation")}} interface updates the `state` of the {{domxref("Navigation.currentEntry","currentEntry")}}; used - in cases where the state change will be independent from a navigation or reload. +The **`updateCurrentEntry()`** method of the {{domxref("Navigation")}} interface updates the `state` of the {{domxref("Navigation.currentEntry","currentEntry")}}; used in cases where the state change will be independent from a navigation or reload. ## Syntax From 127c770c14d8632d50daffefb244f1801c1f85d9 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:27:45 +0000 Subject: [PATCH 32/50] Update files/en-us/web/api/navigation/traverseto/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/traverseto/index.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/files/en-us/web/api/navigation/traverseto/index.md b/files/en-us/web/api/navigation/traverseto/index.md index 2010eaad08c2498..8a93f19c71e167f 100644 --- a/files/en-us/web/api/navigation/traverseto/index.md +++ b/files/en-us/web/api/navigation/traverseto/index.md @@ -40,11 +40,14 @@ traverseTo(key, options) ### Return value -An object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: - -- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. -- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. -- either one of the above promises rejects, meaning that the navigation has failed for some reason. +An object with the following properties: + +- `committed` + - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` + - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. + +Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions From 3761a1df49a393af8589647f02250fad70012b48 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:28:31 +0000 Subject: [PATCH 33/50] Update files/en-us/web/api/navigation/back/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/back/index.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/files/en-us/web/api/navigation/back/index.md b/files/en-us/web/api/navigation/back/index.md index 2da0f19e5ad1298..0d931c31b85ebd8 100644 --- a/files/en-us/web/api/navigation/back/index.md +++ b/files/en-us/web/api/navigation/back/index.md @@ -38,11 +38,14 @@ back(options) ### Return value -An object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: - -- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. -- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. -- either one of the above promises rejects, meaning that the navigation has failed for some reason. +An object with the following properties: + +- `committed` + - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` + - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. + +Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions From 991c81aa8bf601821110bfc9289ed734048307c8 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:29:07 +0000 Subject: [PATCH 34/50] Update files/en-us/web/api/navigation/cangoback/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/cangoback/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation/cangoback/index.md b/files/en-us/web/api/navigation/cangoback/index.md index eff3b34a3136c4c..fda395223d53e4f 100644 --- a/files/en-us/web/api/navigation/cangoback/index.md +++ b/files/en-us/web/api/navigation/cangoback/index.md @@ -29,7 +29,7 @@ and `false` if it is not. ## Value -A boolean value—`true` if it is possible to navigate backwards in the navigation history, `false` if not. +A boolean value: `true` if it is possible to navigate backwards in the navigation history, `false` otherwise. ## Examples From e816cb1d67a2517d0ee109643119ae5167de9d73 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:29:31 +0000 Subject: [PATCH 35/50] Update files/en-us/web/api/navigation/cangoforward/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/cangoforward/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation/cangoforward/index.md b/files/en-us/web/api/navigation/cangoforward/index.md index 54290aeb4060659..dae4d57df47c62a 100644 --- a/files/en-us/web/api/navigation/cangoforward/index.md +++ b/files/en-us/web/api/navigation/cangoforward/index.md @@ -27,7 +27,7 @@ and `false` if it is not. ## Value -A boolean value—`true` if it is possible to navigate forwards in the navigation history, `false` if not. +A boolean value:`true` if it is possible to navigate forwards in the navigation history, `false`otherwise. ## Examples From 9696dbcae78dc8a99592ee55f9d1f303f9742297 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:29:58 +0000 Subject: [PATCH 36/50] Update files/en-us/web/api/navigation/currententry/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/currententry/index.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/files/en-us/web/api/navigation/currententry/index.md b/files/en-us/web/api/navigation/currententry/index.md index 2e54debef6b5183..96c9e732c6431bc 100644 --- a/files/en-us/web/api/navigation/currententry/index.md +++ b/files/en-us/web/api/navigation/currententry/index.md @@ -21,8 +21,7 @@ browser-compat: api.Navigation.currentEntry {{APIRef("Navigation API")}}{{seecompattable}} The **`currentEntry`** read-only property of the -{{domxref("Navigation")}} interface returns a {{domxref("NavigationHistoryEntry")}} object representing the location the user is currently - navigated to right now. +{{domxref("Navigation")}} interface returns a {{domxref("NavigationHistoryEntry")}} object representing the location the user is currently navigated to right now. ## Value From 504f04f695aba915aadce52b543d1fc1dadb32bc Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:30:20 +0000 Subject: [PATCH 37/50] Update files/en-us/web/api/navigation/forward/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/forward/index.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/files/en-us/web/api/navigation/forward/index.md b/files/en-us/web/api/navigation/forward/index.md index 9fc33f43df0fe61..9ba79d5577e6300 100644 --- a/files/en-us/web/api/navigation/forward/index.md +++ b/files/en-us/web/api/navigation/forward/index.md @@ -38,11 +38,14 @@ forward(options) ### Return value -An object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: - -- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. -- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. -- either one of the above promises rejects, meaning that the navigation has failed for some reason. +An object with the following properties: + +- `committed` + - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` + - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. + +Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions From ed352c59044aa7d0687339e2d03ed6f89e328dc3 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:30:41 +0000 Subject: [PATCH 38/50] Update files/en-us/web/api/navigation/navigate/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/navigate/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index 520ee02e9d2c610..93fbad633046043 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -25,6 +25,7 @@ The **`navigate()`** method of the ## Syntax ```js-nolint +navigate(url) navigate(url, options) ``` From b0a10a5fea9e3065acf6478fc4ccfbee1d0180f4 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:32:18 +0000 Subject: [PATCH 39/50] Update files/en-us/web/api/navigation/navigate/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/navigate/index.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index 93fbad633046043..553d524b9cec866 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -47,11 +47,14 @@ navigate(url, options) ### Return value -An object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: - -- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. -- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. -- either one of the above promises rejects, meaning that the navigation has failed for some reason. +An object with the following properties: + +- `committed` + - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` + - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. + +Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions From 5e6be2aca79ceccac79a1121bbb4a9900ac5160b Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:33:23 +0000 Subject: [PATCH 40/50] Update files/en-us/web/api/navigation/navigate/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/navigate/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index 553d524b9cec866..3e00223e03238d1 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -101,7 +101,7 @@ backButtonEl.addEventListener("click", () => { }); ``` -### Usage of info and state +### Using info and state ```js async function navigateHandler() { From 4ad513f184604e57db783eebe3485353d6aa0f34 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:34:19 +0000 Subject: [PATCH 41/50] Update files/en-us/web/api/navigation/reload/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/reload/index.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/files/en-us/web/api/navigation/reload/index.md b/files/en-us/web/api/navigation/reload/index.md index 46818b98e88eef5..d28011cc3855233 100644 --- a/files/en-us/web/api/navigation/reload/index.md +++ b/files/en-us/web/api/navigation/reload/index.md @@ -40,11 +40,14 @@ navigate(options) ### Return value -An object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until: - -- `committed` fulfills, meaning that the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. -- `finished` fulfills, meaning that all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. -- either one of the above promises rejects, meaning that the navigation has failed for some reason. +An object with the following properties: + +- `committed` + - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. +- `finished` + - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. + +Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions From af10131c08a6b4a48b26c4c87ae830e13e2d7fc8 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:34:48 +0000 Subject: [PATCH 42/50] Update files/en-us/web/api/navigation/reload/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/reload/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation/reload/index.md b/files/en-us/web/api/navigation/reload/index.md index d28011cc3855233..d671c255e538c8d 100644 --- a/files/en-us/web/api/navigation/reload/index.md +++ b/files/en-us/web/api/navigation/reload/index.md @@ -55,7 +55,7 @@ None. ## Examples -Usage of info and state +### Using info and state ```js async function handleReload() { From 3b887e330ead2993cf4bb730372068933bdfd12e Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:35:12 +0000 Subject: [PATCH 43/50] Update files/en-us/web/api/navigation/transition/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/transition/index.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/files/en-us/web/api/navigation/transition/index.md b/files/en-us/web/api/navigation/transition/index.md index 776626ab6c8ee2d..96a5df38e8bd34c 100644 --- a/files/en-us/web/api/navigation/transition/index.md +++ b/files/en-us/web/api/navigation/transition/index.md @@ -20,9 +20,7 @@ browser-compat: api.Navigation.transition {{APIRef("Navigation API")}}{{seecompattable}} -The **`transition`** read-only property of the -{{domxref("Navigation")}} interface returns a {{domxref("NavigationTransition")}} object representing the status of an in-progress navigation, - which can be used to track it. +The **`transition`** read-only property of the {{domxref("Navigation")}} interface returns a {{domxref("NavigationTransition")}} object representing the status of an in-progress navigation, which can be used to track it. ## Value From 9c9e8da3f94917e86a74db39c27e75d9cd3d393d Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:36:14 +0000 Subject: [PATCH 44/50] Update files/en-us/web/api/navigation/traverseto/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/traverseto/index.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/files/en-us/web/api/navigation/traverseto/index.md b/files/en-us/web/api/navigation/traverseto/index.md index 8a93f19c71e167f..056aded209c5321 100644 --- a/files/en-us/web/api/navigation/traverseto/index.md +++ b/files/en-us/web/api/navigation/traverseto/index.md @@ -20,8 +20,7 @@ browser-compat: api.Navigation.traverseTo {{APIRef("Navigation API")}}{{seecompattable}} -The **`traverseTo()`** method of the -{{domxref("Navigation")}} interface navigates to a specific {{domxref("NavigationHistoryEntry")}} by {{domxref("NavigationHistoryEntry.key", "key")}}. +The **`traverseTo()`** method of the {{domxref("Navigation")}} interface navigates to the {{domxref("NavigationHistoryEntry")}} identified by the given {{domxref("NavigationHistoryEntry.key", "key")}}. ## Syntax From d1b7e04e0db9f54e082084be0d530188280c0ad0 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:36:49 +0000 Subject: [PATCH 45/50] Update files/en-us/web/api/navigation/traverseto/index.md Co-authored-by: wbamberg --- files/en-us/web/api/navigation/traverseto/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/files/en-us/web/api/navigation/traverseto/index.md b/files/en-us/web/api/navigation/traverseto/index.md index 056aded209c5321..f554d5193ca0d1a 100644 --- a/files/en-us/web/api/navigation/traverseto/index.md +++ b/files/en-us/web/api/navigation/traverseto/index.md @@ -25,6 +25,7 @@ The **`traverseTo()`** method of the {{domxref("Navigation")}} interface navigat ## Syntax ```js-nolint +traverseTo(key) traverseTo(key, options) ``` From 6448d5b98d816a5adc78c1fd72da21cd90482816 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 10 Nov 2022 09:44:28 +0000 Subject: [PATCH 46/50] fixing linter trailing space errors --- files/en-us/web/api/navigation/back/index.md | 2 +- .../web/api/navigation/currententrychange_event/index.md | 8 +++++++- files/en-us/web/api/navigation/forward/index.md | 2 +- files/en-us/web/api/navigation/navigate/index.md | 2 +- files/en-us/web/api/navigation/reload/index.md | 2 +- files/en-us/web/api/navigation/traverseto/index.md | 2 +- 6 files changed, 12 insertions(+), 6 deletions(-) diff --git a/files/en-us/web/api/navigation/back/index.md b/files/en-us/web/api/navigation/back/index.md index 0d931c31b85ebd8..ec046448f940683 100644 --- a/files/en-us/web/api/navigation/back/index.md +++ b/files/en-us/web/api/navigation/back/index.md @@ -44,7 +44,7 @@ An object with the following properties: - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. - + Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions diff --git a/files/en-us/web/api/navigation/currententrychange_event/index.md b/files/en-us/web/api/navigation/currententrychange_event/index.md index 6ac08dd4929f301..f58e866a9e8e76a 100644 --- a/files/en-us/web/api/navigation/currententrychange_event/index.md +++ b/files/en-us/web/api/navigation/currententrychange_event/index.md @@ -23,7 +23,13 @@ browser-compat: api.Navigation.currententrychange_event The **`currententrychange`** event of the {{domxref("Navigation")}} interface is fired when the {{domxref("Navigation.currentEntry")}} has changed. -This event will fire for same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}), replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`), or other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API", "History API", "", "nocode")}}'s {{domxref("History.replaceState()")}}). +This event will fire for: + +- Same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}). + +- Replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`). + +- Other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API", "History API", "", "nocode")}}'s {{domxref("History.replaceState()")}}). This event fires after the navigation is committed, meaning that the visible URL has changed and the {{domxref("NavigationHistoryEntry")}} update has occurred. It is useful for migrating from usage of older API features like the {{domxref("Window/hashchange_event", "hashchange")}} or {{domxref("Window/popstate_event", "popstate")}} events. diff --git a/files/en-us/web/api/navigation/forward/index.md b/files/en-us/web/api/navigation/forward/index.md index 9ba79d5577e6300..f636b270bc56e85 100644 --- a/files/en-us/web/api/navigation/forward/index.md +++ b/files/en-us/web/api/navigation/forward/index.md @@ -44,7 +44,7 @@ An object with the following properties: - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. - + Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index 3e00223e03238d1..95e5f2f0a9a5786 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -53,7 +53,7 @@ An object with the following properties: - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. - + Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions diff --git a/files/en-us/web/api/navigation/reload/index.md b/files/en-us/web/api/navigation/reload/index.md index d671c255e538c8d..796a5c7e1e9672d 100644 --- a/files/en-us/web/api/navigation/reload/index.md +++ b/files/en-us/web/api/navigation/reload/index.md @@ -46,7 +46,7 @@ An object with the following properties: - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. - + Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions diff --git a/files/en-us/web/api/navigation/traverseto/index.md b/files/en-us/web/api/navigation/traverseto/index.md index f554d5193ca0d1a..1f11eedc5d18b44 100644 --- a/files/en-us/web/api/navigation/traverseto/index.md +++ b/files/en-us/web/api/navigation/traverseto/index.md @@ -46,7 +46,7 @@ An object with the following properties: - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. - + Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions From f4b5752830fdabf9bc3d84858ace36cf9999dbb9 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Mon, 14 Nov 2022 07:14:35 +0000 Subject: [PATCH 47/50] add structured-clonable information to navigate() --- files/en-us/web/api/navigation/navigate/index.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index 95e5f2f0a9a5786..6cc6715e1b5325d 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -36,7 +36,7 @@ navigate(url, options) - `options` {{optional_inline}} - : An options object containing the following properties: - `state` - - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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. + - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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-clonable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - `info` - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("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`. - `history` @@ -58,6 +58,8 @@ Either one of these promises rejects if the navigation has failed for some reaso ### Exceptions +- `DataCloneError` {{domxref("DOMException")}} + - : Thrown if the `state` parameter had values included in it that are not structured-clonable. - `SyntaxError` {{domxref("DOMException")}} - : Thrown if the `url` parameter is not a valid URL. - `NotSupportedError` {{domxref("DOMException")}} From 7f81b8b0aa17ebaea7d27ba9f89b419f22caff3f Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 15 Nov 2022 16:22:03 +0000 Subject: [PATCH 48/50] add structured-clonable information to reload() and updateCurrentEntry() --- files/en-us/web/api/navigation/reload/index.md | 5 +++-- files/en-us/web/api/navigation/updatecurrententry/index.md | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/files/en-us/web/api/navigation/reload/index.md b/files/en-us/web/api/navigation/reload/index.md index 796a5c7e1e9672d..858cf864297456b 100644 --- a/files/en-us/web/api/navigation/reload/index.md +++ b/files/en-us/web/api/navigation/reload/index.md @@ -34,7 +34,7 @@ navigate(options) - `options` {{optional_inline}} - : An options object containing the following properties: - `state` - - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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. + - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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-clonable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - `info` - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("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`. @@ -51,7 +51,8 @@ Either one of these promises rejects if the navigation has failed for some reaso ### Exceptions -None. +- `DataCloneError` {{domxref("DOMException")}} + - : Thrown if the `state` parameter had values included in it that are not structured-clonable. ## Examples diff --git a/files/en-us/web/api/navigation/updatecurrententry/index.md b/files/en-us/web/api/navigation/updatecurrententry/index.md index a166862b6f55796..787cebff0107fd0 100644 --- a/files/en-us/web/api/navigation/updatecurrententry/index.md +++ b/files/en-us/web/api/navigation/updatecurrententry/index.md @@ -34,7 +34,7 @@ updateCurrentEntry(options) - `options` {{optional_inline}} - : An options object containing the following properties: - `state` - - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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. + - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "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-clonable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). ### Return value @@ -42,6 +42,8 @@ None (`undefined`). ### Exceptions +- `DataCloneError` {{domxref("DOMException")}} + - : Thrown if the `state` parameter had values included in it that are not structured-clonable. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("Navigation.currentEntry")}} is `null`, i.e. there is no current history entry. This could occur for exaple if the current page is `about:blank`. From 14766519fce19ced063f57b5d5f08d7702ac9eee Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 16 Nov 2022 16:26:06 +0000 Subject: [PATCH 49/50] making fixes in response to wbamberg navigationhistoryentry comments --- .../web/api/navigation/currententry/index.md | 23 +++++++++++--- .../web/api/navigation/navigate/index.md | 23 +++++++++++--- .../web/api/navigation/traverseto/index.md | 23 +++++++++++--- .../navigationhistoryentry/getstate/index.md | 10 ++++-- .../api/navigationhistoryentry/id/index.md | 8 +++-- .../web/api/navigationhistoryentry/index.md | 31 +++++++++++++------ .../api/navigationhistoryentry/index/index.md | 4 +-- .../api/navigationhistoryentry/key/index.md | 29 ++++++++++++----- 8 files changed, 113 insertions(+), 38 deletions(-) diff --git a/files/en-us/web/api/navigation/currententry/index.md b/files/en-us/web/api/navigation/currententry/index.md index 96c9e732c6431bc..9d14b4cba756844 100644 --- a/files/en-us/web/api/navigation/currententry/index.md +++ b/files/en-us/web/api/navigation/currententry/index.md @@ -30,16 +30,29 @@ A {{domxref("NavigationHistoryEntry")}} object. ## Examples ```js -async function initHomeBtn() { - // Get the key of the first loaded page - // so the user can always go back there. +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); + backToHomeButton.onclick = () => { + navigation.traverseTo(key); + } } +navigation.addEventListener("navigate", event => { + event.intercept({ + async handler() { + // Handle single-page navigations + } + }); +}); + async function handleNavigate(url) { - // Navigate away, but the button will always work. + + // Navigate to a different view, but the button will always work. await navigation.navigate(url).finished; + + // ... } ``` diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index 6cc6715e1b5325d..c7229c2144bde4b 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -74,16 +74,29 @@ Either one of these promises rejects if the navigation has failed for some reaso ### Set up home button ```js -async function initHomeBtn() { - // Get the key of the first loaded page - // so the user can always go back there. +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); + backToHomeButton.onclick = () => { + navigation.traverseTo(key); + } } +navigation.addEventListener("navigate", event => { + event.intercept({ + async handler() { + // Handle single-page navigations + } + }); +}); + async function handleNavigate(url) { - // Navigate away, but the button will always work. + + // Navigate to a different view, but the button will always work. await navigation.navigate(url).finished; + + // ... } ``` diff --git a/files/en-us/web/api/navigation/traverseto/index.md b/files/en-us/web/api/navigation/traverseto/index.md index 1f11eedc5d18b44..a2ef039b9602e17 100644 --- a/files/en-us/web/api/navigation/traverseto/index.md +++ b/files/en-us/web/api/navigation/traverseto/index.md @@ -59,16 +59,29 @@ Either one of these promises rejects if the navigation has failed for some reaso ### Set up home button ```js -async function initHomeBtn() { - // Get the key of the first loaded page - // so the user can always go back there. +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); + backToHomeButton.onclick = () => { + navigation.traverseTo(key); + } } +navigation.addEventListener("navigate", event => { + event.intercept({ + async handler() { + // Handle single-page navigations + } + }); +}); + async function handleNavigate(url) { - // Navigate away, but the button will always work. + + // Navigate to a different view, but the button will always work. await navigation.navigate(url).finished; + + // ... } ``` diff --git a/files/en-us/web/api/navigationhistoryentry/getstate/index.md b/files/en-us/web/api/navigationhistoryentry/getstate/index.md index 22d99de53c66c61..2aac6339207679c 100644 --- a/files/en-us/web/api/navigationhistoryentry/getstate/index.md +++ b/files/en-us/web/api/navigationhistoryentry/getstate/index.md @@ -46,8 +46,14 @@ None. ## Examples ```js -let current = navigation.currentEntry; -console.log(current.getState()); +async function handleReload() { + // Update existing state via reload() + await navigation.reload({ state: { ...navigation.currentEntry.getState(), newState: 3 } }); + + // Print current state to the console + const current = navigation.currentEntry; + console.log(current.getState()); +} ``` ## Specifications diff --git a/files/en-us/web/api/navigationhistoryentry/id/index.md b/files/en-us/web/api/navigationhistoryentry/id/index.md index 9dae8926bcde3f6..dc5bb7e5bb88640 100644 --- a/files/en-us/web/api/navigationhistoryentry/id/index.md +++ b/files/en-us/web/api/navigationhistoryentry/id/index.md @@ -21,16 +21,18 @@ browser-compat: api.NavigationHistoryEntry.id {{APIRef("Navigation API")}}{{seecompattable}} The **`id`** read-only property of the -{{domxref("NavigationHistoryEntry")}} interface returns the `id` of the history entry. This is a unique, UA-generated value that always represents the history entry, useful to correlate a history entry with an external resource such as a storage cache. +{{domxref("NavigationHistoryEntry")}} interface returns the `id` of the history entry. This is a unique, UA-generated value that always represents a specific history entry, useful to correlate it with an external resource such as a storage cache. + +This differs from the {{domxref("NavigationHistoryEntry.key", "key")}} of a history entry. The `key` is a unique, UA-generated value that represents the history entry's slot in the entries list rather than the entry itself. It is used to navigate that particular slot via {{domxref("Navigation.traverseTo()")}}. The `key` will be reused by other entries that replace the entry in the list (that is, if the {{domxref("NavigateEvent.navigationType")}} is `replace`). ## Value -A string representing the `id` of the destination {{domxref("NavigationHistoryEntry")}}. +A string representing the `id` of the {{domxref("NavigationHistoryEntry")}}. ## Examples ```js -let current = navigation.currentEntry; +const current = navigation.currentEntry; console.log(current.id); ``` diff --git a/files/en-us/web/api/navigationhistoryentry/index.md b/files/en-us/web/api/navigationhistoryentry/index.md index a343b9a79bb8d91..be53a5bd80b0dc6 100644 --- a/files/en-us/web/api/navigationhistoryentry/index.md +++ b/files/en-us/web/api/navigationhistoryentry/index.md @@ -23,7 +23,7 @@ The **`NavigationHistoryEntry`** interface of the {{domxref("Navigation API", "N These objects are commonly accessed via the {{domxref("Navigation.currentEntry")}} property and {{domxref("Navigation.entries()")}} method. -The Navigation API only exposes history entries created directly by the application (i.e. not {{htmlelement("iframe")}} navigations or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than the older {{domxref("History API", "History API", "", "nocode")}}. +The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded {{htmlelement("iframe")}}s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older {{domxref("History API", "History API", "", "nocode")}}. {{InheritanceDiagram}} @@ -32,11 +32,11 @@ The Navigation API only exposes history entries created directly by the applicat _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("NavigationHistoryEntry.id", "id")}} {{ReadOnlyInline}} - - : Returns the `id` of the history entry. This is a unique, UA-generated value that always represents the history entry, useful to correlate a history entry with an external resource such as a storage cache. + - : Returns the `id` of the history entry. This is a unique, UA-generated value that always represents a specific history entry, useful to correlate it with an external resource such as a storage cache. - {{domxref("NavigationHistoryEntry.index", "index")}} {{ReadOnlyInline}} - - : Returns the index of the history entry in the history entries list (i.e. returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list. + - : Returns the index of the history entry in the history entries list (that is, the list returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list. - {{domxref("NavigationHistoryEntry.key", "key")}} {{ReadOnlyInline}} - - : Returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the history entries list, used to navigate to this place in the history via {{domxref("Navigation.traverseTo()")}}. It will be reused by other entries that replace the entry in the list (i.e. if the {{domxref("NavigateEvent.navigationType")}} is `replace`). + - : Returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the entries list rather than the entry itself. It is used to navigate that particular slot via {{domxref("Navigation.traverseTo()")}}. The `key` will be reused by other entries that replace the entry in the list (that is, if the {{domxref("NavigateEvent.navigationType")}} is `replace`). - {{domxref("NavigationHistoryEntry.sameDocument", "sameDocument")}} {{ReadOnlyInline}} - : Returns `true` if this history entry is for the same `document` as the current {{domxref("Document")}} value, or `false` otherwise. - {{domxref("NavigationHistoryEntry.url", "url")}} {{ReadOnlyInline}} @@ -57,16 +57,29 @@ _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ ## Examples ```js -async function initHomeBtn() { - // Get the key of the first loaded page - // so the user can always go back there. +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); + backToHomeButton.onclick = () => { + navigation.traverseTo(key); + } } +navigation.addEventListener("navigate", event => { + event.intercept({ + async handler() { + // Handle single-page navigations + } + }); +}); + async function handleNavigate(url) { - // Navigate away, but the button will always work. + + // Navigate to a different view, but the button will always work. await navigation.navigate(url).finished; + + // ... } ``` diff --git a/files/en-us/web/api/navigationhistoryentry/index/index.md b/files/en-us/web/api/navigationhistoryentry/index/index.md index c1921f0d1a3b2da..5e9139d1dab20be 100644 --- a/files/en-us/web/api/navigationhistoryentry/index/index.md +++ b/files/en-us/web/api/navigationhistoryentry/index/index.md @@ -21,11 +21,11 @@ browser-compat: api.NavigationHistoryEntry.index {{APIRef("Navigation API")}}{{seecompattable}} The **`index`** read-only property of the -{{domxref("NavigationHistoryEntry")}} interface returns the index of the history entry in the history entries list (i.e. returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list. +{{domxref("NavigationHistoryEntry")}} interface returns the index of the history entry in the history entries list (that is, the list returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list. ## Value -A number representing the `index` of the destination {{domxref("NavigationHistoryEntry")}}, or `-1`. +A number representing the `index` of the entry in the history entries list, or `-1` if this item does not appear in the list. ## Examples diff --git a/files/en-us/web/api/navigationhistoryentry/key/index.md b/files/en-us/web/api/navigationhistoryentry/key/index.md index 74d28997316e77c..14499dfbb790249 100644 --- a/files/en-us/web/api/navigationhistoryentry/key/index.md +++ b/files/en-us/web/api/navigationhistoryentry/key/index.md @@ -21,11 +21,13 @@ browser-compat: api.NavigationHistoryEntry.key {{APIRef("Navigation API")}}{{seecompattable}} The **`key`** read-only property of the -{{domxref("NavigationHistoryEntry")}} interface returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the history entries list, used to navigate to this place in the history via {{domxref("Navigation.traverseTo()")}}. It will be reused by other entries that replace the entry in the list (i.e. if the {{domxref("NavigateEvent.navigationType")}} is `replace`). +{{domxref("NavigationHistoryEntry")}} interface returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the entries list. It is used to navigate that particular slot via {{domxref("Navigation.traverseTo()")}}. The `key` will be reused by other entries that replace the entry in the list (that is, if the {{domxref("NavigateEvent.navigationType")}} is `replace`). + +This differs from the {{domxref("NavigationHistoryEntry.id", "id")}} of a history entry. The `id` is a unique, UA-generated value that always represents a specific history entry rather than its slot in the entries list. This is useful to correlate it with an external resource such as a storage cache. ## Value -A string representing the `key` of the destination {{domxref("NavigationHistoryEntry")}}. +A string representing the `key` of the {{domxref("NavigationHistoryEntry")}}. ## Examples @@ -39,16 +41,29 @@ console.log(current.key); ### Set up a home button ```js -async function initHomeBtn() { - // Get the key of the first loaded page - // so the user can always go back there. +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); + backToHomeButton.onclick = () => { + navigation.traverseTo(key); + } } +navigation.addEventListener("navigate", event => { + event.intercept({ + async handler() { + // Handle single-page navigations + } + }); +}); + async function handleNavigate(url) { - // Navigate away, but the button will always work. + + // Navigate to a different view, but the button will always work. await navigation.navigate(url).finished; + + // ... } ``` From 18056066aa60b15466ced9ac7a58a0a9757b3fa0 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Sun, 20 Nov 2022 09:23:24 +0000 Subject: [PATCH 50/50] moooooar fixes for wbamberg comments --- .../api/navigateevent/canintercept/index.md | 11 ++++++++++- .../web/api/navigateevent/formdata/index.md | 2 +- files/en-us/web/api/navigateevent/index.md | 5 ++++- .../en-us/web/api/navigateevent/info/index.md | 3 ++- .../web/api/navigateevent/intercept/index.md | 19 ++++++++++++++----- .../web/api/navigateevent/scroll/index.md | 3 +++ .../web/api/navigateevent/signal/index.md | 2 +- .../web/api/navigation/currententry/index.md | 14 ++++---------- .../web/api/navigation/navigate/index.md | 14 ++++---------- .../api/navigation/navigate_event/index.md | 5 ++++- .../web/api/navigation/traverseto/index.md | 14 ++++---------- files/en-us/web/api/navigation_api/index.md | 5 ++++- .../navigationdestination/getstate/index.md | 3 ++- .../dispose_event/index.md | 2 +- .../navigationhistoryentry/getstate/index.md | 5 +++-- .../web/api/navigationhistoryentry/index.md | 14 ++++---------- .../api/navigationhistoryentry/index/index.md | 2 +- .../api/navigationhistoryentry/key/index.md | 18 ++++++------------ .../samedocument/index.md | 2 +- .../api/navigationhistoryentry/url/index.md | 2 +- 20 files changed, 74 insertions(+), 71 deletions(-) diff --git a/files/en-us/web/api/navigateevent/canintercept/index.md b/files/en-us/web/api/navigateevent/canintercept/index.md index e230e326d1ba301..c3a742cc5984391 100644 --- a/files/en-us/web/api/navigateevent/canintercept/index.md +++ b/files/en-us/web/api/navigateevent/canintercept/index.md @@ -22,7 +22,16 @@ browser-compat: api.NavigateEvent.canIntercept {{APIRef("Navigation API")}}{{seecompattable}} The **`canIntercept`** read-only property of the -{{domxref("NavigateEvent")}} interface returns `true` if the navigation can be intercepted, or `false` otherwise (e.g. you can't intercept a cross-origin navigation). +{{domxref("NavigateEvent")}} interface returns `true` if the navigation can be intercepted and have its URL rewritten, or `false` otherwise + +There are several rules around when a navigation can be intercepted. For example: + +- You can't intercept cross-origin navigations. +- You can intercept `http` or `https` URLs if only the `path`, `query`, and `fragment` portions of the new URL differ from the current URL. +- You can intercept `file` URLs if only the `query` and `fragment` portions of the new URL differ. +- For other URL types you can intercept the navigation if only the `fragment` portion differs. + +See the spec for more explanation on [when a Document can have its URL rewritten](https://html.spec.whatwg.org/multipage/nav-history-apis.html#can-have-its-url-rewritten), including a table of examples. ## Value diff --git a/files/en-us/web/api/navigateevent/formdata/index.md b/files/en-us/web/api/navigateevent/formdata/index.md index 700bf282b07b142..f8aa3602366afac 100644 --- a/files/en-us/web/api/navigateevent/formdata/index.md +++ b/files/en-us/web/api/navigateevent/formdata/index.md @@ -22,7 +22,7 @@ browser-compat: api.NavigateEvent.formData {{APIRef("Navigation API")}}{{seecompattable}} The **`formData`** read-only property of the -{{domxref("NavigateEvent")}} interface returns the {{domxref("FormData")}} object representing the submitted data in the case of a `POST` form submission, or `null` otherwise. +{{domxref("NavigateEvent")}} interface returns the {{domxref("FormData")}} object representing the submitted data in the case of a [`POST`](/en-US/docs/Web/HTTP/Methods/POST) form submission, or `null` otherwise. ## Value diff --git a/files/en-us/web/api/navigateevent/index.md b/files/en-us/web/api/navigateevent/index.md index 6e289d6ba5f22fe..4e7c44bf7ebb331 100644 --- a/files/en-us/web/api/navigateevent/index.md +++ b/files/en-us/web/api/navigateevent/index.md @@ -88,10 +88,12 @@ navigation.addEventListener('navigate', event => { }); ``` -> **Note:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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. +> **Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("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 {{domxref("NavigateEvent.scroll", "scroll()")}} call between the two. + ```js navigation.addEventListener('navigate', event => { if (shouldNotIntercept(navigateEvent)) return; @@ -102,6 +104,7 @@ navigation.addEventListener('navigate', event => { async handler() { const articleContent = await getArticleContent(url.pathname); renderArticlePage(articleContent); + event.scroll(); const secondaryContent = await getSecondaryContent(url.pathname); diff --git a/files/en-us/web/api/navigateevent/info/index.md b/files/en-us/web/api/navigateevent/info/index.md index c73a6ec75aea58f..072b647d1b94c65 100644 --- a/files/en-us/web/api/navigateevent/info/index.md +++ b/files/en-us/web/api/navigateevent/info/index.md @@ -26,7 +26,7 @@ The **`info`** read-only property of the ## Value -Any data type representing the `info` value, or `false` if none was passed. +The `info` value passed by the initiating navigation operation, or `undefined` if none was passed. ## Examples @@ -70,3 +70,4 @@ navigation.addEventListener("navigate", (event) => { - [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) - [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) - Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) +- Methods that allow info to be passed — {{domxref("Navigation.back()")}}, {{domxref("Navigation.forward()")}}, {{domxref("Navigation.navigate()")}}, {{domxref("Navigation.reload()")}}, and {{domxref("Navigation.traverseTo()")}} diff --git a/files/en-us/web/api/navigateevent/intercept/index.md b/files/en-us/web/api/navigateevent/intercept/index.md index 244cc78fd96dc4c..7776033fa511a55 100644 --- a/files/en-us/web/api/navigateevent/intercept/index.md +++ b/files/en-us/web/api/navigateevent/intercept/index.md @@ -26,6 +26,7 @@ The **`intercept()`** method of the ## Syntax ```js-nolint +intercept() intercept(options) ``` @@ -35,14 +36,22 @@ intercept(options) - : An options object containing the following properties: - `handler` - : A callback function that defines what the navigation handling behavior should be. This generally handles resource fetching, and returns a promise. - - `focusReset` - - : Defines the navigation's focus behavior. Once the promise returned by your handler function resolves, by default the browser will focus the first element with the {{htmlattrxref("autofocus")}} attribute, or the {{htmlelement("body")}} element if no element has `autofocus` set. You can turn this behavior off setting `focusReset` to `manual`. The other available value is `after-transition`, which is the default. - - `scroll` - - : Defines the navigation's focus behavior. By default the browser will handle scrolling, for example by scrolling to the relevant fragment identifier if the URL contains a fragment, or restoring the scroll position to the same place as last time if the page is reloaded or page in the history is revisited. You can turn this behavior off setting `scroll` to `manual`. The other available value is `after-transition`, which is the default. + - `focusReset` {{optional_inline}} + - : Defines the navigation's focus behavior. This may take one of the following values: + - `after-transition` + - : Once the promise returned by your handler function resolves, the browser will focus the first element with the [`autofocus`](/en-US/docs/Web/HTML/Global_attributes/autofocus) attribute, or the {{htmlelement("body")}} element if no element has `autofocus` set. This is the default value. + - `manual` + - : Disable the default behavior. + - `scroll` {{optional_inline}} + - : Defines the navigation's scrolling behavior. This may take one of the following values: + - `after-transition` + - : Allow the browser to handle scrolling, for example by scrolling to the relevant fragment identifier if the URL contains a fragment, or restoring the scroll position to the same place as last time if the page is reloaded or a page in the history is revisited. This is the default value. + - `manual` + - : Disable the default behavior. ### Return value -`undefined`. +None (`undefined`). ### Exceptions diff --git a/files/en-us/web/api/navigateevent/scroll/index.md b/files/en-us/web/api/navigateevent/scroll/index.md index 74eb073d3aab273..57822caedc55ee7 100644 --- a/files/en-us/web/api/navigateevent/scroll/index.md +++ b/files/en-us/web/api/navigateevent/scroll/index.md @@ -45,6 +45,8 @@ None. ### 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 {{domxref("NavigateEvent.scroll", "scroll()")}} call between the two. + ```js navigation.addEventListener('navigate', (event) => { if (shouldNotIntercept(navigateEvent)) { @@ -57,6 +59,7 @@ navigation.addEventListener('navigate', (event) => { async handler() { const articleContent = await getArticleContent(url.pathname); renderArticlePage(articleContent); + event.scroll(); const secondaryContent = await getSecondaryContent(url.pathname); diff --git a/files/en-us/web/api/navigateevent/signal/index.md b/files/en-us/web/api/navigateevent/signal/index.md index a2c48693cb9afc1..47d0f63020f16dd 100644 --- a/files/en-us/web/api/navigateevent/signal/index.md +++ b/files/en-us/web/api/navigateevent/signal/index.md @@ -30,7 +30,7 @@ An {{domxref("AbortSignal")}} object. ## Examples -The general idea here is that the `signal` property can be passed to an associated {{domxref("fetch()")}} operation so that if the navigation is cancelled, it can be safely aborted, avoiding wasting bandwidth on fetches that are no longer needed. +The general idea here is that the `signal` property can be passed to an associated {{domxref("fetch()")}} operation so that if the navigation is cancelled, the `fetch()` operation can be safely aborted, avoiding wasting bandwidth on fetches that are no longer needed. ```js navigation.addEventListener("navigate", (event) => { diff --git a/files/en-us/web/api/navigation/currententry/index.md b/files/en-us/web/api/navigation/currententry/index.md index 9d14b4cba756844..c6f04e3fde8ab0c 100644 --- a/files/en-us/web/api/navigation/currententry/index.md +++ b/files/en-us/web/api/navigation/currententry/index.md @@ -38,22 +38,16 @@ function initHomeBtn() { 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() { - // Handle single-page navigations + // Navigate to a different view, + // but the "home" button will always work. } }); }); - -async function handleNavigate(url) { - - // Navigate to a different view, but the button will always work. - await navigation.navigate(url).finished; - - // ... -} ``` ## Specifications diff --git a/files/en-us/web/api/navigation/navigate/index.md b/files/en-us/web/api/navigation/navigate/index.md index c7229c2144bde4b..91831bf94b245ce 100644 --- a/files/en-us/web/api/navigation/navigate/index.md +++ b/files/en-us/web/api/navigation/navigate/index.md @@ -82,22 +82,16 @@ function initHomeBtn() { 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() { - // Handle single-page navigations + // Navigate to a different view, + // but the "home" button will always work. } }); }); - -async function handleNavigate(url) { - - // Navigate to a different view, but the button will always work. - await navigation.navigate(url).finished; - - // ... -} ``` ### A smart back button diff --git a/files/en-us/web/api/navigation/navigate_event/index.md b/files/en-us/web/api/navigation/navigate_event/index.md index 943d7d34761f998..579d11a324c4d59 100644 --- a/files/en-us/web/api/navigation/navigate_event/index.md +++ b/files/en-us/web/api/navigation/navigate_event/index.md @@ -68,10 +68,12 @@ navigation.addEventListener('navigate', (event) => { }); ``` -> **Note:** Previous to the Navigation API being available, to do something similar you'd have to listen for all click events on links, run `event.preventDefault()`, perform the appropriate {{domxref("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. +> **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 {{domxref("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 {{domxref("NavigateEvent.scroll", "scroll()")}} call between the two. + ```js navigation.addEventListener('navigate', (event) => { if (shouldNotIntercept(navigateEvent)) { @@ -84,6 +86,7 @@ navigation.addEventListener('navigate', (event) => { async handler() { const articleContent = await getArticleContent(url.pathname); renderArticlePage(articleContent); + event.scroll(); const secondaryContent = await getSecondaryContent(url.pathname); diff --git a/files/en-us/web/api/navigation/traverseto/index.md b/files/en-us/web/api/navigation/traverseto/index.md index a2ef039b9602e17..d27ec98717f6c37 100644 --- a/files/en-us/web/api/navigation/traverseto/index.md +++ b/files/en-us/web/api/navigation/traverseto/index.md @@ -67,22 +67,16 @@ function initHomeBtn() { 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() { - // Handle single-page navigations + // Navigate to a different view, + // but the "home" button will always work. } }); }); - -async function handleNavigate(url) { - - // Navigate to a different view, but the button will always work. - await navigation.navigate(url).finished; - - // ... -} ``` ## Specifications diff --git a/files/en-us/web/api/navigation_api/index.md b/files/en-us/web/api/navigation_api/index.md index fefe3140aa86115..d95f4dc230e2bd4 100644 --- a/files/en-us/web/api/navigation_api/index.md +++ b/files/en-us/web/api/navigation_api/index.md @@ -82,7 +82,7 @@ In some cases however, a state change will be independent from a navigation or r There are a few perceived limitations with the Navigation API: -1. The current specification doesn't trigger {{domxref("Navigation.navigate_event", "navigate")}} on a page's first load. This might be fine for sites that use Server Side Rendering (SSR)—your server could return the correct initial state, which is the fastest way to get content to your users. But sites that leverage client-side code to create their pages may need an additional function to initialize the page. +1. The current specification doesn't trigger a {{domxref("Navigation.navigate_event", "navigate")}} event on a page's first load. This might be fine for sites that use Server Side Rendering (SSR)—your server could return the correct initial state, which is the fastest way to get content to your users. But sites that leverage client-side code to create their pages may need an additional function to initialize the page. 2. The Navigation API operates only within a single frame—the top-level page, or a single specific {{htmlelement("iframe")}}. This has some interesting implications that are [further documented in the spec](https://github.com/WICG/navigation-api#warning-backforward-are-not-always-opposites), but in practice, will reduce developer confusion. The previous {{domxref("History API", "History API", "", "nocode")}} has several confusing edge cases, like support for frames, which the Navigation API handles up-front. 3. You can't currently use the Navigation API to programmatically modify or rearrange the history list. It might be useful to have a temporary state, for example navigating the user to a temporary modal that asks them for some information, then going back to the previous URL. In this case, you'd want to delete the temporary modal navigation entry so the user cannot mess up the application flow by hitting the forward button and opening it again. @@ -140,6 +140,8 @@ navigation.addEventListener('navigate', (event) => { ### 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 {{domxref("NavigateEvent.scroll", "scroll()")}} call between the two. + ```js navigation.addEventListener('navigate', (event) => { if (shouldNotIntercept(event)) { @@ -152,6 +154,7 @@ navigation.addEventListener('navigate', (event) => { async handler() { const articleContent = await getArticleContent(url.pathname); renderArticlePage(articleContent); + event.scroll(); const secondaryContent = await getSecondaryContent(url.pathname); diff --git a/files/en-us/web/api/navigationdestination/getstate/index.md b/files/en-us/web/api/navigationdestination/getstate/index.md index 8407adbac9e52e4..db54e6e0ac2d1aa 100644 --- a/files/en-us/web/api/navigationdestination/getstate/index.md +++ b/files/en-us/web/api/navigationdestination/getstate/index.md @@ -21,7 +21,7 @@ browser-compat: api.NavigationDestination.getState {{APIRef("Navigation API")}}{{seecompattable}} The **`getState()`** method of the -{{domxref("NavigationDestination")}} interface returns a clone of the available state associated with the destination {{domxref("NavigationHistoryEntry")}}, or navigation operation (e.g. {{domxref("Navigation.navigate()", "navigate()")}}) as appropriate. +{{domxref("NavigationDestination")}} interface returns a clone of the developer-supplied state associated with the destination {{domxref("NavigationHistoryEntry")}}, or navigation operation (e.g. {{domxref("Navigation.navigate()", "navigate()")}}) as appropriate. ## Syntax @@ -64,3 +64,4 @@ navigation.addEventListener('navigate', (event) => { - [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) - [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) - Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) +- Methods that allow state to be updated — {{domxref("Navigation.navigate()")}}, {{domxref("Navigation.reload()")}}, and {{domxref("Navigation.updateCurrentEntry()")}} diff --git a/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md b/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md index 8de4df1c1a94a26..1d3cb6091540cb7 100644 --- a/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md +++ b/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md @@ -28,7 +28,7 @@ Disposal occurs when: - Forward history entries are cleared. See the example at [Notifications on entry disposal](https://github.com/wicg/navigation-api#notifications-on-entry-disposal) for more information. - The user clears their browser history using settings or provided UI controls. -- The 50-page history limit is exceeded. This is not specified anywhere, but it is widely implemented. See the discussion in [How to Manipulate history.length and set it to more than 50](https://stackoverflow.com/questions/25275418/how-to-manipulate-history-length-and-set-it-to-more-than-50). +- The history limit is exceeded. This is not specified anywhere, but browsers tend to have a history limit of 50 pages. ## Syntax diff --git a/files/en-us/web/api/navigationhistoryentry/getstate/index.md b/files/en-us/web/api/navigationhistoryentry/getstate/index.md index 2aac6339207679c..62b6a009f96d0c4 100644 --- a/files/en-us/web/api/navigationhistoryentry/getstate/index.md +++ b/files/en-us/web/api/navigationhistoryentry/getstate/index.md @@ -21,7 +21,7 @@ browser-compat: api.NavigationHistoryEntry.getState {{APIRef("Navigation API")}}{{seecompattable}} The **`getState()`** method of the -{{domxref("NavigationHistoryEntry")}} interface returns a clone of the available state associated with this history entry. +{{domxref("NavigationHistoryEntry")}} interface returns a clone of the developer-supplied state associated with this history entry. ## Syntax @@ -35,7 +35,7 @@ None. ### Return value -A value representing the state. This can be any type. +A value representing the state. This can be any [structured-clonable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) data type. If no state is defined, it returns `undefined`. @@ -69,3 +69,4 @@ async function handleReload() { - [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/) - [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md) - Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/) +- Methods that allow state to be updated — {{domxref("Navigation.navigate()")}}, {{domxref("Navigation.reload()")}}, and {{domxref("Navigation.updateCurrentEntry()")}} diff --git a/files/en-us/web/api/navigationhistoryentry/index.md b/files/en-us/web/api/navigationhistoryentry/index.md index be53a5bd80b0dc6..eff0a5350facc5f 100644 --- a/files/en-us/web/api/navigationhistoryentry/index.md +++ b/files/en-us/web/api/navigationhistoryentry/index.md @@ -65,22 +65,16 @@ function initHomeBtn() { 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() { - // Handle single-page navigations + // Navigate to a different view, + // but the "home" button will always work. } }); }); - -async function handleNavigate(url) { - - // Navigate to a different view, but the button will always work. - await navigation.navigate(url).finished; - - // ... -} ``` ## Specifications diff --git a/files/en-us/web/api/navigationhistoryentry/index/index.md b/files/en-us/web/api/navigationhistoryentry/index/index.md index 5e9139d1dab20be..c39924594e28ea2 100644 --- a/files/en-us/web/api/navigationhistoryentry/index/index.md +++ b/files/en-us/web/api/navigationhistoryentry/index/index.md @@ -30,7 +30,7 @@ A number representing the `index` of the entry in the history entries list, or ` ## Examples ```js -let current = navigation.currentEntry; +const current = navigation.currentEntry; console.log(current.index); ``` diff --git a/files/en-us/web/api/navigationhistoryentry/key/index.md b/files/en-us/web/api/navigationhistoryentry/key/index.md index 14499dfbb790249..f0654a2d1888190 100644 --- a/files/en-us/web/api/navigationhistoryentry/key/index.md +++ b/files/en-us/web/api/navigationhistoryentry/key/index.md @@ -34,7 +34,7 @@ A string representing the `key` of the {{domxref("NavigationHistoryEntry")}}. ### Basic usage ```js -let current = navigation.currentEntry; +const current = navigation.currentEntry; console.log(current.key); ``` @@ -47,24 +47,18 @@ function initHomeBtn() { 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() { - // Handle single-page navigations + // Navigate to a different view, + // but the "home" button will always work. } }); }); - -async function handleNavigate(url) { - - // Navigate to a different view, but the button will always work. - await navigation.navigate(url).finished; - - // ... -} ``` ## Specifications diff --git a/files/en-us/web/api/navigationhistoryentry/samedocument/index.md b/files/en-us/web/api/navigationhistoryentry/samedocument/index.md index 05a9acb4837c594..4af97ceaeff2526 100644 --- a/files/en-us/web/api/navigationhistoryentry/samedocument/index.md +++ b/files/en-us/web/api/navigationhistoryentry/samedocument/index.md @@ -30,7 +30,7 @@ A boolean. ## Examples ```js -let current = navigation.currentEntry; +const current = navigation.currentEntry; console.log(current.sameDocument); // Will always return true ``` diff --git a/files/en-us/web/api/navigationhistoryentry/url/index.md b/files/en-us/web/api/navigationhistoryentry/url/index.md index 145f6bf6dd446c9..c69694e6edb2f0a 100644 --- a/files/en-us/web/api/navigationhistoryentry/url/index.md +++ b/files/en-us/web/api/navigationhistoryentry/url/index.md @@ -30,7 +30,7 @@ A string representing the URL. ## Examples ```js -let current = navigation.currentEntry; +const current = navigation.currentEntry; console.log(current.url); ```