Learn about event-driven testing with Selenium BiDi
WebDriver BiDi is a new protocol, standardized by the W3C. Even though it's still in draft mode, support for this new protocol has already been implemented in Chrome, Microsoft Edge and Firefox.
The advantage of using this new protocol (based on WebSocket) over the older one (HTTP) is that it allows for bidirectional communication between the test script and the Selenium endpoint. This means your test scripts can now listen for certain events, generated by the (remote) browser under test.
Previously, a similar protocol was developed called CDP (Chrome DevTools Protocol), which only supported Chromium-based browsers (Chrome and Microsoft Edge). The new BiDi protocol is the new official standards-based alternative to CDP. It is supported on multiple browsers and is used for automation with Puppeteer.
Key Features of WebDriver BiDi Protocol
There are various advantages to using Selenium BiDi:
-
Event-Driven Automation:
Allows your test scripts to listen to browser based events as they happen. This eliminates the need for polling and improves the overall test performance.
-
Standardization:
The WebDriver BiDi protocol is a W3C standard, which means you'll get the same consistency and interoperability between browser flavors. You can run the same BiDi test script on multiple different browsers on the TestingBot browser grid.
-
Future Proof:
The most popular browser vendors are committed to supporting the WebDriver BiDi Protocol. By adopting BiDi early on, you are future-proofing your test cases and ensuring compatibility with upcoming browser advancements.
-
Cross-Browser Compatibility
Unlike CDP, which is restricted to a limited set of browsers, the WebDriver BiDi Protocol is designed to operate across various browsers, including Firefox.
Configuring Selenium BiDi
To get started with Selenium BiDi on TestingBot, you'll need to add several capabilities to your existing Selenium tests:
Selenium Version 4 is required
Selenium BiDi is only available on Selenium 4. We suggest using Selenium version 4.23.0 or higher.
Please specify the selenium-version capability in a tb:options capability.
caps = {
platformName: "Windows 10",
browserName: "chrome",
browserVersion: "latest",
"tb:options" => {
"selenium-version" => '4.33.0'
}
}
options.web_socket_url = true
ChromeOptions options = new ChromeOptions();
options.setPlatformName("Windows 11");
options.setBrowserVersion("latest");
MutableCapabilities tbOptions = new MutableCapabilities();
tbOptions.setCapability("key", "api_key");
tbOptions.setCapability("secret", "api_secret");
tbOptions.setCapability("selenium-version", "4.33.0");
options.setCapability("tb:options", tbOptions);
$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability('platformName', 'Windows 11');
$capabilities->setCapability('browserVersion', 'latest');
$capabilities->setCapability('tb:options', array(
'selenium-version' => '4.33.0'
));
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.browser_version = 'latest'
options.platform_name = 'Windows 10'
options.set_capability('tb:options', {
'name': 'W3C Sample',
'selenium-version': '4.33.0'
})
driver = webdriver.Remote(
command_executor='https://key:secret@hub.testingbot.com/wd/hub',
options=options)
driver = await new webdriver.Builder().withCapabilities({
"browserName": 'chrome',
"platformName": 'Windows 10',
"goog:chromeOptions" : { "w3c" : true },
"tb:options": {
"key": "api_key",
"secret": "api_secret",
"selenium-version": '4.33.0'
}
}).usingServer("https://hub.testingbot.com/wd/hub").build();
var chromeOptions = new ChromeOptions()
{
BrowserVersion = "latest",
PlatformName = "Windows 10"
};
var tbOptions = new Dictionary<string, object>
{
["key"] = "api_key",
["secret"] = "api_secret",
["selenium-version"] = "4.33.0"
};
chromeOptions.AddAdditionalOption("tb:options", tbOptions);
driver = new RemoteWebDriver(new Uri("https://hub.testingbot.com/wd/hub"),
chromeOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
webSocketUrl capability
Please specify the webSocketUrl capability to indicate to Selenium that you want to use the BiDi protocol.
caps = {
platformName: "Windows 10",
browserName: "chrome",
browserVersion: "latest",
"selenium-version": "4.33.0",
webSocketUrl: true
}
options.web_socket_url = true
ChromeOptions options = new ChromeOptions();
options.setPlatformName("Windows 11");
options.setBrowserVersion("latest");
options.setCapability("webSocketUrl", true);
MutableCapabilities tbOptions = new MutableCapabilities();
tbOptions.setCapability("key", "api_key");
tbOptions.setCapability("secret", "api_secret");
tbOptions.setCapability("selenium-version", "4.33.0");
options.setCapability("tb:options", tbOptions);
$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability('platformName', 'Windows 11');
$capabilities->setCapability('browserVersion', 'latest');
$capabilities->setCapability('webSocketUrl', true);
$capabilities->setCapability('tb:options', array(
'selenium-version' => '4.33.0'
));
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.browser_version = 'latest'
options.platform_name = 'Windows 10'
options.enable_bidi = True
options.set_capability('tb:options', {
'name': 'W3C Sample',
'selenium-version': '4.33.0'
})
driver = webdriver.Remote(
command_executor='https://key:secret@hub.testingbot.com/wd/hub',
options=options)
driver = await new webdriver.Builder().withCapabilities({
"browserName": 'chrome',
"platformName": 'Windows 10',
"webSocketUrl": true,
"tb:options": {
"key": "api_key",
"secret": "api_secret",
"selenium-version": '4.33.0'
}
}).usingServer("https://hub.testingbot.com/wd/hub").build();
var chromeOptions = new ChromeOptions()
{
BrowserVersion = "latest",
PlatformName = "Windows 10",
UseWebSocketUrl = true
};
var tbOptions = new Dictionary<string, object>
{
["key"] = "api_key",
["secret"] = "api_secret",
["selenium-version"] = "4.33.0"
};
chromeOptions.AddAdditionalOption("tb:options", tbOptions);
driver = new RemoteWebDriver(new Uri("https://hub.testingbot.com/wd/hub"),
chromeOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
Session limits
A BiDi session is a regular Selenium session with an extra WebSocket channel, so the usual Selenium limits apply:
| Limit | Default | Maximum |
|---|---|---|
Idle timeout (idletimeout) |
The Selenium grid default | 7200 seconds (2 hours) |
Maximum duration (maxduration) |
1800 seconds (30 minutes) | 7200 seconds (2 hours) |
Only WebDriver commands sent over HTTP reset the idle timer. Messages on the BiDi or CDP WebSocket do not, so a test that only waits for BiDi events (for example console logs or network responses) without sending a WebDriver command will be ended by the idle timeout. Raise idletimeout for such tests, or send a WebDriver command now and then.
Dependencies for the examples below
The Java examples report the test result to TestingBot with the TestingBot REST client. Add it next to selenium-java:
<dependency>
<groupId>com.testingbot</groupId>
<artifactId>testingbotrest</artifactId>
<version>1.0.10</version>
</dependency>
The C# examples are NUnit tests. Create a project with dotnet new nunit and add Selenium with dotnet add package Selenium.WebDriver --version 4.52.0. The BiDi API in .NET is still changing between releases, and these examples are written for that version.
Listen to console.log events
This example shows how to use Selenium BiDi to collect events generated by the browser in realtime, such as the console.log events. It will navigate to a website and click a button that generates console.log entries.
require "rubygems"
require "selenium-webdriver"
tb_options = {
"name" => "My Bidi Test",
"browserName" => "chrome",
"platform" => "WIN10",
"version" => "latest",
"selenium-version" => "4.33.0"
}
options = Selenium::WebDriver::Chrome::Options.new
options.add_option('tb:options', tb_options)
options.web_socket_url = true
driver = Selenium::WebDriver.for(
:remote,
:url => "https://key:secret@hub.testingbot.com/wd/hub",
:capabilities => options)
driver.navigate.to "https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html"
driver.script.add_console_message_handler { |log| puts log }
wait = Selenium::WebDriver::Wait.new(timeout: 10)
consoleLog = wait.until {
element = driver.find_element(id: 'consoleLog')
element if element.displayed?
}
consoleLog.click
driver.quit
<dependency>
<groupId>com.testingbot</groupId>
<artifactId>testingbotrest</artifactId>
<version>1.1.0</version>
</dependency>
import com.testingbot.testingbotrest.TestingbotREST;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.module.LogInspector;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebDriver;
public class ListenToConsoleLogs {
public static final String KEY = "KEY";
public static final String SECRET = "SECRET";
public static final String REMOTE_URL = "https://" + KEY + ":" + SECRET + "@hub.testingbot.com/wd/hub";
public static void main(String[] args) throws MalformedURLException {
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("webSocketUrl", true);
HashMap<String, Object> testingbotOptions = new HashMap<>();
testingbotOptions.put("selenium-version", "4.33.0");
capabilities.setCapability("tb:options", testingbotOptions);
WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);
try {
Augmenter augmenter = new Augmenter();
driver = augmenter.augment(driver);
try (LogInspector logInspector = new LogInspector(driver)) {
CountDownLatch latch = new CountDownLatch(1);
logInspector.onConsoleEntry(consoleLogEntry -> {
System.out.println("text: " + consoleLogEntry.getText());
System.out.println("level: " + consoleLogEntry.getLevel());
latch.countDown();
});
String page = "https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html";
driver.get(page);
driver.findElement(By.id("consoleLog")).click();
// Console events arrive asynchronously: wait up to 5 seconds for the first one
if (latch.await(5, TimeUnit.SECONDS)) {
markTestStatus(true, "Console logs streaming", driver);
} else {
markTestStatus(false, "Console logs did not stream", driver);
}
driver.quit();
}
} catch (Exception e) {
markTestStatus(false, "Exception!", driver);
e.printStackTrace();
driver.quit();
}
}
public static void markTestStatus(Boolean status, String reason, WebDriver driver) {
TestingbotREST r = new TestingbotREST(System.getenv("TESTINGBOT_KEY"), System.getenv("TESTINGBOT_SECRET"));
Map<String, Object> data = new HashMap<String, Object>();
data.put("success", status ? "1" : "0");
data.put("name", reason);
r.updateTest(((RemoteWebDriver) driver).getSessionId().toString(), data);
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
def console_log():
tb_options = {
'name': 'TestingBot Sample Test',
'selenium-version': '4.33.0'
}
options = webdriver.ChromeOptions()
options.browser_version = 'latest'
options.platform_name = 'Windows 11'
options.set_capability('webSocketUrl', True)
options.set_capability('tb:options', tb_options)
driver = webdriver.Remote(
command_executor='https://key:secret@hub.testingbot.com/wd/hub', options=options)
driver.get('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
log_entries = []
driver.script.add_console_message_handler(log_entries.append)
driver.find_element(By.ID, "consoleLog").click()
WebDriverWait(driver, 5).until(lambda _: log_entries)
print(log_entries[0].text)
driver.quit()
const webdriver = require('selenium-webdriver');
const USERNAME = process.env.TESTINGBOT_KEY;
const ACCESS_KEY = process.env.TESTINGBOT_SECRET;
(async () => {
const driver = await (new webdriver.Builder()
.withCapabilities({
browserName: 'chrome',
platformName: 'WIN10',
webSocketUrl: true,
'tb:options': {
'selenium-version': '4.33.0'
},
})
.usingServer(
`https://${USERNAME}:${ACCESS_KEY}@hub.testingbot.com/wd/hub`
)
.build());
// Add a listener for log events.
await driver.script().addConsoleMessageHandler((logEntry) => {
console.log(logEntry.text);
});
await driver.get(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html'
);
// Trigger a console log on the demo page.
await driver.findElement({ id: 'consoleLog' }).click();
await driver.quit();
})();
using System.Collections.Concurrent;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.Log;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Safari;
namespace NUnit_TestingBot_Sample
{
[TestFixture("chrome", "latest", "Windows 10")]
[Category("BiDi")]
public class BidiTest
{
private IWebDriver _driver;
private CancellationToken _token = CancellationToken.None;
private readonly string _browser;
private readonly string _version;
private readonly string _os;
public BidiTest(string browser, string version, string os)
{
_browser = browser;
_version = version;
_os = os;
}
[SetUp]
public void SetUp()
{
var browserOptions = new ChromeOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
};
var testingBotOptions = CreateTestingBotOptions();
browserOptions.AddAdditionalOption("tb:options", testingBotOptions);
_driver = new RemoteWebDriver(
new Uri("https://hub.testingbot.com/wd/hub"),
browserOptions.ToCapabilities(),
TimeSpan.FromSeconds(60)
);
}
[Test]
public async Task CaptureConsoleLogs()
{
await using var bidi = await _driver.AsBiDiAsync();
var entries = new ConcurrentQueue<string>();
await bidi.Log.EntryAdded.SubscribeAsync(e => entries.Enqueue($"{e.Level}: {e.Text}"));
_driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
_driver.FindElement(By.Id("consoleLog")).Click();
// BiDi events arrive asynchronously: wait up to 5 seconds for the first one
for (var i = 0; i < 50 && entries.IsEmpty; i++) await Task.Delay(100);
foreach (var entry in entries) Console.WriteLine(entry);
Assert.That(entries, Is.Not.Empty, "No console.log entry was received");
}
[TearDown]
public void TearDown()
{
if (_driver == null) return;
var testPassed = TestContext.CurrentContext.Result.Outcome.Status ==
NUnit.Framework.Interfaces.TestStatus.Passed;
try
{
((IJavaScriptExecutor)_driver).ExecuteScript($"tb:test-result={testPassed.ToString().ToLower()}");
}
catch (Exception ex)
{
TestContext.Out.WriteLine($"Failed to report test result: {ex.Message}");
}
finally
{
_driver.Quit();
_driver.Dispose();
}
}
private Dictionary<string, object> CreateTestingBotOptions()
{
var key = Environment.GetEnvironmentVariable("TESTINGBOT_KEY");
var secret = Environment.GetEnvironmentVariable("TESTINGBOT_SECRET");
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret))
{
throw new InvalidOperationException(
"TESTINGBOT_KEY and TESTINGBOT_SECRET environment variables must be set");
}
return new Dictionary<string, object>
{
["key"] = key,
["secret"] = secret,
["name"] = TestContext.CurrentContext.Test.Name,
["selenium-version"] = "4.33.0"
};
}
}
}
Listen to JavaScript Exceptions
You can use this API to listen for JavaScript exceptions and register callbacks in your test, to process the exception details. These exception details can help in further inspecting the cause of a failing test.
The example test script below will navigate to a web page and click a button that will throw an exception. Selenium BiDi will forward this to your test script.
require "rubygems"
require "selenium-webdriver"
tb_options = {
"name" => "My Bidi Test",
"browserName" => "chrome",
"platform" => "WIN10",
"version" => "latest",
"selenium-version" => "4.33.0"
}
options = Selenium::WebDriver::Chrome::Options.new
options.add_option('tb:options', tb_options)
options.web_socket_url = true
driver = Selenium::WebDriver.for(
:remote,
:url => "https://key:secret@hub.testingbot.com/wd/hub",
:capabilities => options)
driver.navigate.to "https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html"
driver.script.add_javascript_error_handler { |error| puts error }
wait = Selenium::WebDriver::Wait.new(timeout: 10)
jsException = wait.until {
element = driver.find_element(id: 'jsException')
element if element.displayed?
}
jsException.click
driver.quit
<dependency>
<groupId>com.testingbot</groupId>
<artifactId>testingbotrest</artifactId>
<version>1.1.0</version>
</dependency>
import com.testingbot.testingbotrest.TestingbotREST;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.module.LogInspector;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebDriver;
public class ListenToJavaScriptExceptions {
public static final String KEY = "KEY";
public static final String SECRET = "SECRET";
public static final String REMOTE_URL = "https://" + KEY + ":" + SECRET + "@hub.testingbot.com/wd/hub";
static Boolean success = false;
public static void main(String[] args) throws MalformedURLException {
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("webSocketUrl", true);
HashMap<String, Object> testingbotOptions = new HashMap<>();
testingbotOptions.put("selenium-version", "4.33.0");
capabilities.setCapability("tb:options", testingbotOptions);
WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);
try {
Augmenter augmenter = new Augmenter();
driver = augmenter.augment(driver);
try (LogInspector logInspector = new LogInspector(driver)) {
logInspector.onJavaScriptException(logEntry -> {
System.out.println("text: " + logEntry.getText());
System.out.println("level: " + logEntry.getLevel());
success = true;
});
String page = "https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html";
driver.get(page);
driver.findElement(By.id("jsException")).click();
Thread.sleep(1500);
if (success) {
markTestStatus(true, "Caught a JS exception successfully", driver);
} else {
markTestStatus(false, "Failed to catch the JS exception", driver);
}
driver.quit();
}
} catch (Exception e) {
markTestStatus(false, "Exception!", driver);
e.printStackTrace();
driver.quit();
}
}
public static void markTestStatus(Boolean status, String reason, WebDriver driver) {
TestingbotREST r = new TestingbotREST(System.getenv("TESTINGBOT_KEY"), System.getenv("TESTINGBOT_SECRET"));
Map<String, Object> data = new HashMap<String, Object>();
data.put("success", status ? "1" : "0");
data.put("name", reason);
r.updateTest(((RemoteWebDriver) driver).getSessionId().toString(), data);
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
def js_exception():
tb_options = {
'name': 'TestingBot Sample Test',
'selenium-version': '4.33.0'
}
options = webdriver.ChromeOptions()
options.browser_version = 'latest'
options.platform_name = 'Windows 11'
options.set_capability('webSocketUrl', True)
options.set_capability('tb:options', tb_options)
driver = webdriver.Remote(
command_executor='https://key:secret@hub.testingbot.com/wd/hub', options=options)
driver.get('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
log_entries = []
driver.script.add_javascript_error_handler(log_entries.append)
driver.find_element(By.ID, "jsException").click()
WebDriverWait(driver, 5).until(lambda _: log_entries)
print(log_entries[0].text)
driver.quit()
const webdriver = require('selenium-webdriver');
const USERNAME = process.env.TESTINGBOT_KEY;
const ACCESS_KEY = process.env.TESTINGBOT_SECRET;
(async () => {
const driver = await (new webdriver.Builder()
.withCapabilities({
browserName: 'chrome',
platformName: 'WIN10',
webSocketUrl: true,
'tb:options': {
'selenium-version': '4.33.0'
},
})
.usingServer(
`https://${USERNAME}:${ACCESS_KEY}@hub.testingbot.com/wd/hub`
)
.build());
// Add a listener for error events.
await driver.script().addJavaScriptErrorHandler((logEntry) => {
console.error(logEntry.text);
});
await driver.get(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html'
);
// Trigger a console log on the demo page.
await driver.findElement({ id: 'jsException' }).click();
await driver.quit();
})();
using System.Collections.Concurrent;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.Log;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Safari;
namespace NUnit_TestingBot_Sample
{
[TestFixture("chrome", "latest", "Windows 10")]
[Category("BiDi")]
public class BidiTest
{
private IWebDriver _driver;
private CancellationToken _token = CancellationToken.None;
private readonly string _browser;
private readonly string _version;
private readonly string _os;
public BidiTest(string browser, string version, string os)
{
_browser = browser;
_version = version;
_os = os;
}
[SetUp]
public void SetUp()
{
var browserOptions = new ChromeOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
};
var testingBotOptions = CreateTestingBotOptions();
browserOptions.AddAdditionalOption("tb:options", testingBotOptions);
_driver = new RemoteWebDriver(
new Uri("https://hub.testingbot.com/wd/hub"),
browserOptions.ToCapabilities(),
TimeSpan.FromSeconds(60)
);
}
[Test]
public async Task CaptureJavaScriptExceptions()
{
await using var bidi = await _driver.AsBiDiAsync();
var errors = new ConcurrentQueue<string>();
await bidi.Log.EntryAdded.SubscribeAsync(e =>
{
// JavaScript errors arrive as JavascriptEntryAddedEventArgs, console.log calls as ConsoleEntryAddedEventArgs
if (e is JavascriptEntryAddedEventArgs) errors.Enqueue(e.Text);
});
_driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
_driver.FindElement(By.Id("jsException")).Click();
// BiDi events arrive asynchronously: wait up to 5 seconds for the first one
for (var i = 0; i < 50 && errors.IsEmpty; i++) await Task.Delay(100);
foreach (var error in errors) Console.WriteLine($"JavaScript error: {error}");
Assert.That(errors, Is.Not.Empty, "No JavaScript exception was received");
}
[TearDown]
public void TearDown()
{
if (_driver == null) return;
var testPassed = TestContext.CurrentContext.Result.Outcome.Status ==
NUnit.Framework.Interfaces.TestStatus.Passed;
try
{
((IJavaScriptExecutor)_driver).ExecuteScript($"tb:test-result={testPassed.ToString().ToLower()}");
}
catch (Exception ex)
{
TestContext.Out.WriteLine($"Failed to report test result: {ex.Message}");
}
finally
{
_driver.Quit();
_driver.Dispose();
}
}
private Dictionary<string, object> CreateTestingBotOptions()
{
var key = Environment.GetEnvironmentVariable("TESTINGBOT_KEY");
var secret = Environment.GetEnvironmentVariable("TESTINGBOT_SECRET");
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret))
{
throw new InvalidOperationException(
"TESTINGBOT_KEY and TESTINGBOT_SECRET environment variables must be set");
}
return new Dictionary<string, object>
{
["key"] = key,
["secret"] = secret,
["name"] = TestContext.CurrentContext.Test.Name,
["selenium-version"] = "4.33.0"
};
}
}
}
Intercept Network Request
You can intercept and modify network requests with Selenium BiDi. Monitor network traffic, or mock outgoing requests. Modify request details such as headers, body, cookies, method and URL.
<dependency>
<groupId>com.testingbot</groupId>
<artifactId>testingbotrest</artifactId>
<version>1.1.0</version>
</dependency>
import com.testingbot.testingbotrest.TestingbotREST;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.module.Network;
import org.openqa.selenium.bidi.network.AddInterceptParameters;
import org.openqa.selenium.bidi.network.ContinueRequestParameters;
import org.openqa.selenium.bidi.network.InterceptPhase;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebDriver;
public class InterceptNetworkRequest {
public static final String KEY = "KEY";
public static final String SECRET = "SECRET";
public static final String REMOTE_URL = "https://" + KEY + ":" + SECRET + "@hub.testingbot.com/wd/hub";
public static void main(String[] args) throws MalformedURLException {
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("webSocketUrl", true);
HashMap<String, Object> testingbotOptions = new HashMap<>();
testingbotOptions.put("selenium-version", "4.33.0");
capabilities.setCapability("tb:options", testingbotOptions);
WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);
try {
Augmenter augmenter = new Augmenter();
driver = augmenter.augment(driver);
try (Network network = new Network(driver)) {
network.addIntercept(new AddInterceptParameters(InterceptPhase.BEFORE_REQUEST_SENT));
CountDownLatch latch = new CountDownLatch(1);
network.onBeforeRequestSent(
beforeRequestSent -> {
network.continueRequest(
new ContinueRequestParameters(beforeRequestSent.getRequest().getRequestId()));
latch.countDown();
});
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
boolean countdown = latch.await(5, TimeUnit.SECONDS);
if (countdown) {
markTestStatus(true, "Network request intercepted successfully", driver);
} else {
markTestStatus(false, "Network request failed to intercept", driver);
}
driver.quit();
}
} catch (Exception e) {
markTestStatus(false, "Exception!", driver);
e.printStackTrace();
driver.quit();
}
}
public static void markTestStatus(Boolean status, String reason, WebDriver driver) {
TestingbotREST r = new TestingbotREST(System.getenv("TESTINGBOT_KEY"), System.getenv("TESTINGBOT_SECRET"));
Map<String, Object> data = new HashMap<String, Object>();
data.put("success", status ? "1" : "0");
data.put("name", reason);
r.updateTest(((RemoteWebDriver) driver).getSessionId().toString(), data);
}
}
using System.Collections.Concurrent;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.Network;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Safari;
namespace NUnit_TestingBot_Sample
{
[TestFixture("chrome", "latest", "Windows 10")]
[Category("BiDi")]
public class BidiTest
{
private IWebDriver _driver;
private CancellationToken _token = CancellationToken.None;
private readonly string _browser;
private readonly string _version;
private readonly string _os;
public BidiTest(string browser, string version, string os)
{
_browser = browser;
_version = version;
_os = os;
}
[SetUp]
public void SetUp()
{
var browserOptions = new ChromeOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
};
var testingBotOptions = CreateTestingBotOptions();
browserOptions.AddAdditionalOption("tb:options", testingBotOptions);
_driver = new RemoteWebDriver(
new Uri("https://hub.testingbot.com/wd/hub"),
browserOptions.ToCapabilities(),
TimeSpan.FromSeconds(60)
);
}
[Test]
public async Task InterceptNetworkRequests()
{
await using var bidi = await _driver.AsBiDiAsync();
var intercepted = new ConcurrentQueue<string>();
// Pause every request before it is sent, so the handler can decide what happens to it
await bidi.Network.AddInterceptAsync([InterceptPhase.BeforeRequestSent]);
await bidi.Network.BeforeRequestSent.SubscribeAsync(async req =>
{
if (!req.IsBlocked) return;
intercepted.Enqueue(req.Request.Url);
if (req.Request.Url.EndsWith(".png"))
{
// Answer image requests with a 1x1 transparent PNG instead of the real image
await bidi.Network.ProvideResponseAsync(req.Request.Request, new ProvideResponseOptions
{
StatusCode = 200,
Body = Convert.FromBase64String(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=")
});
}
else
{
await bidi.Network.ContinueRequestAsync(req.Request.Request);
}
});
_driver.Navigate().GoToUrl("https://www.selenium.dev");
// BiDi events arrive asynchronously: wait up to 5 seconds for the first one
for (var i = 0; i < 50 && intercepted.IsEmpty; i++) await Task.Delay(100);
Assert.That(intercepted, Is.Not.Empty, "No request was intercepted");
}
[TearDown]
public void TearDown()
{
if (_driver == null) return;
var testPassed = TestContext.CurrentContext.Result.Outcome.Status ==
NUnit.Framework.Interfaces.TestStatus.Passed;
try
{
((IJavaScriptExecutor)_driver).ExecuteScript($"tb:test-result={testPassed.ToString().ToLower()}");
}
catch (Exception ex)
{
TestContext.Out.WriteLine($"Failed to report test result: {ex.Message}");
}
finally
{
_driver.Quit();
_driver.Dispose();
}
}
private Dictionary<string, object> CreateTestingBotOptions()
{
var key = Environment.GetEnvironmentVariable("TESTINGBOT_KEY");
var secret = Environment.GetEnvironmentVariable("TESTINGBOT_SECRET");
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret))
{
throw new InvalidOperationException(
"TESTINGBOT_KEY and TESTINGBOT_SECRET environment variables must be set");
}
return new Dictionary<string, object>
{
["key"] = key,
["secret"] = secret,
["name"] = TestContext.CurrentContext.Test.Name,
["selenium-version"] = "4.33.0"
};
}
}
}
Intercept Network Response
You can intercept and modify incoming network responses with Selenium BiDi. Monitor incoming network traffic, or mock incoming requests. Modify request details such as headers, body, cookies, method, URL and status code.
<dependency>
<groupId>com.testingbot</groupId>
<artifactId>testingbotrest</artifactId>
<version>1.1.0</version>
</dependency>
import com.testingbot.testingbotrest.TestingbotREST;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.module.Network;
import org.openqa.selenium.bidi.network.AddInterceptParameters;
import org.openqa.selenium.bidi.network.ContinueResponseParameters;
import org.openqa.selenium.bidi.network.InterceptPhase;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebDriver;
public class InterceptNetworkResponse {
public static final String KEY = "KEY";
public static final String SECRET = "SECRET";
public static final String REMOTE_URL = "https://" + KEY + ":" + SECRET + "@hub.testingbot.com/wd/hub";
public static void main(String[] args) throws MalformedURLException {
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("webSocketUrl", true);
HashMap<String, Object> testingbotOptions = new HashMap<>();
testingbotOptions.put("selenium-version", "4.33.0");
capabilities.setCapability("tb:options", testingbotOptions);
WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);
try {
Augmenter augmenter = new Augmenter();
driver = augmenter.augment(driver);
try (Network network = new Network(driver)) {
network.addIntercept(new AddInterceptParameters(InterceptPhase.RESPONSE_STARTED));
CountDownLatch latch = new CountDownLatch(1);
network.onResponseStarted(
responseDetails -> {
network.continueResponse(
new ContinueResponseParameters(responseDetails.getRequest().getRequestId()));
latch.countDown();
});
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
boolean countdown = latch.await(5, TimeUnit.SECONDS);
if (countdown) {
markTestStatus(true, "Network response intercepted successfully", driver);
} else {
markTestStatus(false, "Network response failed to intercept", driver);
}
driver.quit();
}
} catch (Exception e) {
markTestStatus(false, "Exception!", driver);
e.printStackTrace();
driver.quit();
}
}
public static void markTestStatus(Boolean status, String reason, WebDriver driver) {
TestingbotREST r = new TestingbotREST(System.getenv("TESTINGBOT_KEY"), System.getenv("TESTINGBOT_SECRET"));
Map<String, Object> data = new HashMap<String, Object>();
data.put("success", status ? "1" : "0");
data.put("name", reason);
r.updateTest(((RemoteWebDriver) driver).getSessionId().toString(), data);
}
}
using System.Collections.Concurrent;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.Network;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Safari;
namespace NUnit_TestingBot_Sample
{
[TestFixture("chrome", "latest", "Windows 10")]
[Category("BiDi")]
public class BidiTest
{
private IWebDriver _driver;
private CancellationToken _token = CancellationToken.None;
private readonly string _browser;
private readonly string _version;
private readonly string _os;
public BidiTest(string browser, string version, string os)
{
_browser = browser;
_version = version;
_os = os;
}
[SetUp]
public void SetUp()
{
var browserOptions = CreateBrowserOptions();
var testingBotOptions = CreateTestingBotOptions();
browserOptions.AddAdditionalOption("tb:options", testingBotOptions);
_driver = new RemoteWebDriver(
new Uri("https://hub.testingbot.com/wd/hub"),
browserOptions.ToCapabilities(),
TimeSpan.FromSeconds(60)
);
}
[Test]
public async Task CaptureNetworkLog()
{
await using var bidi = await _driver.AsBiDiAsync();
var responses = new ConcurrentQueue<string>();
await bidi.Network.ResponseStarted.SubscribeAsync(res =>
{
Console.WriteLine($"URL: {res.Request.Url}");
Console.WriteLine($"Method: {res.Request.Method}");
Console.WriteLine($"Status: {res.Response.Status}");
Console.WriteLine($"Headers: {string.Join(", ", res.Response.Headers.Select(h => $"{h.Name}: {(string)h.Value}"))}");
responses.Enqueue(res.Request.Url);
});
_driver.Navigate().GoToUrl("https://www.selenium.dev");
// BiDi events arrive asynchronously: wait up to 5 seconds for the first one
for (var i = 0; i < 50 && responses.IsEmpty; i++) await Task.Delay(100);
Assert.That(responses, Is.Not.Empty, "No network response was captured");
}
[TearDown]
public void TearDown()
{
if (_driver == null) return;
var testPassed = TestContext.CurrentContext.Result.Outcome.Status ==
NUnit.Framework.Interfaces.TestStatus.Passed;
try
{
((IJavaScriptExecutor)_driver).ExecuteScript($"tb:test-result={testPassed.ToString().ToLower()}");
}
catch (Exception ex)
{
TestContext.Out.WriteLine($"Failed to report test result: {ex.Message}");
}
finally
{
_driver.Quit();
_driver.Dispose();
}
}
private Dictionary<string, object> CreateTestingBotOptions()
{
var key = Environment.GetEnvironmentVariable("TESTINGBOT_KEY");
var secret = Environment.GetEnvironmentVariable("TESTINGBOT_SECRET");
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret))
{
throw new InvalidOperationException(
"TESTINGBOT_KEY and TESTINGBOT_SECRET environment variables must be set");
}
return new Dictionary<string, object>
{
["key"] = key,
["secret"] = secret,
["name"] = TestContext.CurrentContext.Test.Name,
["selenium-version"] = "4.27.0"
};
}
private DriverOptions CreateBrowserOptions()
{
return _browser.ToLower() switch
{
"firefox" => new FirefoxOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
},
"safari" => new SafariOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
},
_ => new ChromeOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
}
};
}
}
}
Basic Auth
By default, Selenium does not support providing an username and password when testing a website behind a Basic Auth protection.
The following test example will open a website and enter sample credentials in the basic auth popup window.
<dependency>
<groupId>com.testingbot</groupId>
<artifactId>testingbotrest</artifactId>
<version>1.1.0</version>
</dependency>
import com.testingbot.testingbotrest.TestingbotREST;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.module.Network;
import org.openqa.selenium.bidi.network.AddInterceptParameters;
import org.openqa.selenium.bidi.network.InterceptPhase;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.UsernameAndPassword;
public class BasicAuth {
public static final String KEY = "KEY";
public static final String SECRET = "SECRET";
public static final String REMOTE_URL = "https://" + KEY + ":" + SECRET + "@hub.testingbot.com/wd/hub";
public static void main(String[] args) throws MalformedURLException {
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("webSocketUrl", true);
HashMap<String, Object> testingbotOptions = new HashMap<>();
testingbotOptions.put("selenium-version", "4.33.0");
capabilities.setCapability("tb:options", testingbotOptions);
WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);
try {
Augmenter augmenter = new Augmenter();
driver = augmenter.augment(driver);
try (Network network = new Network(driver)) {
network.addIntercept(new AddInterceptParameters(InterceptPhase.AUTH_REQUIRED));
network.onAuthRequired(responseDetails -> {
String requestId = responseDetails.getRequest().getRequestId();
// Only answer the challenge from the site under test; let the browser handle any other
if (responseDetails.getRequest().getUrl().startsWith("https://httpbin.org/basic-auth/")) {
network.continueWithAuth(requestId, new UsernameAndPassword("foo", "bar"));
} else {
network.continueWithAuthNoCredentials(requestId);
}
});
driver.get("https://httpbin.org/basic-auth/foo/bar");
String text = driver.findElement(By.tagName("body")).getText();
System.out.println(text);
if (text.contains("authenticated")) {
markTestStatus(true, "Authentication entered successfully", driver);
} else {
markTestStatus(false, "Failed to enter authentication credentials", driver);
}
driver.quit();
}
} catch (Exception e) {
markTestStatus(false, "Exception!", driver);
e.printStackTrace();
driver.quit();
}
}
public static void markTestStatus(Boolean status, String reason, WebDriver driver) {
TestingbotREST r = new TestingbotREST(System.getenv("TESTINGBOT_KEY"), System.getenv("TESTINGBOT_SECRET"));
Map<String, Object> data = new HashMap<String, Object>();
data.put("success", status ? "1" : "0");
data.put("name", reason);
r.updateTest(((RemoteWebDriver) driver).getSessionId().toString(), data);
}
}
using System.Collections.Concurrent;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.Network;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Safari;
namespace NUnit_TestingBot_Sample
{
[TestFixture("chrome", "latest", "Windows 10")]
[Category("BiDi")]
public class BidiTest
{
private IWebDriver _driver;
private CancellationToken _token = CancellationToken.None;
private readonly string _browser;
private readonly string _version;
private readonly string _os;
public BidiTest(string browser, string version, string os)
{
_browser = browser;
_version = version;
_os = os;
}
[SetUp]
public void SetUp()
{
var browserOptions = CreateBrowserOptions();
var testingBotOptions = CreateTestingBotOptions();
browserOptions.AddAdditionalOption("tb:options", testingBotOptions);
_driver = new RemoteWebDriver(
new Uri("https://hub.testingbot.com/wd/hub"),
browserOptions.ToCapabilities(),
TimeSpan.FromSeconds(60)
);
}
[Test]
public async Task BasicAuth()
{
await using var bidi = await _driver.AsBiDiAsync();
// Pause requests that get an authentication challenge. Send the credentials only to the
// site they belong to; let the browser handle any other challenge as it normally would.
await bidi.Network.AddInterceptAsync([InterceptPhase.AuthRequired]);
await bidi.Network.AuthRequired.SubscribeAsync(async auth =>
{
ContinueWithAuth action = auth.Request.Url.StartsWith("https://httpbin.org/basic-auth/")
? new ContinueWithAuthCredentials(new AuthCredentials("foo", "bar"))
: new ContinueWithAuthDefault();
await bidi.Network.ContinueWithAuthAsync(auth.Request.Request, action);
});
_driver.Navigate().GoToUrl("https://httpbin.org/basic-auth/foo/bar");
var body = _driver.FindElement(By.TagName("body")).Text;
Console.WriteLine(body);
Assert.That(body, Does.Contain("authenticated"));
}
[TearDown]
public void TearDown()
{
if (_driver == null) return;
var testPassed = TestContext.CurrentContext.Result.Outcome.Status ==
NUnit.Framework.Interfaces.TestStatus.Passed;
try
{
((IJavaScriptExecutor)_driver).ExecuteScript($"tb:test-result={testPassed.ToString().ToLower()}");
}
catch (Exception ex)
{
TestContext.Out.WriteLine($"Failed to report test result: {ex.Message}");
}
finally
{
_driver.Quit();
_driver.Dispose();
}
}
private Dictionary<string, object> CreateTestingBotOptions()
{
var key = Environment.GetEnvironmentVariable("TESTINGBOT_KEY");
var secret = Environment.GetEnvironmentVariable("TESTINGBOT_SECRET");
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret))
{
throw new InvalidOperationException(
"TESTINGBOT_KEY and TESTINGBOT_SECRET environment variables must be set");
}
return new Dictionary<string, object>
{
["key"] = key,
["secret"] = secret,
["name"] = TestContext.CurrentContext.Test.Name,
["selenium-version"] = "4.27.0"
};
}
private DriverOptions CreateBrowserOptions()
{
return _browser.ToLower() switch
{
"firefox" => new FirefoxOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
},
"safari" => new SafariOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
},
_ => new ChromeOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
}
};
}
}
}
Intercept Network Response
Using CDP (DevTools) you can intercept network responses generated during the Selenium test.
import org.junit.jupiter.api.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.devtools.*;
// Selenium's typed CDP classes are version-pinned: v156 below must match the Chrome major
// version requested in setUp(), and must be one your selenium-java release ships.
// selenium-java 4.52 includes v154, v155 and v156. When you upgrade Chrome, upgrade
// selenium-java and change v156 in these imports and browserVersion together.
import org.openqa.selenium.devtools.v156.network.Network;
import org.openqa.selenium.devtools.v156.network.model.RequestId;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URI;
import java.time.Duration;
import java.util.Base64;
import java.util.HashMap;
import java.util.Optional;
public class WebDriverDevToolsTest {
private RemoteWebDriver driver;
private DevTools devTools;
@BeforeEach
public void setUp() throws Exception {
ChromeOptions options = new ChromeOptions();
options.setBrowserVersion("156");
options.setPlatformName("Windows 11");
HashMap<String, Object> tbOptions = new HashMap<>();
tbOptions.put("key", System.getenv("TESTINGBOT_KEY"));
tbOptions.put("secret", System.getenv("TESTINGBOT_SECRET"));
tbOptions.put("name", "DevTools Network Example");
tbOptions.put("selenium-version", "4.33.0");
tbOptions.put("build", "Java-DevTools-" + System.currentTimeMillis());
tbOptions.put("webSocketUrl", true);
options.setCapability("tb:options", tbOptions);
driver = new RemoteWebDriver(
new URI("https://hub.testingbot.com/wd/hub").toURL(),
options
);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
devTools = ((HasDevTools) driver).getDevTools();
devTools.createSession();
}
@Test
public void recordNetworkResponses() {
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()));
devTools.addListener(Network.responseReceived(), response -> {
System.out.println("URL: " + response.getResponse().getUrl());
System.out.println("Status: " + response.getResponse().getStatus());
System.out.println("Headers: " + response.getResponse().getHeaders());
RequestId requestId = response.getRequestId();
try {
String body = devTools.send(Network.getResponseBody(requestId)).getBody();
boolean isBase64 = devTools.send(Network.getResponseBody(requestId)).getBase64Encoded();
if (isBase64) {
body = new String(Base64.getDecoder().decode(body));
}
System.out.println("Body: " + body);
} catch (Exception e) {
System.out.println("Could not fetch response body: " + e.getMessage());
}
});
driver.get("https://www.selenium.dev");
try {
Thread.sleep(3000); // wait for responses
} catch (InterruptedException ignored) {}
}
@AfterEach
public void tearDown() {
if (driver != null) {
try {
((JavascriptExecutor) driver).executeScript("tb:test-result=true");
} catch (Exception ignored) {}
driver.quit();
}
}
}
using System.Collections.Generic;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.Chrome;
using System.Linq;
namespace NUnit_TestingBot_Sample
{
[TestFixture("chrome", "137", "Windows 10")]
[Category("DevTools")]
public class WebDriverDevtoolsTests
{
private IWebDriver? _driver;
private readonly string _browser;
private readonly string _version;
private readonly string _os;
public WebDriverDevtoolsTests(string browser, string version, string os)
{
_browser = browser;
_version = version;
_os = os;
}
[SetUp]
public void SetUp()
{
var browserOptions = CreateBrowserOptions();
var testingBotOptions = CreateTestingBotOptions();
browserOptions.AddAdditionalOption("tb:options", testingBotOptions);
_driver = new RemoteWebDriver(
new Uri("https://hub.testingbot.com/wd/hub"),
browserOptions.ToCapabilities(),
TimeSpan.FromSeconds(600));
_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
[Test]
public async Task RecordNetworkResponse()
{
INetwork networkInterceptor = _driver!.Manage().Network;
networkInterceptor.NetworkResponseReceived += (_, e) =>
{
Console.WriteLine($"Response body: {e.ResponseBody}");
Console.WriteLine($"Response headers: {string.Join(", ", e.ResponseHeaders.Select(h => $"{h.Key}: {h.Value}"))}");
Console.WriteLine($"Response status code: {e.ResponseStatusCode}");
Console.WriteLine($"Response URL: {e.ResponseUrl}");
};
await networkInterceptor.StartMonitoring();
_driver!.Navigate().GoToUrl("https://www.selenium.dev/");
await networkInterceptor.StopMonitoring();
}
private ChromeOptions CreateBrowserOptions()
{
var options = new ChromeOptions
{
BrowserVersion = _version,
PlatformName = _os,
UseWebSocketUrl = true
};
return options;
}
[TearDown]
public void TearDown()
{
_driver?.Quit();
_driver?.Dispose();
}
private Dictionary<string, object> CreateTestingBotOptions()
{
var key = Environment.GetEnvironmentVariable("TESTINGBOT_KEY");
var secret = Environment.GetEnvironmentVariable("TESTINGBOT_SECRET");
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret))
{
throw new InvalidOperationException(
"TESTINGBOT_KEY and TESTINGBOT_SECRET environment variables must be set");
}
return new Dictionary<string, object>
{
["key"] = key,
["secret"] = secret,
["name"] = $"{TestContext.CurrentContext.Test.Name}",
["selenium-version"] = "4.33.0",
["build"] = $"DevTools-Tests-{DateTime.Now:yyyy-MM-dd}"
};
}
}
}