Headless Firefox Screenshot with Selenium Java
Capturing a screenshot of a web page while Selenium runs Firefox in headless mode is a common requirement for automated testing, visual regression, or monitoring tasks. The process is straightforward once you understand the pieces that must work together: a compatible Selenium binding, a matching GeckoDriver, a Firefox binary that can run without a display, and a small amount of Java code that tells the driver what to do.
What You’ll Need
- Java JDK 11 or newer (the Selenium Java client is built for Java 8+, but Java 11+ is recommended for newer libraries)
- Maven or Gradle to manage dependencies (the example uses Maven)
- GeckoDriver that matches the Firefox version you plan to use
- Firefox ≥ 60 (which supports headless mode out of the box)
- An IDE or text editor and a terminal to run the build and test
Step‑by‑Step
- Set up a Maven project
Create a new directory and runmvn archetype:generate -DgroupId=com.example -DartifactId=screenshot -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false. Add the Selenium dependency topom.xml: <dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.18.0</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.6.0</version>
</dependency>
</dependencies>- Download GeckoDriver
If you prefer manual control, download the appropriate binary from GitHub releases and place it in a directory that’s on your system PATH. Alternatively, thewebdrivermanagerdependency above will download and cache the driver automatically. - Configure Firefox for headless operation
Create aFirefoxOptionsinstance and enable headless mode: FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);- Instantiate the driver
Using WebDriverManager makes driver setup painless: WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver(options);- Navigate to the target page
Use a normaldriver.get(url)call. If you need to wait for dynamic content, wrap the navigation in aWebDriverWaitthat waits for a specific element. - Take the screenshot
Cast the driver toTakesScreenshotand capture the image: File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);- Persist the file
Choose a directory and file name, then copy the temporary file: Path destination = Paths.get("screenshots", "home.png");
Files.createDirectories(destination.getParent());
Files.copy(screenshot.toPath(), destination, StandardCopyOption.REPLACE_EXISTING);- Clean up
Always quit the driver to release resources: driver.quit();
Common Mistakes
- Using a Firefox binary that is too old to support headless mode (pre‑60)
- Forgetting to set the
options.setHeadless(true)flag before constructing the driver - Mixing the old
org.openqa.selenium.firefox.FirefoxDriverwith the newGeckoDriverServicewithout configuring the service correctly - Attempting to cast the driver to
TakesScreenshotbefore the driver is fully initialized - Writing the screenshot to a location without write permissions or to a non‑existent parent directory
- Running the test on a CI machine that lacks the
DISPLAYenvironment variable but also does not enable headless mode
Tips
- Use
WebDriverManagerto avoid manual driver downloads and version mismatches. - Leverage
FirefoxProfileto set preferences likebrowser.download.dirif you need to download files before screenshotting. - When testing visual regressions, capture the full page by adding
options.addArguments("-width=1920", "-height=1080");or by using Firefox’sfullPageScreenshotcapability. - Store screenshots in a timestamped folder to keep test runs organized:
String folder = "screenshots/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")); - Log the screenshot path so that debugging is easier when a test fails.
Troubleshooting
When the screenshot is blank or the test fails to start, try the following steps:
- Verify the Firefox version
Runfirefox --versionand compare it with the GeckoDriver release you downloaded. Mismatched versions often cause silent failures. - Check the headless flag
AddSystem.out.println(options.isHeadless());before driver creation to confirm the flag is set. - Inspect driver logs
Enable driver logging by addingoptions.setLogLevel(FirefoxDriverLogLevel.DEBUG);and reviewing the console output for errors. - Confirm the page has fully rendered
UseWebDriverWaitto wait for a stable element or fordocument.readyState == "complete"before taking the screenshot. - Check file permissions
Ensure the process has write access to the target directory and that the file name does not contain illegal characters. - Run in non‑headless mode temporarily
Remove the headless flag to see the browser UI; this can reveal layout issues that cause an empty screenshot.
Frequently Asked Questions
Can I capture a full‑page screenshot in headless Firefox?
Yes. Firefox supports a fullPageScreenshot capability. Add options.addPreference("browser.screenshot.fullPage", true); before driver creation, or use the FirefoxDriver.getFullPageScreenshotAs() method if you’re on Selenium 4.18+.
Does the screenshot include elements hidden by CSS or off‑screen?
Only visible elements are captured. If an element is hidden with display:none or is outside the viewport, it will not appear in the image unless you scroll it into view or use full‑page capture.
What if the screenshot file is corrupted or unreadable?
Common causes are a race condition where the file is deleted before it’s read, or the driver writes to a temporary location that is cleaned up too early. Use Files.copy immediately after capture and avoid deleting the temp file until after the copy succeeds.
Can I embed the screenshot in test reports?
Yes. Convert the file to Base64 with Base64.getEncoder().encodeToString(Files.readAllBytes(destination)); and include the data URI in HTML reports or Allure attachments.
Is there a way to take screenshots without Java code?
Some CI tools expose a browser driver that can capture screenshots via command line, but for Selenium‑based automation the Java snippet shown above is the most portable and reliable method.