Invoke Chrome browser in headless mode using Selenium 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 – 3.141.59
chrome browser version – 80.0.3987.163
chrome driver version – 80.0.3987.106 (Download link : https://chromedriver.storage.googleapis.com/index.html?path=80.0.3987.106/)

Opening chrome in headless mode fastens the execution. This mode is really helpful for distributed executions.

Headless chrome browser can be opened using selenium by following below steps:
1. Map the path of the downloaded chromedriver.exe file to ‘webdriver.chrome.driver’,

System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\src\\main\\resources\\chromedriver.exe");

2. Instantiate an object with ChromeOptions() class and add arguments to start the browser in headless mode. For windows platform we have set an argument to ‘disable gpu’ alongside ‘headless’

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--disable-gpu");

3. Instantiate (creation of object) driver object with ChromeDriver() class by passing the ChromeOptions object (This step opens the chrome browser in headless mode)

WebDriver driver = new ChromeDriver(options);

3. Now, next steps of maximizing the browser, setting implicit timeout for driver object and launch of expected website can be carried out

driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://www.google.com");

4. Quit/close the driver object after automating the necessary flows within the website.

Sample code for reference

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;

public class LaunchHeadlessChromeTest {
    public static void main(String[] args){
        System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\src\\main\\resources\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless");
        options.addArguments("--disable-gpu");
        WebDriver driver = new ChromeDriver(options);
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://www.google.com");
        driver.findElement(By.name("q")).sendKeys("Test");
        driver.quit();
    }
}

Leave a Reply

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