How to run a headless Browser with Selenium Java

asked 2 years ago

Selenium WebDriver allows you to run tests in headless mode, which means the browser runs in the background without opening a visible window. This is useful for running tests on servers or in continuous integration (CI) environments where no GUI is available.

To run tests in headless mode on Chrome, you can use ChromeOptions  and pass the --headless argument.

Example: Running Chrome in Headless Mode

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

public class HeadlessTest {
    public static void main(String[] args) {
        // Set up ChromeOptions
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless"); // Enable headless mode

        // Create WebDriver instance with headless options
        WebDriver driver = new ChromeDriver(options);

        // Open the website
        driver.get("https://www.qafeast.com/demo");

        // Print the page title or current URL to verify it worked
        System.out.println("Page Title: " + driver.getTitle());

        // Close the browser
        driver.quit();
    }
}