Principle:SeleniumHQ Selenium Network Traffic Interception
| Knowledge Sources | |
|---|---|
| Domains | Browser_Automation, DevTools, Network |
| Last Updated | 2026-02-11 00:00 GMT |
Overview
Mechanism for intercepting, modifying, or mocking HTTP requests and responses made by the browser during a WebDriver session.
Description
Network interception allows test code to modify requests before they reach the server, or replace server responses with custom ones. This is implemented via the CDP Fetch domain, which pauses network requests and allows the client to provide modified headers, bodies, or entirely synthetic responses. Selenium wraps this in NetworkInterceptor, providing a high-level API using Filter, HttpHandler, and Routable patterns from the Selenium HTTP framework.
The interception model supports three entry points:
- HttpHandler: a simple function from request to response, wrapped as (Filter) next -> handler (the next handler is ignored)
- Routable: a pattern-matching handler that processes matching requests and passes non-matching ones through to the actual server via next.execute(req)
- Filter: a composable middleware that receives a next handler and can modify both the request (before calling next) and the response (after calling next)
The special sentinel NetworkInterceptor.PROCEED_WITH_REQUEST signals that a request should continue to the actual server unmodified.
Usage
Use for testing error scenarios (simulating server errors), mocking API responses, adding authentication headers, or capturing request/response data for verification. Particularly useful for testing offline behavior, slow network conditions, or specific API contract violations. The interceptor automatically creates a CDP session if one does not exist.
Theoretical Basis
# Pseudocode: Network Interception
1. Construct NetworkInterceptor with driver and Filter/Handler/Routable
2. Verify driver implements HasDevTools
3. Obtain DevTools, create CDP session if needed (on current window)
4. Call domains.network().interceptTrafficWith(filter) to enable Fetch domain
5. For each intercepted request:
a. Filter/Handler receives an HttpRequest
b. Returns: HttpResponse (synthetic) or delegates to next handler
c. PROCEED_WITH_REQUEST sentinel causes unmodified pass-through
6. On close(): call domains.network().resetNetworkFilter()
- Disables interception, normal network behavior resumes