Versions used while doing this blog post, (These are the prerequisites to automate firefox browser. Browser and driver versions should match)
selenium-java version – 4.4.0
firefox browser version – 105
gecko driver version – 0.31.0 (Download link : https://github.com/mozilla/geckodriver/releases) [Using WebDriverManager to auto download the driver version]
Opening firefox in headless mode fastens the execution. This mode is really helpful for distributed executions.
Headless firefox browser can be opened using selenium by following below steps:
1. Map the correct version of geckodriver using WebDriverManager,
WebDriverManager.firefoxdriver().driverVersion("0.31.0").setup();
2. Instantiate an object with FirefoxOptions() class and add arguments to start the browser in headless mode. For windows platform we have set an argument to ‘disable gpu’ alongside ‘headless’
FirefoxOptions options = new FirefoxOptions(); options.addArguments("--headless"); options.addArguments("--disable-gpu");
3. Instantiate (creation of object) driver object with FirefoxDriver() class by passing the FirefoxOptions object (This step opens the Firefox browser in headless mode)
WebDriver driver = new FirefoxDriver(options);
3. Now, next steps of maximizing the browser, setting implicit timeout for driver object and launch of expected website can be carried out
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); driver.manage().window().maximize(); driver.get("https://www.google.com"); driver.findElement(By.name("q")).sendKeys("Test");
4. Quit/close the driver object after automating the necessary flows within the website.
driver.quit();
Sample code for reference
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.time.Duration;
public class OpenFirefoxHeadlessUsingSelenium4 {
public static void main(String[] args){
WebDriverManager.firefoxdriver().driverVersion("0.31.0").setup();
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--headless");
options.addArguments("--disable-gpu");
WebDriver driver = new FirefoxDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("Test");
driver.quit();
}
}