You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
- : 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.
53
+
- : Intercepts this navigation, turning it into a same-document navigation to the {{domxref("NavigationDestination.url", "destination")}} URL. It can accept handler functions that define what the navigation handling behavior should be, plus `focusReset` and `scroll` options to enable or disable the browser's default focus and scrolling behavior as desired.
- : 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.
Copy file name to clipboardExpand all lines: files/en-us/web/api/navigateevent/intercept/index.md
+161-4Lines changed: 161 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -25,7 +25,9 @@ intercept(options)
25
25
-`options` {{optional_inline}}
26
26
- : An options object containing the following properties:
27
27
-`handler` {{optional_inline}}
28
-
- : A callback function that defines what the navigation handling behavior should be. This generally handles resource fetching, and returns a promise.
28
+
- : A callback function that defines what the navigation handling behavior should be; it returns a promise. This function will run after the {{domxref("Navigation.currentEntry", "currentEntry")}} property has been updated.
29
+
-`precommitHandler` {{optional_inline}}
30
+
- : A callback function that defines any behavior that should occur just before the navigation has committed; it accepts a controller object as an argument and returns a promise. This function will run before the {{domxref("Navigation.currentEntry", "currentEntry")}} property has been updated.
29
31
-`focusReset` {{optional_inline}}
30
32
- : Defines the navigation's focus behavior. This may take one of the following values:
31
33
-`after-transition`
@@ -48,7 +50,162 @@ None (`undefined`).
48
50
-`InvalidStateError` {{domxref("DOMException")}}
49
51
- : Thrown if the current {{domxref("Document")}} is not yet active, or if the navigation has been cancelled.
50
52
-`SecurityError` {{domxref("DOMException")}}
51
-
- : 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`).
53
+
- : Thrown if:
54
+
- The event was dispatched by a {{domxref("EventTarget.dispatchEvent", "dispatchEvent()")}} call, rather than the user agent.
55
+
- The navigation cannot be intercepted ({{domxref("NavigateEvent.canIntercept")}} is `false`).
56
+
- A `precommitHandler()` callback is provided on a non-cancelable event ({{domxref("Event.cancelable")}} is `false`).
57
+
58
+
## Description
59
+
60
+
The `intercept()` method is used to implement same-document (SPA) navigation behavior when a navigation occurs; for example, when a link is clicked, a form is submitted, or a programmatic navigation is initiated (using {{domxref("History.pushState()")}}, {{domxref("Window.location")}}, etc.).
61
+
62
+
It does this via a couple of different callbacks, `handler()` and `precommitHandler()`.
63
+
64
+
### Handling immediate navigations with `handler()`
65
+
66
+
The `handler()` callback is run in response to a committed navigation. It will run after the {{domxref("Navigation.currentEntry", "currentEntry")}} property has been updated, meaning that a new URL is shown in the browser UI and the history is updated with a new entry.
67
+
68
+
A typical example looks like this, enabling specific content to be rendered and loaded in response to a certain navigation:
// Include multiple conditions for different page types here, as needed
85
+
});
86
+
```
87
+
88
+
`handler()` should be used to implement navigation behavior where the navigation is committed to: the user should be shown something new.
89
+
90
+
### Handling precommit actions with `precommitHandler()`
91
+
92
+
However, you might also wish to modify or cancel in-flight navigation, or to perform work while the navigation is ongoing and before it is committed. This kind of scenario can be dealt with using the `precommitHandler()` callback, which runs before the {{domxref("Navigation.currentEntry", "currentEntry")}} property has been updated and the browser UI shows the new location.
93
+
94
+
For example, if the user navigates to a restricted page and is not signed in, you may want to redirect the browser to a sign-in page. This might be handled like so:
if (url.pathname.startsWith("/restricted/") &&!userSignedIn) {
101
+
event.intercept({
102
+
asyncprecommitHandler(controller) {
103
+
controller.redirect("/signin/", {
104
+
state:"signin-redirect",
105
+
history:"push",
106
+
});
107
+
},
108
+
});
109
+
}
110
+
});
111
+
```
112
+
113
+
This pattern is simpler than the alternative of canceling the original navigation and starting a new one to the redirect location, because it avoids exposing the intermediate state. For example, only one `navigatesuccess` or `navigateerror` event fires, and if the navigation was triggered by a call to {{domxref("Navigation.navigate()")}}, the promise only fulfills once the redirect destination is reached.
114
+
115
+
The `precommitHandler()` callback takes a `controller` object as an argument, which contains a `redirect()` method. The `redirect()` method takes two parameters — a string representing the URL to redirect to, and an options object containing two parameters:
116
+
117
+
-`state` {{optional_inline}}
118
+
- : Contains any state information you want to pass along with the navigation; for example, for logging or tracking purposes. The state for the navigation can subsequently be retrieved via {{domxref("NavigationHistoryEntry.getState()")}}.
119
+
-`history` {{optional_inline}}
120
+
- : An enumerated value that specifies how this redirect should be added to the navigation history. It can take one of the following values:
121
+
-`auto`
122
+
- : The default value, which lets the browser decide how to handle it:
123
+
- If the original navigation occurred as a result of a {{domxref("Navigation.navigate()")}} call, the value will be whatever was specified in the `navigate()` call's [`history`](/en-US/docs/Web/API/Navigation/navigate#history) option.
124
+
- Otherwise, the value used is usually `push`, but it will become `replace` if the redirect points to the same URL as the pre-navigation URL.
125
+
-`push`
126
+
- : Adds a new {{domxref("NavigationHistoryEntry")}} to the navigation history, and clears any available forward navigation (that is, if the user previously navigated to other locations, then used the back button to return back through the history before then initiating the navigation that caused the redirect).
127
+
-`replace`
128
+
- : Replaces the {{domxref("Navigation.currentEntry")}} with the `NavigationHistoryEntry`.
129
+
130
+
> [!NOTE]
131
+
> The `redirect()` method can can convert the history behavior between `auto`, `push`, and `replace`, but it cannot turn a `traverse` navigation into a `push`/`replace` navigation and vice versa.
132
+
133
+
`precommitHandler()` generally handles any modifications to the navigation behavior that are required before the destination URL is actually displayed in the browser, cancelling or redirecting it somewhere else as required. Because `precommitHandler()` can be used to cancel navigations, it will only work as expected when the event's {{domxref("Event.cancelable")}} property is `true`. Calling `intercept()` with a `precommitHandler()` on a non-cancelable event results in a `SecurityError` being thrown.
134
+
135
+
### Responding to navigation success or failure
136
+
137
+
When the promises returned by the `intercept()` handler functions fulfill, the `Navigation` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If those promises reject, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle the failure case.
138
+
139
+
There is also a `finished` property on the return value of navigation methods (such as {{domxref("Navigation.navigate()")}}), which fulfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases.
140
+
141
+
### Interaction between `precommitHandler()` and `handler()`
142
+
143
+
Both `precommitHandler()` and `handler()` callbacks can be included inside the same `intercept()` call.
144
+
145
+
1. First, the `precommitHandler()` handler runs.
146
+
- When the `precommitHandler()` promise fulfills, the navigation commits.
147
+
- If the `precommitHandler()` rejects, `navigateerror` fires, the `committed` and `finished` promises reject, and the navigation is cancelled.
148
+
149
+
2. When the navigation commits, a new {{domxref("NavigationHistoryEntry")}} is created for the navigation, and its `committed` promise fulfills.
150
+
151
+
3. Next, the `handler()` promise runs.
152
+
- When the `handler()` promise fulfills and the `navigatesuccess` event fires, the navigation `finished` promise fulfills as well, to indicate the navigation is finished.
153
+
- If `handler()` rejects, `navigateerror` fires, the `finished` promise rejects, and the navigation is canceled.
154
+
155
+
Note that the above process is upheld even across multiple `intercept()` calls on the same `NavigateEvent`. All `precommitHandler()` callbacks are called first, and when all of them resolve, the navigation commits, and all the `handler()` callbacks are called.
156
+
157
+
### Controlling focus behavior
158
+
159
+
By default, after a navigation handled using `intercept()` has occurred, the document focus will reset to the first element in the DOM with an [`autofocus`](/en-US/docs/Web/HTML/Reference/Global_attributes/autofocus) attribute set, or otherwise to the {{htmlelement("body")}} element, if no `autofocus` attribute is set. If you want to override this behavior, to manually implement a more accessible focus position on navigation (for example, the new top-level heading), you can do so by setting the `focusReset` option to `manual`.
After an `intercept()` navigation occurs, the following scrolling behavior occurs:
183
+
184
+
- For `push` and `replace` navigations (see {{domxref("Navigation.navigate()")}}), the browser will attempt to scroll to the fragment given by `event.destination.url`. If there is no fragment available, it will reset the scroll position to the top of the page.
185
+
- For {{domxref("Navigation.traverseTo", "traverse")}} and {{domxref("Navigation.reload", "reload")}} navigations, the browser behaves similarly to the description in the previous item above in this list, but delays its scroll restoration logic until the `intercept()` promise fulfills. It will perform no scroll restoration if the promise rejects. If the user has scrolled during the transition then no scroll restoration will be performed.
186
+
187
+
If you want to turn this behavior off, you can do so by setting the `scroll` option to `manual`.
If you want to manually trigger the default scrolling behavior described earlier (maybe you want to reset the scroll position to the top of the page early, before the full navigation has finished), you can do so by calling {{domxref("NavigateEvent.scroll()")}}.
Copy file name to clipboardExpand all lines: files/en-us/web/api/navigation_api/index.md
+4-2Lines changed: 4 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -28,7 +28,9 @@ The `navigation` interface has several associated events, the most notable being
28
28
29
29
The `NavigationEvent` object also provides two methods:
30
30
31
-
- {{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.
31
+
- {{domxref("NavigateEvent.intercept", "intercept()")}} allows you to specify custom behavior for navigations, and can take the following as arguments:
32
+
- Callback handler functions allowing you to specify what happens both _when_ the navigation is committed and _just before_ the navigation is committed. For example, you could load relevant new content into the UI based on the path of the URL navigated to, or redirect the browser to a sign-in page if the URL points to a restricted page and the user is not signed in.
33
+
- Properties that allow you to enable or disable the browser's default focus and scrolling behavior after the navigation occurs.
32
34
- {{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.
33
35
34
36
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 to track the process of the ongoing navigation.
@@ -39,7 +41,7 @@ Once a navigation is initiated, and your `intercept()` handler is called, a {{do
39
41
> [!NOTE]
40
42
> 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.
41
43
42
-
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 fulfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases.
44
+
When the promises returned by the `intercept()` handler functions fulfill, the `Navigation` object's {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires, allowing you to run cleanup code after a successful navigation has completed. If they reject, meaning the navigation has failed, {{domxref("Navigation/navigateerror_event", "navigateerror")}} fires instead, allowing you to gracefully handle failure case. There is also a `finished` property on the return value of navigation methods (such as {{domxref("Navigation.navigate()")}}), which fulfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases.
43
45
44
46
> [!NOTE]
45
47
> 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.
0 commit comments