Before Adopting the Navigation API, Test Link Interception and Browser Back/Forward

Test Navigation API link interception, browser history, reloads, external links, accessibility, and fallbacks with a reproducible local example.

Published
Reading time
7 min read
Before Adopting the Navigation API, Test Link Interception and Browser Back/Forward
On this page

The Navigation API can let a single-page application handle eligible navigations without replacing the document. Before adopting it, test more than a link click: reloads, browser Back and Forward, fragments, and cross-origin links all need deliberate behavior.

This tutorial builds a small local site that works without interception, then adds Navigation API link interception as an enhancement.

Key Takeaways

  • The navigate event is a central place to examine eligible navigations, including history traversal—not just clicks.
  • Intercept only destinations your application can render, and leave unsupported or unsuitable navigations to the browser.
  • Serve usable pages at application URLs so direct visits, reloads, and unsupported browsers have a fallback.
  • Test history, focus, scrolling, fragments, downloads, forms, and external links separately.
  • Browser support and implementation details must be checked before release; they were not verified for this article.

How interception differs from a click handler

A traditional History API implementation often listens for clicks on links, prevents their default behavior, calls history.pushState(), and renders the new view. It also needs a popstate handler to render when the user travels Back or Forward. The click handler must avoid interfering with modified clicks, external destinations, downloads, and links targeting another browsing context.

The Navigation API instead exposes a navigate event on window.navigation. An eligible event can be intercepted with event.intercept(), whose handler renders the destination. The browser still owns the navigation and history machinery; the application supplies the view update. An intercepted navigation can include a same-origin link navigation or a traversal, but same-origin does not automatically mean interceptable. Check event.canIntercept and apply your own route and behavior checks.

Not every navigation reaches the current page as an interceptable event. For example, an external destination or a link opened in another browsing context must retain normal browser behavior. A reload should also remain a reload unless the application has a specific, well-tested reason to handle it differently.

Advertisement

Build a local test site

You need Python 3 and a browser with developer tools. Save the following as server.py and run python3 server.py. Open http://127.0.0.1:8000/ in the browser. Stop the server with Ctrl+C.

The server provides complete HTML for both routes. The script enhances navigation only when the relevant API is available. This example has not been executed here; check it and the API details in your target browsers before using the pattern.

from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlsplit

PAGES = {
    "/": ("Home", "This is the home page."),
    "/about/": ("About", "This is the about page."),
}

TEMPLATE = r'''<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>__TITLE__ - Navigation test</title>
</head>
<body>
  <nav aria-label="Main navigation">
    <a href="/">Home</a>
    <a href="/about/">About</a>
    <a href="#details">Page details</a>
    <a href="https://example.com/">External example</a>
  </nav>
  <main>
    <h1 tabindex="-1">__TITLE__</h1>
    <p id="message">__MESSAGE__</p>
    <section id="details">
      <h2>Page details</h2>
      <p>Use this fragment link to check native in-page navigation.</p>
    </section>
  </main>
  <script>
    const pages = {
      "/": { title: "Home", message: "This is the home page." },
      "/about/": { title: "About", message: "This is the about page." }
    };

    if ("navigation" in window &&
        typeof window.navigation.addEventListener === "function") {
      window.navigation.addEventListener("navigate", (event) => {
        console.log("navigate", event.navigationType, event.canIntercept);

        if (!event.canIntercept ||
            typeof event.intercept !== "function" ||
            event.navigationType === "reload" ||
            event.hashChange ||
            event.downloadRequest != null ||
            event.formData != null) {
          return;
        }

        const destination = new URL(event.destination.url);
        if (destination.origin !== location.origin ||
            destination.search || destination.hash ||
            !Object.hasOwn(pages, destination.pathname)) {
          return;
        }

        const page = pages[destination.pathname];
        event.intercept({
          focusReset: "manual",
          handler() {
            document.title = page.title + " - Navigation test";
            const heading = document.querySelector("main h1");
            heading.textContent = page.title;
            document.querySelector("#message").textContent = page.message;
            heading.focus({ preventScroll: true });
          }
        });
      });
    }
  </script>
</body>
</html>'''


class Handler(BaseHTTPRequestHandler):
    def serve_page(self, send_body):
        path = urlsplit(self.path).path
        if path not in PAGES:
            self.send_error(404)
            return

        title, message = PAGES[path]
        html = TEMPLATE.replace("__TITLE__", title).replace("__MESSAGE__", message)
        body = html.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        if send_body:
            self.wfile.write(body)

    def do_GET(self):
        self.serve_page(True)

    def do_HEAD(self):
        self.serve_page(False)


if __name__ == "__main__":
    with HTTPServer(("127.0.0.1", 8000), Handler) as server:
        print("Open http://127.0.0.1:8000/")
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass

The server is a local demonstration, not a production web server. Its page values are fixed; a real server must escape untrusted values inserted into HTML. The client uses textContent rather than interpreting route data as HTML.

What the handler allows

The handler intercepts only the two known paths, without a query string or fragment. It declines reloads, form submissions, downloads, hash changes, and events the browser says cannot be intercepted. Other paths and query strings go through normal navigation; the server returns a page or a 404 as appropriate.

The focusReset: "manual" option accompanies an explicit focus move to the new heading. Check this option and focus behavior in every target browser. The example leaves scrolling to the browser's interception behavior; verify restoration and fragment scrolling rather than assuming they match your application's needs.

Test clicks, reloads, and history

Open developer tools with the console visible. If your tools have a preserve-log option, enable it so document loads do not erase previous messages. The script logs the navigation type and canIntercept when it receives a navigate event; a missing log does not by itself prove that a browser navigation failed.

  1. Click About, then Home. In a supporting browser, each known route should update the heading, message, title, and address. Check that focus moves to the heading. Inspect the console and network panel to distinguish interception from a full document load.
  2. Press Back and Forward. Check that the address, heading, and message agree at each entry. Also test after scrolling a longer page: decide whether the restored scroll position and focus meet your application's needs.
  3. Reload on About. The server should return the About page directly. Refresh again with JavaScript disabled: the page and links should still be usable.
  4. Open About directly in a new tab. The server should serve the same route without requiring a prior visit to Home. Use a modified click or a link context menu too; a new tab should behave as a normal browser navigation.
  5. Click Page details. The URL fragment and in-page navigation should work without the application replacing the view. Test Back after the fragment change.
  6. Click External example. The browser should navigate normally to the external site, rather than render a local route. Use Back to return and check the restored page.
  7. Try an unknown path and a query string. Navigate directly to /missing/ and to /?test=1. The former should receive the server's 404; the latter should be handled by the server, not the client route handler.

Also test real forms, download links, links with targets, keyboard activation, and assistive technology in your application. This small site does not implement those features, so it cannot establish their behavior. Test across the actual browser and device versions you support, including versions without the API.

Advertisement

Progressive enhancement and release checks

The fallback here is ordinary HTML navigation: both routes have real links and server-rendered content. The API presence check alone is not enough to establish that every event or option behaves consistently; the event-level checks and a usable server response remain important. If client rendering fails after interception, do not assume the browser will automatically restore the old view or retry the navigation. Design error handling and a recovery path for a real application.

Current browser support and implementation details could not be verified in this run. Before publishing or deploying, consult MDN's Navigation API and navigate event documentation and the relevant browser vendors' documentation or release notes. Check support for the interface, intercept(), canIntercept, focusReset, and the navigation types you rely on. Record the specific browser versions you test rather than treating feature detection as a compatibility matrix.

For production, the server or hosting configuration must return the intended document for direct route requests, not just for client-side transitions. Keep authorization and data validation on the server; client-side route checks are not access controls.

Common Mistakes

  • Intercepting every same-origin URL. An origin may contain downloads, server endpoints, or pages your client router does not own.
  • Testing only forward link clicks. Traversals can expose stale content, focus problems, or incorrect scroll restoration.
  • Relying on interception for reloads. Direct requests need a valid server response and any required server-side state.
  • Treating a URL change as a complete accessible navigation. Update the document title and manage focus deliberately; test with keyboard and screen-reader users.
  • Assuming a skipped event is an error. Native navigation is the intended fallback for destinations and behaviors the application does not handle.

Best Practices

Start with a narrow route allowlist and expand it only after testing each navigation type. Preserve real href values, let the browser handle links outside that allowlist, and verify Back, Forward, reload, and direct entry in your deployment environment. If a view requires asynchronous data, define loading, cancellation, and failure behavior before intercepting it.

Conclusion

Navigation API interception can consolidate navigation handling, but adoption depends on more than a successful click. Keep functional server routes, intercept only known eligible destinations, and verify history and accessibility behavior in the browsers your users actually run.

What would your domain sell for?

A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.