User Agents

Web browsers and everyday web tech, explained

Track Client Side Navigation with Chrome DevTools Protocol

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Tracking client-side navigation with the Chrome DevTools Protocol (CDP) enables developers to programmatically observe and respond to navigation events in single-page applications (SPAs), such as route changes via the History API or hash updates. Unlike full page reloads, these navigations don’t trigger traditional page lifecycle events, making standard monitoring insufficient. Using CDP, you can intercept these changes in real time for debugging, performance analysis, or automated testing. This guide walks you through setting up CDP to detect and log client-side navigation events accurately.

What You'll Need

  • A recent version of Google Chrome or a Chromium-based browser
  • Node.js installed (version 14 or higher recommended)
  • Basic familiarity with JavaScript and command-line tools
  • The puppeteer or chrome-remote-interface npm package
  • Remote debugging enabled in Chrome (via command-line flags or DevTools)

Step-by-Step

  1. Launch Chrome with remote debugging enabled. Open a terminal and run: google-chrome --remote-debugging-port=9222 This starts Chrome with a debugging server on port 9222. On Windows, use chrome.exe instead of google-chrome.
  2. Open a web page that uses client-side routing, such as a React, Vue, or Angular application. Navigate around the app to confirm it uses pushState or hash-based routing without full reloads.
  3. Install the chrome-remote-interface package via npm: npm install chrome-remote-interface This library provides a Node.js interface to CDP.
  4. Create a new JavaScript file (e.g., track-navigation.js) and require the package: const CDP = require('chrome-remote-interface');
  5. Connect to the running Chrome instance:
    CDP(async (client) => {
      const { Page, Runtime } = client;
      try {
        await Page.enable();
      } catch (err) {
        console.error('Error enabling Page domain:', err);
      }
  6. Enable the Page domain to receive navigation-related events. The Page.frameNavigated event fires for both full and client-side navigations, but you need to distinguish them.
  7. Set up an event listener for Page.frameNavigated:
    Page.frameNavigated((params) => {
      console.log('Frame navigated:', params.frame.url);
    });
    This logs every navigation, including client-side ones.
  8. To detect only client-side navigations, compare the params.frame.url with the previous URL. Store the last URL in a variable and check if the navigation was initiated via JavaScript:
  9. Enable the Runtime domain to intercept JavaScript calls. Listen for Runtime.executionContextCreated and evaluate expressions to monitor History API usage.
  10. Optionally, intercept pushState and replaceState calls by overriding them in the page context:
    await Runtime.evaluate({
      expression: `{
        const origPush = history.pushState;
        history.pushState = function(state, title, url) {
          console.log('pushState called:', url);
          origPush.call(history, state, title, url);
        };
      }`
    });
  11. Similarly, monitor hash changes using window.addEventListener('hashchange', ...) injected via Runtime.evaluate.
  12. For SPAs using frameworks, combine Page.frameNavigated with custom logging to identify virtual routes. Some frameworks emit events (e.g., Vue Router) that can be tapped into.
  13. Close the client connection gracefully on exit:
    process.on('SIGINT', () => {
      client.close();
      process.exit();
    });

Common Mistakes

  • Assuming Page.frameNavigated only fires on full page loads — it also triggers on client-side navigations, but developers often filter them out incorrectly.
  • Forgetting to enable the Page domain before setting up listeners, resulting in no events received.
  • Injecting scripts too late — always set up overrides like pushState before navigation occurs.
  • Not handling disconnections — if Chrome closes unexpectedly, the script should retry or log the error.
  • Mixing up frame IDs — in complex pages with iframes, ensure you’re tracking the main frame’s navigation.

Tips

  • Use Puppeteer for higher-level control. It abstracts CDP and offers page.on('framenavigated', ...) directly.
  • Log timestamps with each navigation event to analyze timing and sequence.
  • Combine CDP with network monitoring (Network domain) to correlate route changes with XHR/fetch calls.
  • Store navigation history in an array for debugging session replay.
  • Test across different SPA frameworks, as routing implementations vary (e.g., React Router vs. Angular Router).

Troubleshooting

If no navigation events appear, first verify Chrome is running with --remote-debugging-port=9222 and accessible at http://localhost:9222/json. This endpoint should return a list of active pages. If empty, restart Chrome with the flag. If events still don’t fire, ensure Page.enable() completes successfully — wrap it in a try-catch. If using chrome-remote-interface, confirm the version matches your Chrome version. Mismatches can cause silent failures. If script overrides aren’t working, check that Runtime.enable() was called before evaluation. For hash-based routing, ensure the hashchange listener is added before any navigation. In headless environments, use --headless=chrome and confirm DevTools Protocol is still accessible. If the connection drops, implement reconnection logic or use Puppeteer’s built-in resilience.

Frequently Asked Questions

Can I track client-side navigation without Node.js?

Yes, using Chrome DevTools manually. Open the Console and run to log calls.

Does this work in incognito mode?

Yes, but you must launch Chrome in incognito with the remote debugging flag: --incognito --remote-debugging-port=9222.

Why doesn’t Page.frameNavigated fire on every route change?

Some SPAs update state without changing the URL. Ensure the route actually modifies window.location or uses pushState. Otherwise, you’ll need framework-specific hooks.

Can I block or modify client-side navigations?

Yes. Override pushState and replaceState to intercept or cancel calls, or use Page.addScriptToEvaluateOnNewDocument to inject logic early.

Is this method compatible with headless Chrome?

Yes. Run Chrome with --headless=chrome --remote-debugging-port=9222 and connect via CDP as usual.

How do I distinguish client-side from server-side navigations?

Check the type field in Page.frameNavigated. Client-side navigations often have type: 'ScriptTriggered', while server-side ones are 'Other' or 'FormSubmission'.