October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Take a Screenshot with Selenium and Headless Chrome in Node.js

A practical Node.js guide to Selenium screenshots with headless Chrome, including base64 PNG saving, element capture, Chrome CLI, and common fixes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Selenium’s Node.js WebDriver to launch Chrome with headless options, open a page, and save driver.takeScreenshot() as a PNG. Selenium returns the image as a base64-encoded string, so write it with base64 decoding enabled. The example below also closes Chrome in a finally block so the browser is cleaned up if navigation or saving fails.

Install Selenium and prepare Chrome

Install the official JavaScript bindings with npm install selenium-webdriver. The Selenium JavaScript API currently states that Node.js 22 or newer is required; check its API documentation for the supported Node release lines when setting up a project.

As an Amazon Associate I earn from qualifying purchases.

Selenium Manager can automatically handle browser-driver setup in supported environments. If you manage ChromeDriver yourself, Selenium’s Chrome guide says its major version must match Chrome’s major version. The code uses Chrome’s --headless option, as in Selenium’s JavaScript example. The Chrome guide also lists --headless=new among commonly used arguments; choose an argument supported by the Chrome version and runtime you use.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture a page with Selenium

Save this as, for example, capture.js, then run node capture.js. Replace the example URL and output path as needed.

const { Builder, Browser } = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome')
const fs = require('node:fs/promises')

async function capture(url, outputPath = 'screenshot.png') {
  const options = new chrome.Options().addArguments('--headless')
  const driver = await new Builder()
    .forBrowser(Browser.CHROME)
    .setChromeOptions(options)
    .build()

  try {
    await driver.get(url)
    const pngBase64 = await driver.takeScreenshot()
    await fs.writeFile(outputPath, pngBase64, 'base64')
  } finally {
    await driver.quit()
  }
}

capture('https://example.com').catch((error) => {
  console.error(error)
  process.exitCode = 1
})

takeScreenshot() resolves to a base64-encoded PNG, not raw image bytes. Passing 'base64' as the write encoding decodes the string into a valid PNG file. The official Selenium JavaScript example uses this write pattern. This is an implementation pattern based on the documented API and example, not a claim that it was executed or tested here.

Capture a particular element

For a visible element rather than the page, find it and call takeScreenshot() on the returned WebElement:

const element = await driver.findElement({ css: '.product-card' })
const pngBase64 = await element.takeScreenshot()
await fs.writeFile('element.png', pngBase64, 'base64')

Use this inside the capture function’s try block, after navigation. Selenium documents element screenshots as the visible region within the element’s bounding rectangle; the result is not a promise of capturing hidden or off-screen portions of a tall element. See the WebDriver API and JavaScript example.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What Selenium captures—and what it does not guarantee

Selenium documents page screenshots as best effort, preferring the entire page, then the current window, the visible portion of the current frame, and finally the entire display containing the browser. The actual result depends on the page and driver; do not assume every page produces full-page pixels. For element screenshots, capture is limited to the visible part of that element’s bounding rectangle. These behaviors are described in the WebDriver API.

Choose Selenium or Chrome’s command-line capture

Approach Use it when What to account for
Selenium WebDriver You need scripted browser interaction, element capture, or screenshot steps inside automated tests. Set up a WebDriver session and ensure Chrome and ChromeDriver are compatible, or use Selenium Manager’s supported setup behavior.
Chrome headless CLI You need a direct one-off page screenshot and do not need Selenium automation. It is a command-line capture rather than a WebDriver test flow. Chrome’s reference documents the command and output location.

Chrome’s official headless command-line reference gives this example, which saves screenshot.png in the current working directory:

chrome --headless --screenshot --window-size=412,892 https://developer.chrome.com/

Run the browser remotely when needed

If the browser should run on a Selenium Grid or standalone server rather than on the machine running Node.js, Selenium’s JavaScript API documents configuring a Builder with a remote server URL. This can be useful when browser execution is managed separately or shared across a test environment. Consult the Selenium JavaScript API for the remote Builder options.

Troubleshoot common failures

  • Chrome fails to start or the session cannot be created: Check that Chrome is installed and available in the environment. If you installed ChromeDriver manually, align its major version with Chrome’s; Selenium Manager may handle driver setup in supported environments. See the Chrome guide and API setup notes.
  • The screenshot file is invalid or unreadable: Ensure you pass 'base64' to writeFile. The screenshot result is base64 text, so writing it as ordinary text does not decode the PNG.
  • The output is not a full-page image: Selenium describes page capture as best effort rather than a guarantee of full-page pixels. For a specific visible region, use an element screenshot; if full-page capture is essential, verify the output in the target browser and environment.
  • Chrome starts but a page or element is not ready: Navigation completing does not establish that every page-specific asset or asynchronous element is ready for capture. Add an explicit wait for a condition relevant to your page before taking the screenshot; choose the condition based on the page rather than assuming a fixed delay works universally.
  • The process leaves Chrome running after an error: Keep driver.quit() in a finally block so it runs after errors in navigation or screenshot writing. If session creation itself fails before a driver is assigned, there is no established session to close.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. A single GET request can return an image or PDF without setting up Selenium locally. For example, this cURL request saves a WebP screenshot:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

See the ScreenshotNeo documentation for request options. It accepts cookie/consent banners and removes known consent platforms, newsletter popups, and chat widgets before capture; these steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses identify page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots.

Sign up free for 1,000 screenshots a month, with no card required.

Frequently Asked Questions

Can Selenium save a screenshot as JPEG or WebP with this method?

No. Selenium’s documented WebDriver screenshot result is a base64-encoded PNG; the example writes that PNG to disk.

Can I use Selenium screenshots in a remote Grid session?

Yes. Selenium’s JavaScript API documents configuring a Builder to connect to a Grid or standalone server using a remote server URL.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.