The NavigateEvent interface of the Navigation API is the event object for the navigate event, which fires when any type of navigation is initiated (this includes usage of History API features like History.go()). NavigateEvent provides access to information about that navigation, and allows developers to intercept and control the navigation handling.
Returns the filename of the file requested for download, in the case of a download navigation (e.g. an <a> or <area> element with a download attribute), or null otherwise.
Returns the info data value passed by the initiating navigation operation (e.g. Navigation.back(), or Navigation.navigate()), or undefined if no info data was passed.
Returns an 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).
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.
Intercepts this navigation, turning it into a same-document navigation to the 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.
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",(event)=>{// Exit early if this navigation shouldn't be intercepted,// e.g. if the navigation is cross-origin, or a download requestif(shouldNotIntercept(event))return;const url =newURL(event.destination.url);if(url.pathname.startsWith("/articles/")){
event.intercept({asynchandler(){// The URL has already changed, so show a placeholder while//fetching the new content, such as a spinner or loading pagerenderArticlePagePlaceholder();// Fetch the new content and display when readyconst articleContent =awaitgetArticleContent(url.pathname);renderArticlePage(articleContent);},});}});
Note: Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run e.preventDefault(), perform the appropriate History.pushState() call, then set up the page view based on the new URL. And this wouldn't handle all navigations — only user-initiated link clicks.
Handling scrolling using scroll()
In this example of intercepting a navigation, the handler() function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a scroll() call between the two.