BiDi instead of CDP, Actions, files, iframes and windows
Classic Selenium works as request and response, so console or network events come from WebDriver BiDi, a two-way W3C standard, rather than from CDP. CDP is a Chromium protocol that depends on the browser version, so new code uses BiDi. Actions does nothing without perform(). A file is uploaded through sendKeys with an absolute path, and iframes and windows are switched explicitly.
Selenium · BiDi and contexts
A user sees a console error while the test is green. How can Selenium see it?
A page shows the user a broken widget, an unhandled JS error turns red in the console, and a test that checked only visible elements is green. The classic Selenium model is built as request-response (the lesson “How Selenium WebDriver works: client, protocol, driver, browser”): the test asks, the browser answers, and it reports nothing by itself. To see console or network events, a two-way channel is needed. The lesson covers BiDi and CDP, and four places where Selenium tests most often get confused with context: Actions, files, iframes and windows.
How it works and why. Selenium 4 gives access to the Chrome DevTools Protocol (CDP): network interception, emulation, console events. CDP is a Chromium protocol (Chrome, Edge) that depends strongly on the browser version: Selenium ships bindings for specific versions, and after a browser update the code may not find a matching implementation. The Selenium documentation calls CDP support temporary until WebDriver BiDi is implemented. BiDi is a W3C standard: two-way communication over WebSocket, a cross-browser replacement for CDP. It is turned on by the webSocketUrl capability, and browser events reach the test through handlers.
// CDP: Chromium only, tied to the browser version
DevTools devTools = ((HasDevTools) driver).getDevTools();
devTools.createSession();
// after a Chrome update the code may not find matching bindings
The classic model, CDP and BiDi
Chromium, temporary
Works only in Chrome and Edge, depends on the browser version. For new code only when you need something BiDi does not have yet.
W3C standard
A two-way channel, cross-browser. The default for console events, JS errors and the network.
Example: a green test with a JS error. The test listens for unhandled JS errors during the scenario and checks that there were none:
ChromeOptions options = new ChromeOptions();
options.setCapability("webSocketUrl", true); // turns BiDi on
WebDriver driver = new ChromeDriver(options);
List<String> errors = new CopyOnWriteArrayList<>();
String id = ((RemoteWebDriver) driver).script()
.addJavaScriptErrorHandler(e -> errors.add(e.getText()));
driver.get("https://example.com/checkout");
// ... test actions ...
assertTrue(errors.isEmpty(), "JS errors on the page: " + errors);
((RemoteWebDriver) driver).script().removeJavaScriptErrorHandler(id);
Now a hidden error is visible in the report even if there are no visible symptoms. Handlers are removed after use, and console messages are caught in the same way by addConsoleMessageHandler. For new code BiDi is chosen by default, and CDP is taken only when you need a capability BiDi does not have yet. Specific modules and support in different browsers change from version to version, so check the current Selenium documentation before use. The old driver.manage().logs() is designed for Chromium, and relying on it in new tests is not advisable.
Actions. The Actions API builds complex gestures: hover, drag and drop, double and context click, key combinations, scrolling. Nothing happens without perform(): it is only a description of a sequence.
Actions actions = new Actions(driver);
actions.moveToElement(menu).pause(Duration.ofMillis(200)).click(sub).perform();
actions.scrollToElement(footer).perform();
actions.dragAndDrop(card, column).perform();
Files. Uploading a file to a site is done through sendKeys with an absolute path into input type="file", without clicking the button: Selenium does not see the OS dialog. On Grid add setFileDetector(new LocalFileDetector()) (the lesson “Selenium Grid 4 and Docker: how it is built and how to run it”). Downloading a file from a site to disk is set up in the browser options (the folder and no dialog), and then the file's appearance in the folder is awaited.
// upload: sendKeys with an absolute path into input[type=file]
driver.findElement(By.cssSelector("input[type=file]"))
.sendKeys(Path.of("data/report.csv").toAbsolutePath().toString());
// download: the folder and no dialog set in the browser options
Path dir = Files.createTempDirectory("dl");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", Map.of(
"download.default_directory", dir.toString(),
"download.prompt_for_download", false));
// ... click "Download", then wait for the file
new WebDriverWait(driver, Duration.ofSeconds(15)).until(
d -> Files.exists(dir.resolve("report.csv")));
iframe. An element inside a frame is invisible to search until you switch: driver.switchTo().frame(...), and back with parentFrame() or defaultContent(). frameToBeAvailableAndSwitchToIt combines waiting and switching. A typical sign of a forgotten switch: NoSuchElementException on an element that seems to be in place in DevTools (the lesson “StaleElementReferenceException and other common interaction exceptions”).
// an element in an iframe is invisible to search until you switch
new WebDriverWait(driver, Duration.ofSeconds(10)).until(
ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("payment")));
driver.findElement(By.id("card-number")).sendKeys("4111111111111111");
driver.switchTo().defaultContent(); // back to the main document
Windows and tabs. You remember the current handle, wait for the new window (numberOfWindowsToBe) and switch to another handle. driver.switchTo().newWindow(WindowType.TAB) opens a new tab. After close() you must explicitly return to the right window, otherwise the next command goes to the already closed one and ends with NoSuchWindowException.
String original = driver.getWindowHandle();
driver.findElement(By.linkText("Terms")).click(); // opens a tab
new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(original)) {
driver.switchTo().window(handle);
}
}
assertTrue(driver.getTitle().contains("Terms"));
driver.close(); // closed the tab
driver.switchTo().window(original); // and returned explicitly
Limits and alternatives. BiDi does not remove the need for waits and does not make tests faster: it only opens events that were not visible before. Some modules, such as network interception, depend on the Selenium version and the browser. For checking network calls it is sometimes more reliable to test the API itself separately than to eavesdrop on the browser. The question of OS dialogs stays open: Selenium does not see them, so they are bypassed (a path in sendKeys, browser settings) or tested at another level.
Common mistakes.
- Using CDP in new code "because the old guide did": after a Chrome update tests break with no change in the project.
- Forgetting
perform()in an Actions chain: the code runs without errors and does nothing. - Clicking the "Choose file" button for an upload: an OS dialog opens that Selenium does not see, and the test hangs.
- Looking for an element inside an iframe without
switchTo().frame:NoSuchElementExceptionon an element that is "on screen". - Not returning to a window after
close(): the next step throwsNoSuchWindowException.
Check yourself
A test presses the "Choose file" button and then hangs. What happens and how should a file be uploaded properly?
Answer
The click opens an OS dialog that Selenium does not see, so the test waits. Correct: sendKeys with an absolute path into input type="file" without clicking the button; on Grid also setFileDetector(new LocalFileDetector()) so the file is transferred to the node.
After driver.close() of the terms tab the test throws NoSuchWindowException on the next step. Why, and what should be added?
Answer
close() closes the current window, but the driver stays bound to it, so the next commands go to the closed window. You must switch explicitly to the saved handle of the main window: driver.switchTo().window(original).
Actions and do not forget perform(). I find elements in an iframe after switchTo().frame and do a file upload through sendKeys with an absolute path. Middle/Senior: I know the classic Selenium model gives no events from the browser. For the console and JS errors I use WebDriver BiDi (webSocketUrl), since it is a W3C standard and cross-browser, and CDP only where BiDi is not enough yet, remembering that CDP depends on the Chromium version. I switch windows and frames explicitly and wait for them to appear rather than sleep.