Run Chrome Headless Selenium Java

Run Chrome Headless Selenium Java

Starting from Chrome version 59, the Chrome browser introduced the ability to run the test without launching a visual browser window. 

This feature allows you to run tests faster and without a graphical component, but Headless browsers don't mimic user behavior, and debugging is not easy. 

Capturing Screenshots and generating reports has no impact if you are running headless, and this feature is useful when running on CI/CD pipelines, doing web scrapping or when you want to run your test in the background. 

You have to add a headless option in your Chrome Options to make your browser headless. You can use either of the below code for headless.

options.addArguments("--headless");

or

options.setHeadless(true);

Note: Adding just the headless option is not enough. The headless browser runs in resolution 800x600, which is not the standard size. The maximum number of desktops uses the resolution of 1920x1080 pixels. You can check the usage here. Add the below code to specify the screen size.

options.addArguments("--headless","--window-size=1920,1080");

Example

public void launchChromeBrowserHeadless()
{
    System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "//drivers//chromedriver");

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless","--window-size=1920,1080");

    WebDriver driver;
    driver = new ChromeDriver(options);
		
    driver.get("http://www.autopract.com");	
}

You can also disable a few other things depending on your requirement while running tests in headless mode.

  • --disable-gpu: This is only required on Windows. Other platforms no longer need it. The --disable-gpu flag is a temporary workaround for a few bugs.
  • --disable-extensions: This will disables existing extensions on the Chrome browser.
  • --disable-popup-blocking: Disables pop-ups displayed on the Chrome browser.
  • --disable-dev-shm-usage: This is to avoid the docker memory crash issue. 
  • --ignore-certificate-errors: Disable Chrome Checking All SSL Certificates.
  • --no-sandbox: If you are using a Linux environment, maybe you have to add --no-sandbox. The --no-sandbox flag is not needed on Windows if you set the user container correctly.

Video Tutorial: Run Chrome Headless Selenium-Java

Standard (Image)