How to capture java script errors using Selenium Java WebDriver

Using WebDriver log endopints (not supported)

There is no get-logs endpoint defined by W3C WebDriver yet..

https://www.w3.org/TR/webdriver/#endpoints

And this still opened:

https://github.com/w3c/webdriver/issues/406

So, unfortunately, driver.manage().logs() is not implemented by Firefox.

From geckodriver team:

This isn't in the W3C spec at this time, so we are delaying support until the behaviour is well specified. But your request is noted.

See

  • (2016) https://bugzilla.mozilla.org/show_bug.cgi?id=1453962

  • (2016) https://github.com/mozilla/geckodriver/issues/284

  • (2018) https://github.com/mozilla/geckodriver/issues/1292


Using DevTools (seems to work)

I was able to see the console output with selenium-4.1.1 and devtools.v85

package org.example.getlogs

import org.openqa.selenium.WebDriver
import org.openqa.selenium.devtools.DevTools
import org.openqa.selenium.devtools.v85.log.Log
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.firefox.FirefoxOptions

class GetLogsTest {

    public static void main(String[] args) {
        FirefoxOptions options = new FirefoxOptions();
        WebDriver driver = new FirefoxDriver(options);
        DevTools devTools = driver.getDevTools();
        devTools.createSession();
        devTools.send(Log.enable());
        devTools.addListener(Log.entryAdded(),
                logEntry -> {
                    System.out.println("" + logEntry.getLevel()+ ": " + logEntry.getText());
                });
        driver.get("https://stackoverflow.com/questions/70787924/how-to-capture-java-script-errors-using-selenium-java-webdriver");
        driver.quit();
    }
}