BiDirectional APIs in Selenium 4

Sauce AI for Test Authoring: Move from intent to execution in bit.|xBack to ResourcesBlogPosted October 20, 2021

BiDirectional APIs in Selenium 4

One of the nigh interesting and awaited characteristic included in Selenium 4 are the bidirectional APIs. They allow us to do things like: intercept network requests, mock backends, perform canonic hallmark, and view the console log. Everyone is relate to this as the Chrome DevTools Protocol APIs.

quote

The term “ DevTools ” is an ambiguous term, as many browser provide “ DevTools ”, which is a set of tools integrated with the browser. Those tools allow user to do thing such as research the website & # x27; s execution or debugging web applications.

The Chrome DevTools Protocol(CDP) is a peignoir provided by Google to interact with the integrated set of tools. Given its nature, it is not actually project for testing and it do not get a stable API, which means that its functionality can break between different browser versions.

The Selenium project is act with the browser vendors to create theWebDriver BiDirectional Protocol, signify to provide a stable, cross-browser API that uses the bidirectional functionality useful for both browser automation loosely and prove specifically. Since that protocol is not available yet, Selenium is providing access to the CDP for those browsers implementing it (Chrome, Edge, and Firefox).

The new bidirectional APIs will let you execute different activities, such as:

  • Check the browser console logs

  • Intercept network petition, utile to mock backend APIs

  • Perform Basic Authentication

  • Inspect and observe elements in the DOM

  • Execute bootstrap scripts to improve trial execution time

  • Mock geolocation

  • Throttle network performance to simulate real world conditions

Here are code example for some use cases:

Canonic assay-mark

If a website uses basic or digest authentication, it will prompt a dialog that can not be handled through Selenium. To go around that, it is possible to register an hallmark method to access the content require for the test.

@Test
public nihility authenticate () {
WebDriver webDriver = new ChromeDriver ();
((HasAuthentication) webDriver)
.register (() - & gt; new UsernameAndPassword (& quot; admin & quot;, & quot; admin & quot;));

webDriver.get (& quot; https: //the-internet.herokuapp.com & quot;);
webDriver.findElement (By.linkText (& quot; Digest Authentication & quot;)) .click ();

String body = webDriver.findElement (By.tagName (& quot; body & quot;)) .getText ();
assertThat (body, containsString (& quot; Congratulations! & quot;));

webDriver.quit ();
}

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

Observe change in the DOM

Mutation observation is the ability to capture DOM events you are interested in. For model, you might want to know if an element has changed its belongings value. Before, the approach to this was to question the ingredient continuously until the desired change occurred. Now you can observe the change in the DOM and assert over them when an incoming event notifies you about the expected change.

This example look for modification in a span element, then it is vary via JavaScript (for presentation intent), and finally we assert the expected province. On a real test, the simulated JavaScript alteration would be a existent event get the web application change.

@Test
public void mutationObservation () throw InterruptedException {
ChromeDriver driver = new ChromeDriver ();

AtomicReference & lt; DomMutationEvent & gt; seen = new AtomicReference & lt; & gt; ();
CountDownLatch latch = new CountDownLatch (1);
((HasLogEvents) driver) .onLogEvent (domMutation (mutation - & gt; {
seen.set (variation);
latch.countDown ();
}));

driver.get (& quot; https: //www.google.com & quot;);
WebElement couplet = driver.findElement (By.cssSelector (& quot; span & quot;));

((JavascriptExecutor) driver) .executeScript (& quot; arguments [0] .setAttribute (& # x27; cheese & # x27;,
& # x27; gouda & # x27;); & quot;, yoke);

assertThat (latch.await (10, SECONDS), is (true));
assertThat (seen.get () .getAttributeName (), is (& quot; cheese & quot;));
assertThat (seen.get () .getCurrentValue (), is (& quot; gouda & quot;));
driver.quit ();
}

Listen to events from console.log

Logs are vital in testing, and getting logs from the browser console has not always been the almost straightforward operation with Selenium. With the Bidirectional APIs, it is possible to get the console log to understand better how our application under test is perform. With that, we can now do assertions over the console log messages.

The following codification shows how a listener is registered, and it prints to the terminal console all the messages that get printed to the browser console. It will ladehttp: //the-internet.herokuapp.com/broken_images, which has a few humiliated resources and messages related to that are output to the console.

@Test
public void consoleLogTest () {
ChromeDriver driver = new ChromeDriver ();
DevTools devTools = driver.getDevTools ();
devTools.createSession ();
devTools.send (Log.enable ());
devTools.addListener (Log.entryAdded (),
logEntry - & gt; {
System.out.println (& quot; log: & quot; +logEntry.getText ());
System.out.println (& quot; level: & quot; +logEntry.getLevel ());
});
driver.get (& quot; http: //the-internet.herokuapp.com/broken_images & quot;);
// Check the terminal yield for the browser console messages.
driver.quit ();
}

Simulate a mobile twist

This feature is ideal for antiphonal site, as it enable us to quickly verify how the website is displayed on simulated wandering device dimensions. Doing this case of assay is really helpful for early testing. It is potential to achieve this by overthrow the device metrics (width, height, etc.), which sets the dimensions of the simulated device where the website will be furnish.

@Test
public void overrideDeviceMode () {
ChromeDriver driver = new ChromeDriver ();
DevTools devTools = driver.getDevTools ();
devTools.createSession ();
devTools.send (Log.enable ());
// iPhone 11 Pro dimension
devTools.send (Emulation.setDeviceMetricsOverride (375,
812,
50,
true,
Optional.empty (),
Optional.empty (),
Optional.empty (),
Optional.empty (),
Optional.empty (),
Optional.empty (),
Optional.empty (),
Optional.empty (),
Optional.empty ()));
driver.get (& quot; https: //opensource.saucelabs.com/ & quot;);
driver.quit ();
}

Emulate GeoLocation

When a site needs to conduct differently based on the user ’ s location, we need to find ways to set the environment to test the website ’ s behaviour. To do that, we can rely on the geolocation override provided by Selenium 4. In the following code, we set the coordinates of the Sauce Labs office in Berlin, and use the website https: //my-location.org/ to verify the emulated location.

@Test
public vacancy emulateGeoLocation () {
ChromeDriver driver = new ChromeDriver ();
DevTools devTools = driver.getDevTools ();
devTools.createSession ();
devTools.send (Emulation.setGeolocationOverride (Optional.of (52.5043),
Optional.of (13.4501),
Optional.of (1)));
driver.get (& quot; https: //my-location.org/ & quot;);
driver.quit ();
}

Cod Performance Metrics

Performance is key in today ’ s websites. Customers won ’ t tolerate sites that load slowly, use lots of resources, and in general, perform badly. In Selenium 4,Performance.enable and Performance.getMetrics ()enables us to find and validate all performance prosody for the website under tryout. The following code collects metric for the Sauce Labs Open Source Program Office website, and prints them. With that, you can examine the available metrics and assert on the relevant ones for your use suit.

@Test
public void performanceMetrics () {
ChromeDriver driver = new ChromeDriver ();
DevTools devTools = driver.getDevTools ();
devTools.createSession ();
devTools.send (Performance.enable (Optional.empty ()));
List & lt; Metric & gt; metricList = devTools.send (Performance.getMetrics ());
driver.get (& quot; https: //opensource.saucelabs.com/ & quot;);
driver.quit ();
for (Metric m: metricList) {
System.out.println (m.getName () + & quot; = & quot; + m.getValue ());
}
}

Intercepting Network Traffic

Manipulating network traffic is exceedingly useful for testing web applications because it gives us dateless possibilities to configure the surround where the web application will be escape. Blocking network traffic, mocking net connections, simulating the network speed, adding headers, etc. The undermentioned code shows how to add a header to the HTTP asking, which is helpful when our application under tryout exhibit filters requests or exposes specific features depending on the received cope.

@Test
public void addExtraHeaders () {
ChromeDriver driver = new ChromeDriver ();
DevTools devTools = driver.getDevTools ();
devTools.createSession ();
driver.get (& quot; https: //manytools.org/http-html-text/http-request-headers/ & quot;);

devTools.send (Network.enable (Optional.empty (), Optional.empty (), Optional.empty ()));

Headers heading = new Headers (Collections.singletonMap (& quot; testing & quot;, & quot; selenium & quot;));
devTools.send (Network.setExtraHTTPHeaders (headers));

driver.get (& quot; https: //manytools.org/http-html-text/http-request-headers/ & quot;);
driver.quit ();
}

Summary

Testing with Selenium but got more powerful thanks to the eternal possibilities offered by the bidirectional APIs. It is important to observe that this is only supported on Chrome, Edge, and Firefox. However, when WebDriver BiDi is ready, other browsers like Safari will be supported too.

While the examples shown above use thedevTools.send (Command & lt; X & gt; dictation)to interact with CDP, the driver also discover theexecuteCdpCommand. The executeCdpCommandallows you to mail raw commands to CDP, and search even farther functionality. Nevertheless, usingexecuteCdpCommandextensively will tie your examination to a specific browser version, making them harder to maintain and prone to errors yield the unstable nature of the CDP APIs.

While it is invite to use the CDP methods directly, whenever potential, the Selenium squad recommends using the provided group of helper family in Selenium 4. With that, you will future proofread your examination and they will be ready when WebDriver BiDi is available through Selenium. More info about the Birectional APIs can be establish in the officialdocumentation.

At launching, Sauce Labs will support all features except for the Bidirectional APIs. While we are working hard to add full support we do furnish similar functionality through our feature.

Titus Fortner

Sr. Developer Experience Engineer, Sauce Labs

Diego Molina

Staff Software Engineer at Sauce Labs

Published:
Oct 20, 2021
Share this post
Copy Share Link
LinkedIn
© 2026 Sauce Labs Inc., all rights reserved. SAUCE and SAUCE LABS are file trademarks owned by Sauce Labs Inc. in the United States, EU, and may be registered in early jurisdictions.
robot
quote

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free