NavigateEvent: intercept() method
The intercept()
method of the NavigateEvent
interface intercepts this navigation, turning it into a same-document navigation to the destination
URL.
Syntax
intercept()
intercept(options)
Parameters
options
Optional
-
An options object containing the following properties:
handler
Optional
-
A callback function that defines what the navigation handling behavior should be. This generally handles resource fetching, and returns a promise.
focusReset
Optional
-
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
attribute, or the <body>
element if no element has autofocus
set. This is the default value.
-
manual
-
Disable the default behavior.
scroll
Optional
-
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
Exceptions
InvalidStateError
DOMException
-
Thrown if the current Document
is not yet active, or if the navigation has been cancelled.
SecurityError
DOMException
-
Thrown if the event was dispatched by a dispatchEvent()
call, rather than the user agent, or if the navigation cannot be intercepted (i.e. NavigateEvent.canIntercept
is false
).
Examples
Handling a navigation using intercept()
navigation.addEventListener("navigate", (event) => {
if (shouldNotIntercept(event)) return;
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
renderArticlePagePlaceholder();
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
},
});
}
});
Form submission can be detected by querying for the 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
.
navigation.addEventListener("navigate", (event) => {
if (event.formData && event.canIntercept) {
event.intercept({
focusReset: "manual",
scroll: "manual",
async handler() {
await fetch(event.destination.url, {
method: "POST",
body: event.formData,
});
},
});
}
});
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
intercept |
105 |
105 |
No |
No |
No |
No |
105 |
105 |
No |
72 |
No |
20.0 |
See also