Execute Chrome in Headless Mode using Selenium Webdriver

Execute Chrome in Headless Mode

193

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 BrowserEngine
PhantomJSQtWebKit
SlimerJSGecko (Firefox)
TrifleJSTrident (IE)
NightmareElectron

 

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;

 @Test
 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.
 options.addArguments("headless");

// 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.
 driver.get("baseUrl");
System.out.println("Page Source: " + driver.getPageSource());
driver.close();
}
}

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.

Subscribe to Newsletter
Get Latest Posts, Articles and Learning Lessons on Software Testing and Test Automation
You can unsubscribe at any time

Comments are closed.