Execute Chrome in Headless Mode using Selenium Webdriver


Execute Chrome in Headless Mode using Selenium Webdriver

Long time back i have posted article on accelerating the test execution using headless mode,  Headless Browser For Accelerating Your Test Automation.   Google Chrome versions before 59, headless execution had to be done by third-party headless browsers like PhantomJSSlimerJSTrifleJSNightmare,  CasperJS and HTMLUnit.

It means, browsers uses third party engines to execute tests on headless mode and not native engine of the browser below are list of headless browsers and engines used by them to execute the test in headless mode.

Headless Browser Engine
PhantomJS QtWebKit
SlimerJS Gecko (Firefox)
TrifleJS Trident (IE)
Nightmare Electron


When we talk about testing, it’s necessary to simulate Google’s real engine, as both Internet users and web devs tend toward using Google Chrome.

How it Works With Java

As Google Chrome ships with headless execution in version 59 (as you can see here) we can tell ChromeDriver the options before the execution.

I hope now, you know how use chrome with selenium and java. it is import to know if you are an Test Automation or DevOps Engineer.

In the code below I added two options through ChromeOptionsheadless and the window-size.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class ChromeHeadlessTest {

 private WebDriver driver;
 private String baseUrl;

 public void setUp() throws Exception {

// define chrome driver location in system, so that selenium can find it during execution.
 System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe"); 

// define chrome options
 ChromeOptions options = new ChromeOptions();

// To execute test in headless mode below argument is must.

// initiate the chrome driver
 driver = new ChromeDriver(options);

// define base url
 baseUrl = "https://qeworks.com";

// define implicit timeout
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

// We are ready, now all action will be performed in headless mode.
System.out.println("Page Source: " + driver.getPageSource());

The headless option will tell to Google Chrome to execute in headless mode. The window-size is a way to control the responsiveness (and allows your site be displayed, like a mobile site, if you have not set a window size).

You can see some other ways to inform the ChromeOptions here.

Leave A Comment