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
Copy file name to clipboardExpand all lines: files/en-us/web/api/navigateevent/intercept/index.md
+34-1Lines changed: 34 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -117,6 +117,38 @@ The `precommitHandler()` callback takes a {{domxref("NavigationPrecommitControll
117
117
> [!NOTE]
118
118
> 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.
119
119
120
+
### Scheduling post-commit actions in `precommitHandler()`
121
+
122
+
As we saw above, you can specify a `handler()` callback in the object passed to the `intercept()` method in order to preform actions after a navigation is is committed.
123
+
This approach works well if the actions required after commit do not depend on any actions run in the pre-commit phase.
124
+
If they do, then you can use {{domxref("NavigationPrecommitController.addHandler()")}} in `precommitHandler()` to dynamically add a handler that will run after the navigation commits.
125
+
126
+
For example, consider this code that extends the previous example for redirecting a logged-out user to a sign-in page.
127
+
The code uses `addHandler()` to add a post-commit handler callback that shows a message explaining the redirect reason.
128
+
Note that the handler only runs for the specific case of a redirect to the sign-in page.
if (url.pathname.startsWith("/restricted/") &&!userSignedIn) {
135
+
event.intercept({
136
+
asyncprecommitHandler(controller) {
137
+
controller.redirect("/signin/", {
138
+
state:"signin-redirect",
139
+
history:"push",
140
+
});
141
+
142
+
// Use addHandler to trigger logic once the /signin/ page commits
143
+
controller.addHandler(() => {
144
+
showMessage("Please sign in to view that content.");
145
+
});
146
+
},
147
+
});
148
+
}
149
+
});
150
+
```
151
+
120
152
### Responding to navigation success or failure
121
153
122
154
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.
@@ -137,7 +169,8 @@ Both `precommitHandler()` and `handler()` callbacks can be included inside the s
137
169
- When the `handler()` promise fulfills and the `navigatesuccess` event fires, the navigation `finished` promise fulfills as well, to indicate the navigation is finished.
138
170
- If `handler()` rejects, the `navigateerror` event fires, the `finished` promise rejects, and the navigation is canceled.
139
171
140
-
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.
172
+
Note that the above process is upheld even across multiple `intercept()` calls on the same `NavigateEvent`, and for `handler()` callbacks added in the `precommitHandler()`.
173
+
All `precommitHandler()` callbacks are called first, and when all of them resolve, the navigation commits, and all the `handler()` callbacks are called.
The **`addHandler()`** method of the {{domxref("NavigationPrecommitController")}} interface allows you to dynamically add a handler callback function in precommit code, which will then be run after the navigation has committed.
12
+
13
+
This is useful when the navigation workflow depends on information that is not know until precommit code has started running.
14
+
If the precommit and (post-commit) handler are independent, the handler can be specified in the in the [`options.handler`](/en-US/docs/Web/API/NavigateEvent/intercept#handler) argument passed to {{domxref("NavigateEvent.intercept()")}}.
15
+
16
+
## Syntax
17
+
18
+
```js-nolint
19
+
addHandler(handler);
20
+
```
21
+
22
+
### Parameters
23
+
24
+
-`handler`
25
+
- : A callback function that defines the post-commit navigation handling behavior should be; it returns a promise.
26
+
27
+
The handler callback is invoked as though it was passed to the `NavigateEvent.intercept()` method, and will run after the {{domxref("Navigation.currentEntry", "currentEntry")}} property has been updated.
28
+
29
+
### Return value
30
+
31
+
None (`undefined`).
32
+
33
+
### Exceptions
34
+
35
+
-`InvalidStateError` {{domxref("DOMException")}}
36
+
- : Thrown if:
37
+
- The originating {{domxref("NavigateEvent")}} was not intercepted or has been canceled.
38
+
- The {{domxref("Document")}} is not fully active.
39
+
-`SecurityError` {{domxref("DOMException")}}
40
+
- : Thrown if the event {{domxref("Event/isTrusted","isTrusted")}} attribute is `false`.
41
+
42
+
## Examples
43
+
44
+
For more examples see {{domxref("NavigationPrecommitController")}}.
45
+
46
+
### Basic usage
47
+
48
+
This example shows a `precommitHandler` implementation that fetches data for a page and uses `addHandler()` to add different handlers based on the page type (the implementations of the `fetchConfig`, `setupVideoPlayer()` and `setupArticleView()` are not given).
The **`NavigationPrecommitController`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} defines redirect behavior for a navigation [precommit handler](/en-US/docs/Web/API/NavigateEvent/intercept#precommithandler).
10
+
The **`NavigationPrecommitController`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} is passed as an argument to a navigation [precommit handler](/en-US/docs/Web/API/NavigateEvent/intercept#precommithandler) callback.
11
+
12
+
The callback is used to handle any modifications to the navigation that are required before it is committed (and the destination URL is actually displayed in the browser), such as cancelling or redirecting it somewhere else as required.
13
+
This interface provides methods to redirect to a new URL and update history and state, and to dynamically configure post-commit navigation behavior.
- : Adds a handler callback function that will be run after the navigation has committed, as though it has been added to {{domxref("NavigateEvent.intercept()")}} using the [`options.handler`](/en-US/docs/Web/API/NavigateEvent/intercept#handler) argument.
- : Redirects the browser to a specified URL and specifies history behavior and any desired state information.
18
23
19
24
## Description
20
25
21
26
When specifying same-document navigation behavior via the {{domxref("NavigateEvent.intercept()")}} method, it is possible to specify navigation precommit actions via the [`precommitHandler`](/en-US/docs/Web/API/NavigateEvent/intercept#precommithandler) callback. Precommit actions are used to modify or cancel in-flight navigation, or to perform work while the navigation is ongoing and before it is committed (see [Basic precommit navigation example](#basic_precommit_navigation_example)).
22
27
23
-
To specify the redirect behavior, you pass a `NavigationPrecommitController` object into the `precommitHandler` callback function. Inside the function body, you can call the `NavigationPrecommitController.redirect()` method, which takes as an argument an object containing the redirect URL, plus any required history behavior and state information.
28
+
To specify the redirect behavior, you use the `NavigationPrecommitController` object that is passed into your the `precommitHandler` callback function.
29
+
Inside the function body, you can call the `NavigationPrecommitController.redirect()` method, which takes as an argument an object containing the redirect URL, plus any required history behavior and state information.
30
+
31
+
After a navigation is committed, a post-commit handler callback can be run in order to perform operations such as fetching and rendering content.
32
+
If the post-commit navigation code depends on data gathered at runtime in your `precommitHandler`, you can call the {{domxref("NavigationPrecommitController/addHandler", "addHandler()")}} in your precommit handler to dynamically add this post-commit handler callback.
33
+
Note that if the post-commit code is independent of the pre-commit code you can instead pass the [`handler`](/en-US/docs/Web/API/NavigateEvent/intercept#handler) callback to the {{domxref("NavigateEvent.intercept()")}} method.
24
34
25
35
See the [`intercept()` description](/en-US/docs/Web/API/NavigateEvent/intercept#description) for additional context.
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 {{domxref("Navigation.navigatesuccess_event", "navigatesuccess")}} or {{domxref("Navigation.navigateerror_event", "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.
51
61
62
+
### Add handler that is conditional on precommit behavior
63
+
64
+
This is a small modification of the previous example that also shows a message to the user indicating the reason they have landed on the sign-in page after the redirection.
65
+
This uses `addHandler()` in the pre-commit handler to add the post-commit handler that displays the message.
0 commit comments