The intercept() method of the NavigateEvent interface intercepts this navigation, turning it into a same-document navigation to the destination URL.
intercept()
intercept(options)
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,
});
},
});
}
});