Chrome DevTools Protocol (CDP) with Selenium – Complete Guide
Chrome DevTools Protocol (CDP) is a protocol that allows automation tools like Selenium to communicate directly with the Chrome browser and access advanced browser capabilities.
Selenium 4 supports CDP integration, allowing you to perform advanced browser automation tasks such as:
- Network request interception.
- Mock API responses.
- Capture console logs.
- Handle authentication.
- Set geolocation.
- Block images and CSS.
- Capture performance metrics.
- Monitor HTTP requests and responses.
- Simulate device settings.
- Capture browser console errors.
1. What is Chrome DevTools Protocol?
CDP stands for Chrome DevTools Protocol.
It provides a way to communicate with the Chrome browser using different domains.
| CDP Domain | Purpose |
|---|---|
| Network | Monitor network requests and responses |
| Page | Manage browser pages and screenshots |
| Runtime | Execute JavaScript |
| Log | Capture browser logs |
| Performance | Collect performance metrics |
| Emulation | Simulate devices and geolocation |
| Fetch | Intercept and modify requests |
| Security | Manage browser security settings |
2. Selenium 4 CDP setup
Maven dependency:
Use Selenium 4 and a CDP module compatible with your Chrome DevTools Protocol version.
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.39.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-devtools-vNN</artifactId>
<version>4.39.0</version>
</dependency>
</dependencies>
Replace vNN with the supported CDP version available for your Selenium release. Check the Selenium release documentation for the matching module.
3. Create a ChromeDriver with CDP
Selenium provides the DevTools interface.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
public class CDPDemo {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
driver.get("https://www.google.com");
driver.quit();
}
}
Explanation:
- Create ChromeDriver.
- Get the DevTools instance.
- Create a CDP session.
- Open the application.
- Close the browser.
4. Capture Network Requests
You can monitor all network requests sent by the browser.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.vNN.network.Network;
import java.util.Optional;
public class NetworkExample {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Network.enable(
Optional.empty(),
Optional.empty(),
Optional.empty()
));
devTools.addListener(
Network.requestWillBeSent(),
request -> {
System.out.println(
"Request URL: " +
request.getRequest().getUrl()
);
}
);
driver.get("https://www.google.com");
driver.quit();
}
}
Sample output:
Request URL: https://www.google.com/
Request URL: https://www.google.com/images/...
Request URL: https://www.google.com/...
5. Capture HTTP Response Status Codes
You can capture HTTP response status codes using CDP.
devTools.addListener(
Network.responseReceived(),
response -> {
System.out.println(
"URL: " + response.getResponse().getUrl()
);
System.out.println(
"Status Code: " +
response.getResponse().getStatus()
);
}
);
Sample output:
URL: https://example.com/
Status Code: 200
URL: https://example.com/api/users
Status Code: 200
URL: https://example.com/api/products
Status Code: 404
This is useful for API monitoring during UI automation.
6. Capture Browser Console Logs
You can capture JavaScript console messages.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.vNN.log.Log;
public class ConsoleLogs {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Log.enable());
devTools.addListener(
Log.entryAdded(),
entry -> {
System.out.println(
"Level: " + entry.getLevel()
);
System.out.println(
"Message: " + entry.getText()
);
}
);
driver.get("https://example.com");
driver.quit();
}
}
Sample output:
Level: error
Message: Uncaught TypeError
Level: warning
Message: Resource loading failed
7. Block Images Using CDP
You can block images to improve page-loading speed during testing.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.vNN.network.Network;
import java.util.List;
import java.util.Optional;
public class BlockImages {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Network.enable(
Optional.empty(),
Optional.empty(),
Optional.empty()
));
devTools.send(
Network.setBlockedURLs(
List.of("*.png", "*.jpg", "*.jpeg")
)
);
driver.get("https://example.com");
driver.quit();
}
}
8. Mock API Response Using CDP
One of the most useful features for automation testers is API mocking.
You can intercept network requests and provide custom responses using the CDP Fetch domain.
Example: Mock a user API response.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.vNN.fetch.Fetch;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
public class MockAPI {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(
Fetch.enable(
Optional.of(List.of(
new Fetch.RequestPattern(
Optional.of("*api/users*"),
Optional.empty(),
Optional.of(
Fetch.RequestStage.REQUEST
)
)
)),
Optional.empty()
)
);
devTools.addListener(
Fetch.requestPaused(),
request -> {
String json = """
{
"id": 101,
"name": "Sumit",
"role": "QA Engineer"
}
""";
String body = Base64.getEncoder()
.encodeToString(
json.getBytes()
);
devTools.send(
Fetch.fulfillRequest(
request.getRequestId(),
200,
Optional.of(List.of(
new Fetch.HeaderEntry(
"Content-Type",
"application/json"
)
)),
Optional.empty(),
Optional.of(body),
Optional.empty()
)
);
}
);
driver.get("https://example.com");
driver.quit();
}
}
Note: This example illustrates request interception. Adapt the URL pattern, request stage and response headers to the application. The page must actually issue the matching API request.
9. Set Geolocation Using CDP
You can simulate a different geographical location.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.vNN.emulation.Emulation;
import java.util.Optional;
public class GeoLocation {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(
Emulation.setGeolocationOverride(
Optional.of(28.6139),
Optional.of(77.2090),
Optional.of(10)
)
);
driver.get("https://www.google.com");
driver.quit();
}
}
Expected location: New Delhi, India.
10. Capture Performance Metrics
CDP allows you to retrieve browser performance metrics.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.vNN.performance.Performance;
public class PerformanceExample {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Performance.enable());
driver.get("https://example.com");
devTools.send(Performance.getMetrics())
.forEach(metric -> {
System.out.println(
metric.getName() + " : " +
metric.getValue()
);
});
driver.quit();
}
}
Sample output:
Timestamp : 123456.78
Documents : 1
Frames : 1
JSEventListeners : 10
Nodes : 100
LayoutCount : 5
RecalcStyleCount : 3
The values above are illustrative; actual metrics depend on the page.
11. Capture Screenshots Using Selenium
You can capture screenshots through Selenium's screenshot API. CDP also provides screenshot functionality through the Page domain.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.vNN.page.Page;
import java.util.Base64;
public class CDPScreenshot {
public static void main(String[] args) throws Exception {
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
driver.get("https://example.com");
var screenshot = devTools.send(
Page.captureScreenshot(
java.util.Optional.empty(),
java.util.Optional.empty(),
java.util.Optional.empty(),
java.util.Optional.empty(),
java.util.Optional.empty(),
java.util.Optional.empty()
)
);
byte[] imageBytes = Base64.getDecoder()
.decode(screenshot);
java.nio.file.Files.write(
java.nio.file.Path.of("screenshot.png"),
imageBytes
);
driver.quit();
}
}
12. Selenium CDP vs Selenium WebDriver
| Feature | Selenium WebDriver | CDP |
|---|---|---|
| Click elements | Yes | Not its primary purpose |
| Enter text | Yes | Possible through lower-level commands |
| Find elements | Yes | Not its primary purpose |
| Network interception | Limited/native support varies | Yes |
| Mock API responses | Limited | Yes |
| Browser console logs | Yes, through supported logging APIs | Yes |
| Performance metrics | Limited | Yes |
| Geolocation override | Limited | Yes |
| Block network URLs | Limited | Yes |
| Execute JavaScript | Yes | Yes |
13. Important CDP Use Cases in Automation Testing
| Scenario | CDP feature |
|---|---|
| Validate API calls | Network |
| Verify HTTP response codes | Network |
| Mock backend responses | Fetch |
| Capture JavaScript errors | Log |
| Test location-based functionality | Emulation |
| Improve page-loading speed | Network |
| Capture performance metrics | Performance |
| Test mobile device behavior | Emulation |
| Capture screenshots | Page |
14. CDP vs WebDriver BiDi
Selenium is also moving toward WebDriver BiDi, a browser-automation standard that supports bidirectional communication.
| Feature | CDP | WebDriver BiDi |
|---|---|---|
| Standard | Chrome DevTools protocol | W3C WebDriver standard |
| Browser support | Primarily Chromium | Cross-browser design |
| Network events | Yes | Yes |
| Console events | Yes | Yes |
| Browser-specific functionality | Extensive | Standardized capabilities |
| Selenium integration | Yes | Yes |
Recommendation: Prefer WebDriver BiDi for cross-browser capabilities where supported. Use CDP when you need Chrome-specific functionality.
15. Interview Questions on Selenium CDP
Q1. What is CDP in Selenium?
CDP is Chrome DevTools Protocol. Selenium 4 uses it to interact with Chrome's internal browser functionality.
Q2. What is the difference between CDP and WebDriver?
WebDriver primarily automates browser interactions, whereas CDP provides access to advanced browser-level features such as network monitoring and performance metrics.
Q3. Can we mock API responses using Selenium CDP?
Yes. We can use the CDP Fetch domain to intercept requests and fulfill them with custom responses.
Q4. Can we capture browser console errors using CDP?
Yes. We can use the Log domain and its entryAdded event.
Q5. Can we block images using CDP?
Yes. We can use Network.setBlockedURLs().
Q6. Is CDP supported in Firefox?
CDP is primarily a Chromium protocol. For cross-browser automation, consider WebDriver BiDi.
Q7. What is the DevTools interface in Selenium?
It provides methods to create CDP sessions, send commands and register event listeners.
16. Recommended learning order
Selenium CDP learning roadmap
-
CDP fundamentals
Understand DevTools, domains and sessions.
-
Network monitoring
Capture requests, responses and status codes.
-
API mocking
Intercept requests and return custom JSON responses.
-
Browser logging
Capture console errors and warnings.
-
Emulation
Geolocation, device settings and network conditions.
-
Performance testing
Collect browser metrics and analyze page performance.
-
WebDriver BiDi
Learn modern cross-browser event-driven automation.
Useful official documentation
I can also provide a complete Java + Selenium 4 + TestNG CDP automation framework with reusable utilities for network monitoring, API mocking, console logs, performance testing and HTML reporting.

No comments:
Post a Comment