Intermediate
Chapter 14 · 11 min read
Chrome DevTools Protocol (CDP)
Leverage Selenium 4's CDP integration — intercept network requests, emulate geolocation, mock device metrics, and capture console logs.
Chrome DevTools Protocol (CDP)
Selenium 4 introduced native CDP support, giving you direct access to Chrome's DevTools capabilities. This unlocks powerful features like network interception, geolocation mocking, device emulation, and performance metrics — all from your test code.
CdpTest.java
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v131.emulation.Emulation;
import org.openqa.selenium.devtools.v131.network.Network;
import org.openqa.selenium.devtools.v131.log.Log;
import org.testng.annotations.*;
import java.util.*;
public class CdpTest {
ChromeDriver driver;
DevTools devTools;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
devTools = driver.getDevTools();
devTools.createSession();
}
@Test
public void testGeolocationEmulation() {
// Mock geolocation to Mumbai, India
devTools.send(Emulation.setGeolocationOverride(
Optional.of(19.0760), // latitude
Optional.of(72.8777), // longitude
Optional.of(100.0) // accuracy
));
driver.get("https://my-location.org/");
System.out.println("Location mocked to Mumbai");
}
@Test
public void testCaptureConsoleLogs() {
devTools.send(Log.enable());
List<String> consoleLogs = new ArrayList<>();
devTools.addListener(Log.entryAdded(), entry -> {
consoleLogs.add(entry.getText());
System.out.println("Console: " + entry.getText());
});
driver.get("https://www.selenium.dev/");
System.out.println("Captured " + consoleLogs.size() + " log entries");
}
@Test
public void testNetworkInterception() {
devTools.send(Network.enable(Optional.empty(),
Optional.empty(), Optional.empty()));
List<String> requestUrls = new ArrayList<>();
devTools.addListener(Network.requestWillBeSent(), request -> {
requestUrls.add(request.getRequest().getUrl());
});
driver.get("https://www.selenium.dev/");
System.out.println("Captured " + requestUrls.size() + " network requests");
}
@Test
public void testDeviceEmulation() {
// Emulate mobile device
Map<String, Object> deviceMetrics = new HashMap<>();
deviceMetrics.put("width", 375);
deviceMetrics.put("height", 812);
deviceMetrics.put("deviceScaleFactor", 3);
deviceMetrics.put("mobile", true);
driver.executeCdpCommand("Emulation.setDeviceMetricsOverride",
deviceMetrics);
driver.get("https://www.selenium.dev/");
System.out.println("Emulating iPhone X viewport");
}
@AfterMethod
public void teardown() { if (driver != null) driver.quit(); }
}
test_cdp.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
@pytest.fixture
def driver():
d = webdriver.Chrome()
yield d
d.quit()
def test_geolocation_emulation(driver):
"""Mock geolocation via CDP"""
# Mumbai, India
params = {
"latitude": 19.0760,
"longitude": 72.8777,
"accuracy": 100
}
driver.execute_cdp_cmd("Emulation.setGeolocationOverride", params)
driver.get("https://my-location.org/")
print("Location mocked to Mumbai")
def test_device_emulation(driver):
"""Emulate mobile device via CDP"""
metrics = {
"width": 375,
"height": 812,
"deviceScaleFactor": 3,
"mobile": True
}
driver.execute_cdp_cmd("Emulation.setDeviceMetricsOverride", metrics)
driver.get("https://www.selenium.dev/")
print("Emulating iPhone X viewport")
def test_capture_console_logs(driver):
"""Capture browser console logs"""
driver.get("https://www.selenium.dev/")
logs = driver.get_log("browser")
for entry in logs:
print(f"[{entry['level']}] {entry['message']}")
print(f"Captured {len(logs)} log entries")
def test_network_performance(driver):
"""Get performance metrics via CDP"""
driver.get("https://www.selenium.dev/")
metrics = driver.execute_cdp_cmd("Performance.getMetrics", {})
for metric in metrics["metrics"]:
if metric["name"] in ["DomContentLoaded", "NavigationStart"]:
print(f"{metric['name']}: {metric['value']}")
Selenium
Intermediate
Chrome DevTools Protocol (CDP)
Written by PV
© 2026 All Rights Reserved