Track Client Side Navigation with Chrome DevTools Protocol
In this article
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
puppeteerorchrome-remote-interfacenpm package - Remote debugging enabled in Chrome (via command-line flags or DevTools)
Step-by-Step
- Launch Chrome with remote debugging enabled. Open a terminal and run:
google-chrome --remote-debugging-port=9222This starts Chrome with a debugging server on port 9222. On Windows, usechrome.exeinstead ofgoogle-chrome. - 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.
- Install the
chrome-remote-interfacepackage via npm:npm install chrome-remote-interfaceThis library provides a Node.js interface to CDP. - Create a new JavaScript file (e.g.,
track-navigation.js) and require the package:const CDP = require('chrome-remote-interface'); - 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); } - Enable the
Pagedomain to receive navigation-related events. ThePage.frameNavigatedevent fires for both full and client-side navigations, but you need to distinguish them. - 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. - To detect only client-side navigations, compare the
params.frame.urlwith the previous URL. Store the last URL in a variable and check if the navigation was initiated via JavaScript: - Enable the
Runtimedomain to intercept JavaScript calls. Listen forRuntime.executionContextCreatedand evaluate expressions to monitor History API usage. - Optionally, intercept
pushStateandreplaceStatecalls 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); }; }` }); - Similarly, monitor hash changes using
window.addEventListener('hashchange', ...)injected viaRuntime.evaluate. - For SPAs using frameworks, combine
Page.frameNavigatedwith custom logging to identify virtual routes. Some frameworks emit events (e.g., Vue Router) that can be tapped into. - Close the client connection gracefully on exit:
process.on('SIGINT', () => { client.close(); process.exit(); });
Common Mistakes
- Assuming
Page.frameNavigatedonly fires on full page loads — it also triggers on client-side navigations, but developers often filter them out incorrectly. - Forgetting to enable the
Pagedomain before setting up listeners, resulting in no events received. - Injecting scripts too late — always set up overrides like
pushStatebefore 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 (
Networkdomain) 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'.