ScreenshotNeo

BlogGuides

Selenium Chrome DevTools Protocol (CDP): How It Works

Learn how Selenium uses CDP commands and events, when version matching matters, and when WebDriver BiDi is a better fit.

By the ScreenshotNeo team4 October 20269 min read

Selenium’s Chrome DevTools Protocol (CDP) support lets automation code call browser-specific Chrome and Edge capabilities beyond the ordinary WebDriver commands. A CDP command asks the browser to do something; CDP events let code react to browser activity. CDP is version-sensitive and Selenium says it is temporary while WebDriver BiDi is implemented. For new cross-browser, event-driven automation, evaluate BiDi; use CDP when a needed browser capability is available there and you can manage browser-version compatibility.

What is CDP in Selenium?

Chrome DevTools Protocol is the protocol used by Chrome DevTools to communicate with a Chromium-based browser. Selenium exposes ways to send CDP commands through Chrome and Edge drivers, along with generated domain APIs for commonly used parts of the protocol. The protocol is browser-specific; it is not a cross-browser WebDriver standard. Selenium cautions that CDP was not designed as a stable testing API and that functionality depends heavily on browser version. See the Selenium CDP documentation.

Traditional WebDriver interactions are primarily request and response: the client sends an action and waits for its result. CDP also supports commands, and its bidirectional connection can carry asynchronous events. For example, code can issue a network command and separately listen for network activity. Selenium’s Python CDP API documents command execution, event listeners, event waiting, and root connections that can multiplex sessions. These Python interfaces are implementation details; do not assume other Selenium language bindings expose identical APIs.

How Selenium CDP works

  1. Your test creates a WebDriver session. Selenium starts or connects to a browser through its driver.
  2. Your code issues a protocol command. The driver provides a CDP entry point or a generated domain method. The command includes a protocol method and its parameters.
  3. The browser executes it. The response contains a result or an error. A command may require enabling a protocol domain before its events are delivered.
  4. Your test continues with WebDriver or handles events. Use ordinary WebDriver for normal navigation and element interaction; use CDP where it supplies a capability WebDriver does not expose in the workflow you need.

CDP does not replace WebDriver. A practical test often uses WebDriver for navigation and assertions and a targeted CDP command for a browser-specific operation. Selenium’s documentation warns that the basic executeCdpCommand-style access does not support features requiring bidirectional communication; event-driven work needs an API that supports the connection and event handling.

Send a CDP command in Selenium

This Python example sets a cookie through CDP, navigates to the matching origin, then reads the cookie through WebDriver. It follows Selenium’s documented command pattern. Run it with Selenium 4, a compatible Chrome installation, and Selenium Manager or a configured ChromeDriver.

from selenium import webdriver

options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)

try:
    driver.execute_cdp_cmd(
        "Network.setCookie",
        {
            "name": "session_hint",
            "value": "example",
            "url": "https://example.com/",
        },
    )
    driver.get("https://example.com/")
    cookie = driver.get_cookie("session_hint")
    print(cookie)
finally:
    driver.quit()

Use a real cookie name, value, and URL appropriate to your test. Cookies are scoped by browser rules such as host, path, security attributes, and expiry. A cookie for one host will not appear on another. Do not put real credentials or session secrets in source code or logs.

The exact command and parameter names are protocol-defined. Check the documentation for the domain and command supported by the browser version in your environment. Selenium’s generated domain APIs can offer stronger structure for supported commands; the basic command method is useful for direct calls but does not remove protocol-version coupling.

Commands, domains, events, and sessions

Concept What it means What to watch
Domain A group of related protocol methods and events, such as Network or Page. Some domains must be enabled before their events are emitted.
Command A request to perform an operation, with named parameters and a result. Method names, parameter shapes, and results can vary with protocol versions.
Event An asynchronous message from the browser about something that happened. Basic command helpers may not expose event streaming.
Session A connection context associated with a browser target. Advanced CDP APIs may route commands and events by session; manage lifecycle and cleanup.

The Selenium Python CDP API includes execute, listen, and wait_for operations, plus connection and session helpers. Its documentation describes a root connection that reads WebSocket messages and forwards them to the appropriate session. Use the API reference for the Selenium version installed in your project: Selenium Python CDP API reference.

Version matching and compatibility

Version compatibility is the main maintenance cost of CDP. Selenium’s documentation says methods and implementations can change and advises keeping Chrome and DevTools versions aligned. The Selenium documentation describes support for the three most recent Chrome versions at any given time, so always check the documentation and release notes corresponding to your installed Selenium version.

For example, Selenium 4.40’s January 18, 2026 release announcement listed DevTools support for versions 144, 143, and 142. That is a dated snapshot, not a current support guarantee. Consult the Selenium 4.40 release announcement only when assessing that release.

  • Pin or record Selenium and browser versions in CI so a browser update does not silently change protocol behavior.
  • When upgrading Chrome, upgrade Selenium as needed and review its supported DevTools versions.
  • Keep protocol calls narrow and isolated so a version-specific change has a small repair surface.
  • When a generated DevTools module is unavailable for the browser version, check the binding’s supported versions and API before changing imports or command names.

CDP or WebDriver BiDi?

WebDriver BiDi is Selenium’s standards-based direction for bidirectional browser automation. It adds a WebSocket connection to WebDriver so scripts can stream and react to events. Selenium positions it as the cross-browser replacement for CDP and states that CDP support is temporary until BiDi is implemented. BiDi implementations and available features continue to evolve, so verify support for your browser, binding, and specific feature before depending on it. Read Selenium’s WebDriver BiDi documentation.

Question Choose CDP when… Consider BiDi when…
Browser scope You target Chrome or another compatible Chromium browser and need a capability exposed by CDP. You need a standards-based path intended to work across browsers.
Stability You can pin versions and maintain browser-specific integration code. You want to build toward Selenium’s stated stable cross-browser direction, and your required feature is supported.
Events Your chosen Selenium API exposes the needed CDP event connection and you can manage its lifecycle. You need bidirectional event streaming through the BiDi WebSocket API.
Migration A required feature is available only through CDP in your current setup. BiDi supports the feature in your binding and target browsers; migrate deliberately and verify behavior.

Do not assume every feature has a one-to-one BiDi replacement today. Compare the specific browser capability and binding API you depend on, then test that behavior across the browsers you support.

Limitations and edge cases

  • Not browser-independent: CDP commands are tied to Chromium protocol behavior. They are not portable WebDriver commands.
  • Not a stable testing contract: Selenium warns that CDP was not designed as a stable testing API. Treat protocol changes as an upgrade risk.
  • One-way helper limitations: A basic command call is not sufficient for features that require bidirectional communication or event subscriptions.
  • Domain setup: Event workflows may require enabling the relevant domain before subscribing or triggering the browser action.
  • Geolocation: Emulating browser geolocation may not change a site’s inferred location if it uses the client IP address.
  • Mobile behavior: Selenium notes that Chrome Options’ mobile emulation API is generally preferable to overriding device metrics through CDP.
  • Lifecycle and concurrency: Close CDP connections and sessions when done. In the Python API, a closed connection causes subsequent public calls to raise CdpConnectionClosed; session routing matters when several targets are involved.

Troubleshooting Selenium CDP

Symptom Likely cause Fix
Unknown method or invalid parameters The command name or parameter structure is wrong, or the browser protocol version differs from the API you followed. Check the method’s domain documentation and parameter names for the running browser version. Keep the call minimal and inspect the returned browser error.
DevTools module or command is unavailable The Selenium binding does not include generated support for that browser protocol version. Check Selenium’s versioned DevTools support and release notes; align Selenium and Chrome versions or use a supported command path.
Command works but no event arrives The workflow uses a command-only helper, the domain was not enabled, the listener was attached too late, or the event belongs to another target/session. Use a bidirectional event API, enable the correct domain, register the listener before triggering the action, and confirm the target/session.
Cookie is missing after navigation The cookie URL or domain does not match, or cookie attributes prevent it being sent/read. Set a URL on the intended origin, check path and security attributes, and read it only after navigating to that origin.
Behavior changes after a browser update The protocol implementation or generated bindings changed. Review Selenium’s supported versions and release notes, then update or pin versions and adjust the affected command.
Geolocation test reports the wrong region The page may infer region from IP rather than browser-provided geolocation. Check how the application determines location; CDP geolocation emulation only affects browser geolocation signals.
Connection closed errors in Python CDP code The connection context exited or the connection was explicitly closed before a command or listener completed. Keep work inside the connection/session context and close it only after awaited commands and event handling finish.

Performance, reliability, and cost

CDP does not make browser automation inherently faster. It gives access to browser operations and event streams; overall run time still depends on browser startup, page loading, network conditions, waits, and the work your test performs. Avoid adding protocol calls when a normal WebDriver operation already expresses the task. Subscribe only to events needed by the test and remove listeners or close contexts when finished.

For reliability, manage the browser and Selenium versions as a pair, keep protocol-specific code in a small adapter, and verify behavior after upgrades. A CDP call can fail because the browser rejects its parameters, the relevant domain is not enabled, a target session is wrong, or a connection has closed. Handle those failures as browser automation errors rather than assuming the command is portable.

CDP itself has no separate protocol fee in the Selenium workflow described here. The operational costs are the machines, browser execution time, CI capacity, and engineering time spent maintaining version-sensitive behavior. No independent benchmark or reliability figure is established by the sources for this guide.

Or skip the browser setup

For screenshots rather than browser automation, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. It takes a URL in one GET request and returns a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie and consent banners, newsletter popups, and chat widgets are handled before capture; each cleanup step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and billing status.
  • An MCP server gives AI agents tools for screenshots, page information, and PDF capture.
  • The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan.

Sign up for 1,000 free screenshots a month, with no card required.

FAQ

Is CDP part of the WebDriver standard?

No. CDP is a browser protocol used by Chrome DevTools. WebDriver BiDi is Selenium’s standards-based bidirectional direction.

Can I use Selenium CDP commands with Firefox or Safari?

Do not assume so. CDP use in Selenium is Chromium-oriented and browser-version-dependent; use WebDriver features or check BiDi support for your target browser and feature.

Does every Selenium language expose the same CDP event API?

No. Selenium’s Python CDP reference documents Python-specific connection, session, command, and event helpers. Check the documentation for your language binding.

Should I replace all CDP code with BiDi now?

Not automatically. Check that BiDi in your binding and browsers supports the specific capability you use, then migrate and verify that behavior.

Sources