Reading console logs of Chrome browser using Selenium 4, Chrome Devtools and JAVA

Versions used while doing this blog post, (These are the prerequisites to automate chrome browser. Browser and driver versions should match)
selenium-java version – 4.4.0
chrome browser version – 105
chrome driver version – 105 [used WebDriverManager library to auto download needed chrome driver version]

Chrome browser can be opened using selenium by following below steps:
1. Instantiate (creation of object) driver object with ChromeDriver() class using WebDriverManager library (This step opens the chrome browser)

WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

2. Instantiate (creation of object) driver object with ChromeDriver() class (This step opens the chrome browser)

ChromeDriver driver = new ChromeDriver(); //--> We use ChromeDriver here, as it extends ChromiumDriver which as devtools methods

3. Now, next steps of maximizing the browser and setting implicit timeout for driver object

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
driver.manage().window().maximize();

4. Now, create DevTools session using getDevTools() and createSession() methods

DevTools devTools = driver.getDevTools();
//Create chrome dev tools session
devTools.createSession();

5. Now, enable the logs and add a listener to read and print console logs

//Enable the logs
devTools.send(Log.enable());

//Listen to console
devTools.addListener(Log.entryAdded(), entry -> System.out.println(entry.getText()));

6. Launch the expected website URL and observe the display of console messages in output

driver.get("https://nhnb.github.io/console-log/console-log/demo.html");

Sample code for reference

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v104.log.Log;
import java.time.Duration;

public class ReadConsoleLogsUsingSelenium4 {

    public static void main(String[] args){
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));

        DevTools devTools = driver.getDevTools();
        //Create chrome dev tools session
        devTools.createSession();

        //Enable the logs
        devTools.send(Log.enable());

        //Listen to console
        devTools.addListener(Log.entryAdded(), entry -> System.out.println(entry.getText()));

        driver.get("https://nhnb.github.io/console-log/console-log/demo.html");

        driver.quit();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *