Fail a Test on Browser Console Errors
Collect console.error calls and uncaught JavaScript exceptions with WebDriver BiDi, then fail the test with the messages, while ignoring known noise.
Problem
The page looks fine and every assertion passes, but the console shows TypeError: Cannot read properties of undefined on every load. Users on a slightly different path hit a blank widget. You want the suite to notice JavaScript errors, not just broken DOM.
Solution
Enable BiDi when creating the driver, subscribe to console entries and JavaScript exceptions before navigating, collect errors in a list, and assert it is empty at the end of the test (after filtering known third-party noise).
import org.openqa.selenium.bidi.module.LogInspector;import org.openqa.selenium.bidi.log.LogLevel;
ChromeOptions options = new ChromeOptions();options.setCapability("webSocketUrl", true); // enable BiDiWebDriver driver = new ChromeDriver(options);
List<String> errors = new CopyOnWriteArrayList<>();LogInspector logs = new LogInspector(driver);logs.onConsoleEntry(e -> { if (e.getLevel() == LogLevel.ERROR) errors.add("console.error: " + e.getText());});logs.onJavaScriptException(e -> errors.add("uncaught: " + e.getText()));
driver.get("https://app.example.com/checkout");// ... scenario ...
List<String> ignored = List.of("googletagmanager", "ResizeObserver loop");List<String> real = errors.stream() .filter(msg -> ignored.stream().noneMatch(msg::contains)) .toList();assertTrue(real.isEmpty(), "Browser errors:\n" + String.join("\n", real));options = webdriver.ChromeOptions()options.enable_bidi = Truedriver = webdriver.Chrome(options=options)
errors = []driver.script.add_console_message_handler( lambda e: errors.append(f"console.error: {e.text}") if e.level == "error" else None)driver.script.add_javascript_error_handler( lambda e: errors.append(f"uncaught: {e.text}"))
driver.get("https://app.example.com/checkout")# ... scenario ...
IGNORED = ("googletagmanager", "ResizeObserver loop")real = [m for m in errors if not any(i in m for i in IGNORED)]assert not real, "Browser errors:\n" + "\n".join(real)const options = new chrome.Options().enableBidi();const driver = await new Builder().forBrowser('chrome').setChromeOptions(options).build();
const errors = [];await driver.script().addConsoleMessageHandler((e) => {if (e.level === 'error') errors.push(`console.error: ${e.text}`);});await driver.script().addJavaScriptErrorHandler((e) => errors.push(`uncaught: ${e.text}`));
await driver.get('https://app.example.com/checkout');// ... scenario ...
const IGNORED = ['googletagmanager', 'ResizeObserver loop'];const real = errors.filter((m) => !IGNORED.some((i) => m.includes(i)));assert.deepStrictEqual(real, [], 'Browser errors:\n' + real.join('\n'));var options = new ChromeOptions { UseWebSocketUrl = true };var driver = new ChromeDriver(options);
var errors = new ConcurrentQueue<string>();var bidi = await driver.AsBiDiAsync();// log.entryAdded carries both console calls and uncaught exceptionsawait bidi.Log.OnEntryAddedAsync(e =>{ if (e.Level.ToString().Equals("error", StringComparison.OrdinalIgnoreCase)) errors.Enqueue(e.Text);});
driver.Navigate().GoToUrl("https://app.example.com/checkout");// ... scenario ...
string[] ignored = ["googletagmanager", "ResizeObserver loop"];var real = errors.Where(m => !ignored.Any(i => m?.Contains(i) == true)).ToList();Assert.That(real, Is.Empty, "Browser errors:\n" + string.Join("\n", real));Why It Works
WebDriver BiDi pushes log.entryAdded events over a WebSocket the moment the browser produces them, so nothing is lost between polls and nothing depends on Chromium-only logging APIs. Subscribing before get() captures errors thrown during page load, which are the most common ones. Because it is a W3C protocol, the same code works on Chrome, Edge and Firefox.
Making It Automatic
Put the subscription in your driver fixture or base test and the assertion in teardown, so every test checks the console without opting in. Attach the full list (not just errors) to the test report on failure; warnings often explain the error. See Browser and Driver Logs for a reusable collector class.
Gotchas
- BiDi must be enabled at session creation. Without the
webSocketUrlcapability /enable_bidi/enableBidi()/UseWebSocketUrl, the handlers throw or silently never fire. - Third-party noise. Analytics, ad and chat widgets log errors you do not own. Keep an explicit allowlist of substrings in one place and review it; do not filter everything from other origins blindly.
- Failed network requests (a 404 image) show up as console errors in Chrome. Decide whether those should fail the test or be checked separately by a broken links style check.
- The legacy logs API (
driver.manage().logs().get("browser")) is Chromium-only and outside the W3C spec. Prefer BiDi for new code. - Level naming. The level is reported as
error,warn,infoordebug. Compare case-insensitively.
Learn the theory
- Browser and Driver Logs Turn on the logs that explain failures: browser console output via BiDi, chromedriver and geckodriver logs, Selenium's own client logging, network failures, and how to collect them per test.
- WebDriver BiDi Enable the bidirectional protocol and use it for console log capture, JavaScript error detection, basic authentication, DOM mutation events, preload scripts, emulation and web extensions, with browser support and migration guidance as of Selenium 4.52.