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.7.0
firefox browser version – 106
gecko driver version – 0.31.0 (Download link : https://github.com/mozilla/geckodriver/releases) [Selenium manager in latest version auto downloads the driver]
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. 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");
2. Instantiate (creation of object) driver object with FirefoxDriver() class by passing the FirefoxOptions object (This step opens the Firefox browser in headless mode)
IWebDriver 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().ImplicitWait = TimeSpan.FromSeconds(15); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl("https://www.google.com");
4. Quit/close the driver object after automating the necessary flows within the website.
driver.Quit();
Sample code for reference
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
namespace Selenium4CsharpExamples
{
public class OpenFirefoxHeadlessUsingSelenium4
{
static void Main(string[] args)
{
FirefoxOptions options = new FirefoxOptions();
options.AddArguments("-headless");
IWebDriver driver = new FirefoxDriver(options);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(15);
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://www.google.com");
driver.Quit();
}
}
}