The navigate
event of the Navigation
interface is fired when any type of navigation is initiated, allowing you to intercept as required.
Use the event name in methods like addEventListener()
, or set an event handler property.
addEventListener("navigate", (event) => {});
onnavigate = (event) => {};
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);
},
});
}
});
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 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.
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.
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);
},
});
}
});