How to launch Chrome browser as headless in Selenium Java


“Headless” browser is a hot term now especially in executing UI automated scripts. When we launch a browser it opens up in a window or with a UI. We can launch a browser without that window or UI that is called a headless browser. A headless browser gives you a real browser context without the memory overhead of running a full version of a browser. All major browsers like Chrome, Firefox, Microsoft Edge support headless mode.

Running automated UI scripts in a headless browser may lower test execution time but not that much significantly. You can experience a little better performance during automated UI scripts execution. But using a headless browser we can minimize the chances of encountering system configuration issues like memory, the abrupt closure of the browser, etc. Execution of scripts in a headless browser is helpful when you don’t have any grid set up as it allows you to perform other tasks with scripts executions.

Earlier we had HtmlUnit Driver, PhantomJS (Suspended) for headless execution but they were not stable much. Capturing screenshot was a challenge and many did not support that.

In this post, we will learn to launch a Chrome browser in headless mode and will capture a screenshot using Selenium WebDriver Java.

Launching a Chrome Browser in headless mode

There are two ways of launching a Chrome browser in headless mode:-

  1. Using setHeadless() method of ChromeOption class
  2. Using addArguments() method of ChromeOption class

Whatever way you use make sure you set window size as well. It helps in the smooth running of scripts, better resolution, and screen capturing.

You can see the captured screenshot by navigating to the path provided.

You can download/clone the above sample project from here.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.