Unlock Selenium 4 Chrome DevTools API: Simulate Devices, Capture Traffic, Test Faster

This article introduces Chrome DevTools, explains Selenium 4's native CDP support, and provides Java code examples for device‑mode emulation, geolocation, network throttling, HTTP request/response capture, console logging, performance metrics, and basic authentication, enabling more powerful automated web testing.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Unlock Selenium 4 Chrome DevTools API: Simulate Devices, Capture Traffic, Test Faster

Chrome DevTools Overview

Chrome DevTools is a set of built‑in tools in Chromium‑based browsers (Chrome, Opera, Edge) that help developers debug and inspect web pages.

Inspect DOM elements

Edit elements and CSS in real time

Monitor performance

Emulate geolocation

Throttle network speed

Execute and debug JavaScript

View console logs

Selenium 4 Chrome DevTools API

Selenium 4 adds native support for the Chrome DevTools Protocol (CDP). Using the new API you can capture network traffic, emulate geolocation, change device metrics, and more.

Selenium introduces the ChromiumDriver class with two methods for accessing CDP: getDevTools() and executeCdpCommand(). getDevTools() returns a DevTools object that lets you send wrapped CDP commands via send(). executeCdpCommand() sends raw CDP commands when no wrapper exists.

Device Mode Emulation

Most modern applications are responsive. Testers can use CDP’s Emulation.setDeviceMetricsOverride to set width, height, mobile flag, and device scale factor. The Selenium wrapper requires 12 parameters; optional ones can be passed as Optional.empty(). The example below uses the raw executeCdpCommand() for brevity.

package com.devtools;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import java.util.HashMap;
import java.util.Map;
public class SetDeviceMode {
    final static String PROJECT_PATH = System.getProperty("user.dir");
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", PROJECT_PATH + "/src/main/resources/chromedriver");
        ChromeDriver driver = new ChromeDriver();
        DevTools devTools = driver.getDevTools();
        devTools.createSession();
        Map deviceMetrics = new HashMap() {{
            put("width", 600);
            put("height", 1000);
            put("mobile", true);
            put("deviceScaleFactor", 50);
        }};
        driver.executeCdpCommand("Emulation.setDeviceMetricsOverride", deviceMetrics);
        driver.get("https://www.google.com");
    }
}

The script creates a map with the required keys and calls executeCdpCommand to apply the device metrics, then opens Google with the emulated viewport.

Device mode example
Device mode example

Geolocation Emulation

To test location‑dependent features, use Emulation.setGeolocationOverride. The following test sets latitude, longitude, and accuracy, then navigates to a site that shows the current location.

@Test
public void mockLocation() {
    devTools.send(Emulation.setGeolocationOverride(
            Optional.of(48.8584),
            Optional.of(2.2945),
            Optional.of(100)));
    driver.get("https://mycurrentlocation.net/");
    try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); }
}

Network Speed Emulation

Using Network.emulateNetworkConditions you can simulate slow 2G, cellular, or offline conditions. The example below throttles the connection to 2G and opens Google.

package com.devtools;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.network.Network;
import org.openqa.selenium.devtools.network.model.ConnectionType;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class SetNetwork {
    final static String PROJECT_PATH = System.getProperty("user.dir");
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", PROJECT_PATH + "/src/main/resources/chromedriver");
        ChromeDriver driver = new ChromeDriver();
        DevTools devTools = driver.getDevTools();
        devTools.createSession();
        devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
        devTools.send(Network.emulateNetworkConditions(
                false,
                20,
                20,
                50,
                Optional.of(ConnectionType.CELLULAR2G)));
        driver.get("https://www.google.com");
    }
}

HTTP Request Capture

Enable network tracking with Network.enable and add a listener to Network.requestWillBeSent to log each request’s URL and method.

package com.devtools;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.network.Network;
import java.util.Optional;
public class CaptureNetworkTraffic {
    private static ChromeDriver driver;
    private static DevTools chromeDevTools;
    final static String PROJECT_PATH = System.getProperty("user.dir");
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", PROJECT_PATH + "/src/main/resources/chromedriver");
        driver = new ChromeDriver();
        chromeDevTools = driver.getDevTools();
        chromeDevTools.createSession();
        chromeDevTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
        chromeDevTools.addListener(Network.requestWillBeSent(),
                entry -> System.out.println("Request URI : " + entry.getRequest().getUrl()
                        + "
 With method : " + entry.getRequest().getMethod()));
        driver.get("https://www.google.com");
        chromeDevTools.send(Network.disable());
    }
}

HTTP Response Interception

Listen to Network.responseReceived to capture status, headers, and body using Network.getResponseBody.

@Test
public void validateResponse() {
    final RequestId[] requestIds = new RequestId[1];
    devTools.send(Network.enable(Optional.of(100000000), Optional.empty(), Optional.empty()));
    devTools.addListener(Network.responseReceived(), responseReceived -> {
        if (responseReceived.getResponse().getUrl().contains("api.zoomcar.com")) {
            System.out.println("URL: " + responseReceived.getResponse().getUrl());
            System.out.println("Status: " + responseReceived.getResponse().getStatus());
            System.out.println("Type: " + responseReceived.getType().toJson());
            responseReceived.getResponse().getHeaders().toJson()
                    .forEach((k, v) -> System.out.println(k + ":" + v));
            requestIds[0] = responseReceived.getRequestId();
            System.out.println("Response Body: 
"
                    + devTools.send(Network.getResponseBody(requestIds[0])).getBody() + "
");
        }
    });
    driver.get("https://www.zoomcar.com/bangalore");
    driver.findElement(By.className("search")).click();
}

Console Log Capture

Enable console logging with Log.enable and listen to Log.entryAdded to print log text and level.

package com.devtools;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.log.Log;
public class CaptureConsoleLogs {
    private static ChromeDriver driver;
    private static DevTools chromeDevTools;
    final static String PROJECT_PATH = System.getProperty("user.dir");
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", PROJECT_PATH + "/src/main/resources/chromedriver");
        driver = new ChromeDriver();
        chromeDevTools = driver.getDevTools();
        chromeDevTools.createSession();
        chromeDevTools.send(Log.enable());
        chromeDevTools.addListener(Log.entryAdded(),
                logEntry -> {
                    System.out.println("log: " + logEntry.getText());
                    System.out.println("level: " + logEntry.getLevel());
                });
        driver.get("https://testersplayground.herokuapp.com/console-5d63b2b2-3822-4a01-8197-acd8aa7e1343.php");
    }
}

Performance Metrics

Enable performance collection with Performance.enable, navigate to a page, then retrieve metrics via Performance.getMetrics. The example prints a selected set of metrics.

package com.devtools;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.performance.Performance;
import org.openqa.selenium.devtools.performance.model.Metric;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class GetMetrics {
    final static String PROJECT_PATH = System.getProperty("user.dir");
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", PROJECT_PATH + "/src/main/resources/chromedriver");
        ChromeDriver driver = new ChromeDriver();
        DevTools devTools = driver.getDevTools();
        devTools.createSession();
        devTools.send(Performance.enable());
        driver.get("https://www.google.org");
        List<Metric> metrics = devTools.send(Performance.getMetrics());
        List<String> metricNames = metrics.stream()
                .map(o -> o.getName())
                .collect(Collectors.toList());
        devTools.send(Performance.disable());
        List<String> metricsToCheck = Arrays.asList(
                "Timestamp", "Documents", "Frames", "JSEventListeners",
                "LayoutObjects", "MediaKeySessions", "Nodes",
                "Resources", "DomContentLoaded", "NavigationStart");
        metricsToCheck.forEach(metric ->
                System.out.println(metric + " is : " + metrics.get(metricNames.indexOf(metric)).getValue()));
    }
}

Basic Authentication

Browser authentication dialogs cannot be handled directly by Selenium. Using CDP’s Network.setExtraHTTPHeaders you can send an Authorization header to bypass the popup.

package com.devtools;
import org.apache.commons.codec.binary.Base64;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.network.Network;
import org.openqa.selenium.devtools.network.model.Headers;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class SetAuthHeader {
    private static final String USERNAME = "guest";
    private static final String PASSWORD = "guest";
    final static String PROJECT_PATH = System.getProperty("user.dir");
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", PROJECT_PATH + "/src/main/resources/chromedriver");
        ChromeDriver driver = new ChromeDriver();
        DevTools chromeDevTools = driver.getDevTools();
        chromeDevTools.createSession();
        chromeDevTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
        driver.get("https://jigsaw.w3.org/HTTP/");
        Map<String, Object> headers = new HashMap<>();
        String basicAuth = "Basic " + new String(new Base64().encode(String.format("%s:%s", USERNAME, PASSWORD).getBytes()));
        headers.put("Authorization", basicAuth);
        chromeDevTools.send(Network.setExtraHTTPHeaders(new Headers(headers)));
        driver.findElement(By.linkText("Basic Authentication test")).click();
        String loginSuccessMsg = driver.findElement(By.tagName("html")).getText();
        if (loginSuccessMsg.contains("Your browser made it!")) {
            System.out.println("Login successful");
        } else {
            System.out.println("Login failed");
        }
        driver.quit();
    }
}

Conclusion

By adding CDP support, Selenium 4 becomes far more powerful. You can capture HTTP traffic, gather performance data, handle authentication, and simulate geolocation, time zones, and device metrics—all directly from Chrome DevTools.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javatestingChrome DevToolsSeleniumCDP
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.