User Agents

Web browsers and everyday web tech, explained

Run Chrome in Headless Mode with Selenium Java

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Running Chrome in headless mode with Selenium Java allows you to execute browser automation without a visible graphical user interface (GUI). This is essential for running tests on Continuous Integration (CI) servers, such as Jenkins or GitHub Actions, where no monitor is attached. By eliminating the overhead of rendering the UI, headless mode typically consumes fewer system resources and can lead to faster execution times for automated test suites.

What You'll Need

  • Java Development Kit (JDK) installed and configured in your system path.
  • An Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse.
  • The Selenium Java Client library added to your project dependencies (via Maven or Gradle).
  • Google Chrome browser installed on the machine.
  • ChromeDriver that matches the version of your installed Chrome browser.

Step-by-Step

  1. Set up your Project Dependencies: If you are using Maven, add the Selenium Java dependency to your pom.xml file. Ensure you are using a recent version of Selenium (4.x is recommended) to ensure compatibility with the latest Chrome options.
  2. Import Necessary Classes: At the top of your Java class, import the required Selenium classes. You will specifically need org.openqa.selenium.WebDriver, org.openqa.selenium.chrome.ChromeDriver, and org.openqa.selenium.chrome.ChromeOptions.
  3. Initialize ChromeOptions: Create an instance of the ChromeOptions class. This class is used to customize the behavior of the Chrome browser session.
  4. Add the Headless Argument: Use the addArguments method to tell Chrome to run without a window. For modern versions of Chrome (v109+), the recommended argument is "--headless=new". The "--headless=new" flag enables the new headless mode which behaves more like the headed browser, supporting extensions and better rendering.
  5. Configure Additional Performance Arguments: To ensure stability in headless environments (especially Linux servers), add arguments such as "--disable-gpu" to disable hardware acceleration and "--no-sandbox" to bypass the OS security model that can sometimes block the driver in Docker containers.
  6. Set a Window Size: Since there is no physical screen, Chrome may default to a very small window size, which can cause elements to hide behind menus or overlap. Use options.addArguments("window-size=1920,1080") to simulate a standard desktop resolution.
  7. Instantiate the WebDriver: Pass the ChromeOptions object into the ChromeDriver constructor. This tells Selenium to launch the browser using the headless configuration you defined.
  8. Execute Your Script: Write your automation logic (navigating to URLs, clicking elements, asserting text) as you normally would. The browser will operate in the background.
  9. Quit the Session: Always call driver.quit() at the end of your script. Because headless browsers are invisible, failing to quit the driver will leave orphan Chrome processes running in the background, eventually consuming all available RAM.

Common Mistakes

  • Using Outdated Headless Flags: Using --headless instead of --headless=new in newer Chrome versions can lead to discrepancies in how the page renders, causing tests to fail in headless mode that passed in headed mode.
  • Forgetting Window Dimensions: Many developers forget to set a window size. This leads to "ElementNotInteractableException" because the browser defaults to a small size, causing elements to be hidden or shifted.
  • Ignoring Driver Versioning: Attempting to run a headless session with a ChromeDriver version that does not match the installed Chrome browser version will result in a SessionNotCreatedException.
  • Missing the No-Sandbox Flag: When moving from a local Windows machine to a Linux-based CI server, scripts often fail unless --no-sandbox is added to the options.

Tips

  • Capture Screenshots for Debugging: Since you cannot see the browser, use the TakesScreenshot interface to save images of the page when a test fails. This is the only way to see what the browser saw during a headless crash.
  • Use a User-Agent String: Some websites detect headless browsers by checking the User-Agent string and may block the request. You can override this by adding options.addArguments("user-agent=Mozilla/5.0 ...").
  • Log Browser Console Errors: Enable LoggingPreferences in your ChromeOptions to capture JavaScript errors from the browser console, which are otherwise invisible in headless mode.
  • Combine with WebDriverManager: Use the WebDriverManager library to automatically handle the downloading and setup of the correct ChromeDriver version, reducing manual maintenance.

Troubleshooting

If your headless browser is not behaving as expected, start by switching back to headed mode (remove the headless argument) to verify that the script logic is correct. If the script works in headed mode but fails in headless, the issue is likely related to rendering or detection.

If you encounter a SessionNotCreatedException, verify that your Chrome browser has not auto-updated to a version newer than your ChromeDriver. Update the driver to match the browser version exactly.

If elements are not being found, check the window size. Use a screenshot to verify if the element is off-screen or hidden behind a responsive mobile menu that only appears in small window sizes.

For crashes on Linux/Docker environments, ensure that --disable-dev-shm-usage is added to your arguments. This prevents Chrome from crashing due to limited shared memory in containerized environments.

Frequently Asked Questions

Is headless mode faster than headed mode?

Yes, generally. Because the system does not have to spend CPU and GPU resources rendering the visual interface, tests typically execute faster and use less memory.

Can I still take screenshots in headless mode?

Yes. Selenium's getScreenshotAs method works perfectly in headless mode, allowing you to capture the current state of the DOM visually.

Does headless mode support JavaScript?

Yes. Headless Chrome is a full browser engine; it executes JavaScript, handles AJAX requests, and renders CSS exactly like the visible version.

Why is my website blocking my headless browser?

Some servers detect the HeadlessChrome string in the User-Agent header. Changing the User-Agent to a standard browser string often resolves this issue.

Can I run headless mode on a server without any GUI installed?

Yes, that is the primary purpose of headless mode. It allows Chrome to run on minimal Linux distributions (like Ubuntu Server or Alpine) that lack a X11 or Wayland display server.