Resource library

QA How-To

Selenium BiDi Automation Complete Guide (2026)

Selenium BiDi automation complete guide 2026: set up Java and Python tests for network interception, authentication, console errors, and reliable CI runs.

24 min read | 3,391 words

TL;DR

Enable WebDriver BiDi when the Selenium session starts, then use the public Network and Script APIs to subscribe to events or control traffic. Build reliable tests by registering before the triggering action, matching exact evidence, applying timeouts, sanitizing artifacts, and cleaning up every handler.

Key Takeaways

  • Enable BiDi in browser options before creating the WebDriver session.
  • Prefer Selenium's public high-level BiDi modules over internal protocol classes.
  • Register listeners before the action, filter narrowly, and synchronize with bounded waits.
  • Resolve every intercepted request exactly once by continuing, failing, or authenticating it.
  • Keep handlers scoped to one test and remove them before quitting the driver.
  • Treat network and log evidence as support for product assertions, not a replacement for them.
  • Verify each required feature against every browser and Grid image in your support matrix.

The selenium bidi automation complete guide 2026 shows you how to build event-driven browser tests with Selenium's standards-based WebDriver BiDi support. You will enable the bidirectional connection, observe requests and responses, intercept traffic, handle browser authentication, capture JavaScript failures, and design the same features for reliable CI execution.

Classic WebDriver remains the right tool for clicks, locators, navigation, and assertions. BiDi adds a persistent event channel through which the browser can report activity while the session runs and accept selected commands. Use both together: drive the user journey with WebDriver, then use BiDi where browser-level evidence or control proves a real risk.

This is a practical pillar guide. The examples use public Selenium APIs and small, controlled pages. Browser implementations and language bindings can expose capabilities at different times, so validate every feature against the exact Selenium, browser, driver, and Grid combination that your team supports.

TL;DR: Selenium BiDi Automation Complete Guide 2026

Goal Public Selenium surface Reliable test pattern
Observe requests and responses Java Network event callbacks Subscribe, trigger one action, wait for an exact match
Intercept a Python request driver.network.add_request_handler Resolve every callback with continue or fail
Supply browser authentication Network authentication handler Install before navigation and remove after the scenario
Capture console calls Script console-message handler Collect typed entries in a test-scoped list
Capture uncaught JavaScript errors Script JavaScript-error handler Wait for a specific error and retain its stack
Test degraded connectivity Supported network emulation or controlled interception Assert the user-visible fallback, then restore state

BiDi is not a synonym for Chrome DevTools Protocol. WebDriver BiDi is a W3C standards effort designed for interoperable browser automation. CDP is Chromium's debugging protocol. Prefer Selenium's public BiDi feature when it covers the requirement, and isolate any necessary browser-specific fallback.

What You Will Build

By the end of this guide, you will have a small cross-language reference suite that can:

  • Start Chrome or Firefox with a negotiated BiDi WebSocket connection.
  • Observe a navigation request and completed response in Java.
  • Intercept, inspect, and continue selected requests in Python.
  • Supply credentials to a browser-level HTTP authentication challenge.
  • Capture console messages and uncaught JavaScript exceptions.
  • Model network degradation without turning the entire suite into a slow test.
  • Produce bounded, sanitized diagnostics that work locally and on Grid.

The examples deliberately separate observation from control. A passive listener should not change traffic. An intercept that changes or fails traffic belongs to a focused resilience test whose name makes that behavior obvious. This separation prevents a diagnostic helper from becoming the cause of the defect it reports.

You will also learn where BiDi does not belong. Direct API tests remain faster and clearer for broad schema, status, authorization, and business-rule coverage. A BiDi assertion is valuable when the question is specifically about what a real browser sent, received, logged, or displayed during a user flow.

Prerequisites

Use Java 17 or later for the Java example, Python 3.11 or later for the Python example, and a current Selenium 4 release that exposes the APIs shown here. The examples pin Selenium 4.46.0 for reproducibility. If your organization has approved a later compatible release, pin that release consistently in developer machines and CI rather than floating to the newest package on every run.

For Maven, create a normal test project and add Selenium plus JUnit Jupiter:

<dependencies>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.46.0</version>
  </dependency>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.11.4</version>
    <scope>test</scope>
  </dependency>
</dependencies>

For Python, create and activate a virtual environment, then install pinned packages:

python -m venv .venv
source .venv/bin/activate
python -m pip install selenium==4.46.0 pytest==8.3.5

Install a current stable Chrome or Firefox build. Selenium Manager can resolve a compatible local driver in ordinary environments. On Grid, use an explicitly versioned node image and record its Selenium server, browser, and driver versions in failure diagnostics. Never assume that a session supporting one BiDi event automatically supports every newer command.

Verification: Run java -version, python --version, and your browser's version command. Then confirm the dependency resolver completes without an unpinned Selenium version.

Step 1: Enable and Verify the BiDi Session

BiDi must be requested during session creation. Capabilities are negotiated once, so setting an option after new ChromeDriver() or webdriver.Chrome() is too late. In Java, use the browser option's enableBiDi() method:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class BidiSmoke {
  public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions().enableBiDi();
    WebDriver driver = new ChromeDriver(options);
    try {
      Object webSocketUrl = driver.getCapabilities()
          .getCapability("webSocketUrl");
      if (!(webSocketUrl instanceof String)) {
        throw new IllegalStateException("BiDi WebSocket URL is missing");
      }
      System.out.println("BiDi enabled: " + webSocketUrl);
    } finally {
      driver.quit();
    }
  }
}

Python exposes the capability through enable_bidi on browser options:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.enable_bidi = True

driver = webdriver.Chrome(options=options)
try:
    web_socket_url = driver.capabilities.get('webSocketUrl')
    assert isinstance(web_socket_url, str) and web_socket_url
    print('BiDi enabled:', web_socket_url)
finally:
    driver.quit()

Do not log the complete WebSocket URL in shared CI artifacts. It is session infrastructure data and may contain connection details. The print is useful only for a disposable local smoke test. In production diagnostics, report whether the capability exists and record the browser versions.

Verification: Both programs should open a browser, print a nonempty capability, and exit. If the capability is absent on Grid, inspect the returned capabilities and node image before debugging any listener code.

Step 2: Observe a Request and Response in Java

Create Selenium's typed Network module only after a BiDi-enabled driver exists. Register callbacks before navigation because events are not replayed. Use CompletableFuture to transfer one matching asynchronous event back to the test thread with a timeout.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.module.Network;
import org.openqa.selenium.bidi.network.BeforeRequestSent;
import org.openqa.selenium.bidi.network.ResponseDetails;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

class ObserveTrafficTest {
  @Test
  void observesNavigation() throws Exception {
    WebDriver driver = new ChromeDriver(
        new ChromeOptions().enableBiDi());
    String url = "https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html";

    try (Network network = new Network(driver)) {
      CompletableFuture<BeforeRequestSent> request =
          new CompletableFuture<>();
      CompletableFuture<ResponseDetails> response =
          new CompletableFuture<>();

      network.onBeforeRequestSent(event -> {
        if (url.equals(event.getRequest().getUrl())) request.complete(event);
      });
      network.onResponseCompleted(event -> {
        if (url.equals(event.getRequest().getUrl())) response.complete(event);
      });

      driver.get(url);

      BeforeRequestSent sent = request.get(8, TimeUnit.SECONDS);
      ResponseDetails completed = response.get(8, TimeUnit.SECONDS);
      assertEquals("GET", sent.getRequest().getMethod().toUpperCase());
      assertEquals(200, completed.getResponseData().getStatus());
      assertTrue(completed.getResponseData().getMimeType().contains("html"));
    } finally {
      driver.quit();
    }
  }
}

Filter inside each callback. Browsers request favicons, stylesheets, redirects, and scripts, so the first event is rarely a safe business assertion. Do not execute JUnit assertions inside the callback because a failure on a listener thread may not reach the test correctly. Capture the event, then assert on the test thread.

Verification: Run the JUnit test and confirm that both futures complete before eight seconds. Temporarily change the expected URL to a nonexistent path and verify that the test fails with a bounded timeout instead of hanging indefinitely.

Step 3: Intercept Network Requests in Python

Python's high-level network API can install a before_request handler. That handler creates an interception point, which means every callback path must resolve the request exactly once. Continue traffic that you only observe, and fail traffic only when a focused test intends to simulate a transport error.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

def test_observes_document_request():
    options = webdriver.ChromeOptions()
    options.enable_bidi = True
    driver = webdriver.Chrome(options=options)
    observed = []

    def inspect_and_continue(request):
        try:
            if request.url and 'selenium.dev' in request.url:
                observed.append((request.method, request.url))
        finally:
            request.continue_request()

    handler_id = driver.network.add_request_handler(
        'before_request', inspect_and_continue
    )
    try:
        driver.get('https://www.selenium.dev/')
        WebDriverWait(driver, 8).until(
            lambda _driver: any(
                method == 'GET' and url == 'https://www.selenium.dev/'
                for method, url in observed
            )
        )
    finally:
        driver.network.remove_request_handler(
            'before_request', handler_id
        )
        driver.quit()

The finally inside the callback ensures observation cannot accidentally stall traffic. In a mutation test, use an explicit branch: call request.fail_request() for the exact target and request.continue_request() for everything else. Never continue after failing, and never let an unmatched intercepted request remain paused.

Match a test-owned host and exact path before modifying headers, method, body, or URL. Broad mutation can create cross-origin preflights, leak test markers to third parties, or alter unrelated resources. See the focused Python Selenium BiDi request interception tutorial before introducing request changes into a shared framework.

Verification: Run pytest -q. The test should complete and the home page should load normally. Remove request.continue_request() locally and observe the navigation timeout, then restore it. This controlled failure demonstrates why every intercept needs a resolution.

Step 4: Handle Browser Authentication Challenges

HTTP Basic and Digest prompts belong to browser chrome, not the page DOM. Do not locate the prompt with CSS or place production credentials in a URL. Use a BiDi authentication handler, register it before navigation, and remove it immediately after the protected journey.

import os
from selenium import webdriver

def test_basic_authentication():
    options = webdriver.ChromeOptions()
    options.enable_bidi = True
    driver = webdriver.Chrome(options=options)

    username = os.environ.get('BIDI_TEST_USER', 'admin')
    password = os.environ.get('BIDI_TEST_PASSWORD', 'admin')
    auth_id = driver.network.add_auth_handler(username, password)
    try:
        driver.get('https://the-internet.herokuapp.com/basic_auth')
        assert 'Congratulations' in driver.page_source
    finally:
        driver.network.remove_auth_handler(auth_id)
        driver.quit()

The defaults above are public demonstration credentials for the public demonstration page. In your suite, require secrets from a CI secret store, restrict them to a disposable test environment, and never print headers, cookies, or passwords. Scope the driver and handler to one test so later traffic cannot receive credentials unexpectedly.

Java's lower-level typed Network flow uses an intercept at the authentication-required phase, listens for the authentication event, and continues with UsernameAndPassword. That path gives more control for positive and negative cases. The Java Selenium BiDi authentication handler tutorial builds the complete JUnit version and explains cancellation and cleanup.

Verification: Run once with the correct demonstration credentials and assert the success text. Run a separate negative test with wrong credentials and assert the protected content is absent. Never make a negative test mutate the credentials of a concurrently running positive test.

Step 5: Capture Console Messages and JavaScript Errors

A console call and an uncaught exception are different signals. console.error() is application-selected output and does not throw. An uncaught Error interrupts JavaScript execution unless the application handles it. Keep separate collectors so reports preserve this distinction.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

def test_captures_frontend_failures():
    options = webdriver.ChromeOptions()
    options.enable_bidi = True
    driver = webdriver.Chrome(options=options)
    console_entries = []
    javascript_errors = []

    console_id = driver.script.add_console_message_handler(
        console_entries.append
    )
    error_id = driver.script.add_javascript_error_handler(
        javascript_errors.append
    )
    try:
        driver.get('data:text/html,<title>BiDi log test</title>')
        driver.execute_script(
            "console.error('inventory failed');"
            "setTimeout(() => { throw new Error('render failed'); }, 0);"
        )
        WebDriverWait(driver, 5).until(
            lambda _driver: len(javascript_errors) > 0
        )
        assert any('inventory failed' in entry.text
                   for entry in console_entries)
        assert 'render failed' in javascript_errors[0].text
    finally:
        driver.script.remove_console_message_handler(console_id)
        driver.script.remove_javascript_error_handler(error_id)
        driver.quit()

Keep callbacks lightweight. Append typed entries, then perform filtering, redaction, and assertions on the test thread. Install handlers before navigation when bootstrap errors matter. A listener added afterward cannot reconstruct events from the past.

Do not fail every test on every warning. Third-party scripts, browser policy messages, and expected negative paths can produce noise. Define a product-owned policy using structured level, source, phase, and precise signatures. Learn the separate event shapes and policy patterns in Selenium BiDi JavaScript error examples.

Verification: The test must collect both messages and remove both handlers even if an assertion fails. Change the emitted error text and verify that the relevant assertion fails with captured evidence, rather than a generic sleep-based timeout.

Step 6: Test Network Degradation Safely

Network degradation tests should prove a customer behavior, such as a loading indicator, retry action, offline notice, or graceful fallback. They should not merely prove that a throttling command ran. Support for latency, throughput, and offline emulation varies across browser implementations and Selenium binding surfaces, so feature-detect the capability and run it only in the browser matrix where your team has verified it.

When the public emulation feature is available in your approved binding, isolate it in a helper with an explicit lifecycle:

1. Start a fresh BiDi-enabled session.
2. Apply the supported latency or offline condition.
3. Trigger one test-owned request.
4. Assert the loading and recovery UI with bounded waits.
5. Restore normal conditions in teardown, even after failure.
6. Quit the isolated session before another test begins.

Do not invent a convenient method name or copy a CDP command into a class labeled BiDi. If your required browser does not yet expose the standards-based feature, choose a deliberate alternative: fail one request through an intercept, configure a test server delay, or use a controlled proxy. Record that choice as browser-specific infrastructure.

A transport failure is not the same as HTTP 500, and latency is not the same as offline mode. Test each only when the product has a distinct requirement. The Selenium BiDi network conditions tutorial covers the verified current APIs and cleanup strategy in depth.

Verification: Measure product state, not an arbitrary wall-clock threshold. Confirm the fallback appears under the condition, restore normal networking, click Retry, and assert success. A second ordinary navigation in the same teardown check should prove that network state did not leak.

Step 7: Build Test-Scoped Fixtures and Diagnostics

Handlers, intercepts, event collections, and browser state belong to one WebDriver session. Prefer function-scoped fixtures until you have a proven pool that resets every handler and browsing context. A global traffic recorder increases memory use, mixes parallel tests, and creates a security risk.

Your framework helper should expose business-focused operations such as awaitCreateOrderResponse() or failRecommendationsRequest(), not a bag of generic URL-substring callbacks. Keep observation helpers separate from mutation helpers. Give every wait a timeout and a message containing the expected method, sanitized host and path, browser version, and a short sample of observed URLs.

Capture only fields the assertion needs. Authorization headers, cookies, signed URLs, request bodies, and console text can contain secrets or personal data. Redact before persistence, restrict artifact access, and attach evidence to the individual test result. If a callback itself throws, capture that error in a thread-safe holder and surface it on the test thread.

For one expected event, use CompletableFuture in Java or a small list plus WebDriverWait in Python. For several events, use a thread-safe queue, map, or carefully synchronized collector. Avoid fixed sleeps and total request-count assertions because browsers legitimately emit different incidental resources.

Verification: Run two tests in parallel with different expected endpoint markers. Each test should report only its own events and artifact path. Force one assertion failure and confirm that cleanup still removes handlers, closes Network, and quits the associated driver.

Step 8: Run a Cross-Browser Grid Preflight

BiDi is designed for interoperability, but standards, browser implementations, Selenium modules, and Grid images evolve independently. Convert assumptions into a small preflight suite. For each supported browser, start a BiDi session, confirm webSocketUrl, observe one known event, execute the exact command families your product tests require, and cleanly close the connection.

Keep the preflight distinct from product tests. If authentication interception is unsupported, report an environment capability failure with the Selenium client, Grid server, node image, browser, and driver versions. Do not silently skip the product assertion and report a green result. That changes the meaning of the test.

Approach Best use Main tradeoff
WebDriver BiDi Portable live browser events and supported control Feature coverage varies by current implementation
Chrome DevTools Protocol A required Chromium-only capability Browser-specific and version-coupled
External proxy Cross-process traffic capture or advanced stubbing TLS trust and infrastructure complexity
Direct API client Service contracts and broad data coverage Does not prove real browser behavior
Test server controls Deterministic delays and responses Requires application or environment support

Run this preflight whenever Selenium, the browser image, Grid, or driver changes. Pin versions and promote upgrades through the same pipeline as application code. For general remote execution practices, use the Selenium Grid Docker setup guide.

Verification: Produce a compact support report per browser with pass, unsupported, or infrastructure failure for each required feature. A missing capability must fail preflight before the larger regression suite consumes expensive Grid time.

The Complete Series

Use this pillar as your map, then complete each focused tutorial for paste-and-run implementation detail:

Together, the series covers the most useful browser-observability and control workflows without hiding lifecycle details. Start with event capture because it is passive, add authentication where a real browser challenge exists, then introduce interception or degradation only for explicit resilience requirements.

Troubleshooting

webSocketUrl is missing -> Enable BiDi on browser options before driver creation. On Grid, inspect returned capabilities and verify server, node, browser, and driver compatibility. A client upgrade alone cannot create remote-end support.

The callback never fires -> Register it before navigation or the triggering click. Match the exact method, host, path, and browsing context. Print a small sanitized sample of observed events so an unexpected redirect is visible.

Navigation hangs after adding a request handler -> One callback path left the request blocked. Ensure every intercepted request is continued, failed, or otherwise resolved exactly once, including unmatched traffic and exception paths.

The test passes locally but times out on Grid -> Replace fixed sleeps with bounded event conditions, confirm the WebSocket capability on the remote session, and record image versions. Check whether the required event or command is implemented by that browser build.

Events appear in the wrong parallel test -> Stop sharing a driver, Network object, list, or static callback across tests. Scope all state to one session and use unique correlation data plus per-test artifacts.

Console enforcement creates noisy failures -> Separate explicit console calls from uncaught exceptions. Filter by product ownership, severity, phase, and stable signature. Give temporary allowlist entries an owner, issue, and expiry.

Where To Go Next

Choose the next tutorial according to the risk you need to prove. For protected staging environments, begin with authentication. For UI-to-service integration, learn request observation and interception. For front-end reliability, capture JavaScript exceptions. For recovery experiences, isolate network degradation. All four focused guides are linked in The Complete Series above.

Then move repeated setup into a small adapter owned by the test fixture. Keep typed protocol objects inside the adapter and expose product language to tests. Add a Grid preflight before enabling the feature across a regression suite. Finally, review artifact redaction with your security team because browser traffic and logs routinely contain sensitive values.

Do not convert every UI test into a network test. Select journeys where browser evidence answers an important question that DOM assertions or direct API tests cannot. A small number of precise BiDi checks is more maintainable than a global recorder that every test implicitly depends on.

Interview Questions and Answers

Q: What does WebDriver BiDi add to classic Selenium WebDriver?

Classic WebDriver is primarily command and response. WebDriver BiDi adds a persistent bidirectional channel so the browser can publish events while the session runs and accept supported commands. Selenium still uses ordinary WebDriver for navigation and page interaction. BiDi complements it with browser-level observability and control.

Q: How is WebDriver BiDi different from CDP?

WebDriver BiDi is a standards-based automation protocol intended for interoperable browser implementations. CDP is Chromium's debugging protocol and follows Chromium-specific versions and capabilities. Prefer the public Selenium BiDi API for portable new features, while isolating any required CDP fallback.

Q: Why must a request interceptor continue unmatched traffic?

An interceptor pauses requests at a selected phase. If a callback neither continues nor fails a request, the browser waits and the page can appear frozen. Every branch must resolve the request exactly once, including exception and nonmatching branches.

Q: How do you prevent flaky event assertions?

Install the listener before the action, filter by stable business evidence, and transfer the matching event to the test thread. Use a bounded wait rather than sleep, and never assume event order among unrelated resources. Assert the visible product outcome alongside the browser evidence.

Q: How would you secure BiDi test artifacts?

Collect only necessary metadata and redact credentials, cookies, authorization headers, signed query strings, bodies, and personal data. Store evidence per test under controlled retention and access rules. Keep real credentials in a test-only secret store and never place them in source or callback logs.

Q: When should you prefer a direct API test?

Use a direct API test for broad schema, status, authorization, and business-rule coverage when browser behavior adds no value. Use BiDi when you must prove that a real UI action emitted a request, received a browser response, logged an exception, or handled a network condition. The two layers complement each other.

Q: How do you validate BiDi support on Grid?

Run a preflight that checks the WebSocket capability and exercises every event or command family required by the suite. Record the client, Grid, node image, browser, and driver versions. Treat missing required support as an environment failure instead of silently skipping the product assertion.

Best Practices

  • Request BiDi at session creation and verify the returned capability.
  • Prefer public high-level Selenium modules over internal protocol mappings.
  • Register listeners before the behavior and remove them immediately afterward.
  • Match exact test-owned hosts and paths before mutating traffic.
  • Resolve every intercepted request once, and only once.
  • Keep assertions off callback threads and use bounded synchronization.
  • Assert customer-visible behavior, not only protocol activity.
  • Separate observation helpers from traffic-changing helpers.
  • Scope collections and handlers to one driver and one test.
  • Redact sensitive values before logs or traffic become artifacts.
  • Pin Selenium and browser images, then run capability preflight after upgrades.
  • Use direct API tests when the browser boundary is not part of the risk.

The most common design mistake is a global observer that stores everything. It looks convenient, but it obscures ownership, increases memory, leaks secrets, and makes parallel failures difficult to attribute. Capture a narrow window around one action and retain only evidence needed by that scenario.

Conclusion

This selenium bidi automation complete guide 2026 gives you a durable pattern: negotiate BiDi at session creation, use Selenium's public typed APIs, subscribe before the action, synchronize on exact evidence, and clean up within one session. Network interception, browser authentication, JavaScript error capture, and controlled degradation then become focused additions to normal WebDriver tests rather than fragile global instrumentation.

Start with the session smoke test and one passive listener on your supported Grid. Add a product-visible assertion, secure the diagnostics, and run the preflight after every dependency or browser-image upgrade. Once that foundation is stable, follow the complete series to implement each advanced workflow without sacrificing portability, security, or test reliability.

Interview Questions and Answers

What does WebDriver BiDi solve in Selenium automation?

It adds an event-driven channel alongside classic WebDriver's command-response model. The browser can publish network, log, and script events while a test runs, and the client can issue supported control commands. This enables precise browser-boundary assertions without polling browser-specific log buffers.

How would you design a reliable Selenium BiDi listener?

I register it before the action, filter for stable business evidence, and keep the callback lightweight. I transfer data to the test thread using a future or test-scoped collection and wait with a timeout. I remove the listener in teardown and assert both the protocol evidence and the customer-visible result.

Why must every intercepted request be resolved?

An intercept pauses the request at a protocol phase. If a callback does not continue, fail, authenticate, or otherwise resolve it, the browser remains blocked and navigation may time out. Every callback path must make exactly one resolution decision.

When would you use BiDi instead of an API client?

I use BiDi when the risk is at the browser boundary, such as proving a UI action sent a request, observing browser authentication, or connecting a JavaScript failure to a broken screen. I use direct API tests for broad contracts, schemas, data combinations, and service authorization.

How do WebDriver BiDi and CDP differ?

BiDi is a browser automation standard intended for interoperable implementations. CDP is a Chromium debugging protocol with Chromium-specific capabilities and versions. I prefer Selenium's public BiDi surface for portable framework code and isolate any necessary CDP dependency.

How do you make BiDi automation secure?

I collect only the fields required by the assertion and redact credentials, cookies, authorization values, signed URLs, bodies, and personal data. Credentials come from a test-only secret store. Artifacts are scoped per test with controlled access and retention.

How would you qualify WebDriver BiDi on Selenium Grid?

I run a preflight on every versioned browser image that checks `webSocketUrl` and exercises each required event or command. I report the Selenium client, Grid, node image, browser, and driver versions. Unsupported required behavior fails the environment check rather than being silently skipped.

Frequently Asked Questions

What is Selenium WebDriver BiDi?

WebDriver BiDi is a bidirectional browser automation protocol that lets a browser send live events and receive supported commands during a Selenium session. It complements classic WebDriver commands for navigation, locators, and interaction.

How do I enable Selenium BiDi?

Enable BiDi on the browser options before creating the driver. In Java, use an option such as `new ChromeOptions().enableBiDi()`; in Python, set `options.enable_bidi = True`, then verify that returned capabilities contain a `webSocketUrl`.

Is Selenium BiDi the same as Chrome DevTools Protocol?

No. WebDriver BiDi is standards-based and designed for interoperable browser automation, while CDP is Chromium's debugging protocol. Selenium can expose both, but new portable features should prefer public BiDi APIs when they cover the requirement.

Can Selenium BiDi intercept network requests?

Yes, supported Selenium bindings can intercept requests at defined phases and continue, modify, or fail them. Every intercepted request must be resolved exactly once, and support should be verified for each browser and Grid image.

Can Selenium BiDi capture JavaScript errors?

Yes. Selenium's script features can register live handlers for console messages and uncaught JavaScript errors in supported bindings. Register before the action, store typed entries in test-scoped collections, and remove handlers during teardown.

Why does a page hang after I add a network handler?

A request interceptor pauses traffic. At least one callback branch probably failed to continue, fail, or otherwise resolve a request, so ensure matching, nonmatching, and exception paths all make exactly one resolution decision.

Does WebDriver BiDi work on Selenium Grid?

It can when the client, Grid, node, browser, and driver support the required feature and the session returns a BiDi WebSocket URL. Run a small capability preflight against every versioned node image before the full suite.

Related Guides