How to Configure Headless Chrome to Download Files Automatically
Configure Puppeteer, Selenium, or CDP so headless Chrome saves downloads to a writable directory, then verify completion before your job exits.

To make headless Chrome download a file automatically, set the browser’s download policy to allow and provide a writable, absolute downloadPath before clicking a link, submitting a form, or navigating to the download. Then keep Chrome running until the download is complete and verify the resulting file. Headless Chrome does not need a visible prompt when automation supplies this policy and destination.
This guide covers Puppeteer, Selenium, and direct Chrome DevTools Protocol (CDP), including event and filesystem-based completion checks, setup choices, troubleshooting, and operational concerns.
1. Understand the download settings
Chrome’s CDP command Browser.setDownloadBehavior controls download handling. The relevant fields are:

| Field | Purpose | Guidance |
|---|---|---|
behavior / policy |
Choose what Chrome does with downloads. | Use allow for ordinary filenames, or allowAndName when GUID-based names are useful. deny blocks downloads; default restores the default behavior. |
downloadPath |
Destination directory. | Required for allow and allowAndName. Use a writable absolute path that exists or that your program creates. |
eventsEnabled |
Enable download progress events where supported. | Useful when the client exposes CDP download events and you want a completion signal from Chrome. |
browserContextId |
Scope behavior to a browser context in CDP. | Use only when managing multiple contexts and your CDP client supports the field. |
CDP documents the behavior values, path requirement, and optional events. Puppeteer exposes a related DownloadBehavior interface using policy and downloadPath; Selenium’s versioned DevTools bindings expose corresponding fields. Check the reference for the specific browser and library version you run: CDP Browser.setDownloadBehavior, Puppeteer DownloadBehavior, and Selenium Browser API.
2. Configure Puppeteer
Install Puppeteer and run this as an ES module. It creates an isolated directory, sets download behavior before visiting the test page, starts a download, waits for the output file to appear, and checks that it is no longer changing size. Replace the example URL and expected filename with the values for your application.
import puppeteer from 'puppeteer';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
const downloadPath = await fs.mkdtemp(path.join(os.tmpdir(), 'chrome-download-'));
const expectedFile = path.join(downloadPath, 'report.csv');
const browser = await puppeteer.launch({ headless: true });
try {
const page = await browser.newPage();
await page.setDownloadBehavior({
policy: 'allow',
downloadPath,
});
await page.goto('https://example.test/reports', {
waitUntil: 'domcontentloaded',
});
await page.locator('a[data-download="report"]').click();
const deadline = Date.now() + 60_000;
let previousSize = -1;
let stableReads = 0;
while (Date.now() < deadline) {
try {
const stat = await fs.stat(expectedFile);
if (stat.size > 0 && stat.size === previousSize) {
stableReads += 1;
if (stableReads >= 2) break;
} else {
previousSize = stat.size;
stableReads = 0;
}
} catch {
// The file may not exist until Chrome starts writing it.
}
await new Promise(resolve => setTimeout(resolve, 500));
}
const stat = await fs.stat(expectedFile);
if (stat.size === 0 || stableReads < 2) {
throw new Error('Download did not finish before the deadline');
}
console.log(`Saved ${stat.size} bytes to ${expectedFile}`);
} finally {
await browser.close();
}
The example uses filesystem observation because it works even when an event wrapper is unavailable. For downloads with server-generated names, discover the completed file in the isolated directory rather than assuming report.csv. A stable file size is a practical signal, not proof that the bytes are valid; validate the file format or expected content when correctness matters.
Current Puppeteer calls the setting setDownloadBehavior on the page and uses policy. Its API requires a downloadPath for allow and allowAndName. See the Puppeteer Page.setDownloadBehavior reference for version details.
3. Configure Selenium with Chrome DevTools
Selenium’s DevTools APIs are versioned with browser-specific bindings. The command fields are the CDP equivalents: set Behavior to allow, supply DownloadPath, and enable events if that binding supports EventsEnabled. The Java pattern below illustrates the setup; use the matching selenium-devtools-vNN package for the Chrome major version in your environment, since generated package names and constructors vary across Selenium releases.
import java.nio.file.Files;
import java.nio.file.Path;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.vNN.browser.Browser;
import org.openqa.selenium.devtools.vNN.browser.model.Behavior;
public class DownloadReport {
public static void main(String[] args) throws Exception {
Path downloadDir = Files.createTempDirectory("chrome-download-");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ChromeDriver driver = new ChromeDriver(options);
try {
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Browser.setDownloadBehavior(
Behavior.ALLOW,
downloadDir.toAbsolutePath().toString(),
Optional.empty(),
Optional.of(true)));
driver.get("https://example.test/reports");
driver.findElement(By.cssSelector("a[data-download='report']")).click();
// Wait for the expected completed file here; do not quit immediately.
} finally {
driver.quit();
}
}
}
This is a binding pattern, not a copy-paste guarantee for every Selenium version: imports, overloads, optional arguments, and event support differ. Resolve vNN to the generated package matching your browser and Selenium dependency, then follow that package’s API reference. If your binding does not expose the command, use a supported CDP session or a browser-management API compatible with that version. Selenium documents Behavior, BrowserContextId, DownloadPath, and EventsEnabled in its Browser DevTools API.
4. Send the CDP command directly
If your automation framework provides a CDP session, send the command before the action that initiates the response. Here is the protocol payload in JavaScript-like form; the way to create the session depends on the client.
await client.send('Browser.setDownloadBehavior', {
behavior: 'allow',
downloadPath: '/absolute/path/to/downloads',
eventsEnabled: true
});
Use allowAndName in place of allow when GUID-based filenames are preferable, for example when the application does not provide stable filenames or collisions must be avoided. Account for the resulting naming convention in your file lookup. CDP can emit Browser.downloadWillBegin and Browser.downloadProgress events when download events are enabled; treat the protocol’s completed state as a useful signal, then check that the expected artifact exists.
5. Make completion reliable
The most common automation bug is closing the browser immediately after clicking. A click only starts a request; it does not mean Chrome has finished writing the file. Use an event if your client supports it, or observe the filesystem. In either case:
- Create a writable, isolated directory for the run or browser context.
- Set the download policy and destination before triggering the download.
- Trigger the link, form submission, or navigation and capture any resulting page or network errors.
- Wait for the completion event or final file. Ignore temporary partial files such as
.crdownload. - Check filename, nonzero size, and—where useful—content type, file signature, or expected contents.
- Close Chrome only after validation, then clean up the directory when the artifact is no longer needed.
For event-driven flows, register listeners before clicking so a fast response cannot finish before the listener exists. Use a timeout, and make sure error paths still close the browser. For filesystem polling, poll at a reasonable interval and enforce a deadline; an unbounded wait can tie up workers when the server never responds.
6. Browser binary and headless mode
Chrome for Developers describes current headless Chrome as sharing the unified Chrome implementation with headful mode. Chrome 132.0.6793.0 introduced the separately maintained chrome-headless-shell for the old headless mode. If behavior differs between a local machine and CI, check the actual executable and version being launched rather than assuming every “headless Chrome” binary is identical. See Chrome’s Headless mode guide.
Puppeteer normally downloads a compatible Chrome for Testing build and a chrome-headless-shell binary. Its installation guidance lists approximate browser download sizes of 170 MB on macOS, 282 MB on Linux, and 280 MB on Windows; these are installation sizes, not per-download runtime costs. If you need system-managed Chrome or Chromium, Puppeteer documents executablePath and configuration options. Keep the browser version compatible with Puppeteer, and rerun the browser installation command after changing browser download configuration. See the Puppeteer configuration guide and installation guide.
7. Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| No file appears | Behavior was not set, the path is missing, or setup ran after the click. | Set allow and an absolute path before triggering the download. Confirm the action actually returned a file response. |
| “Download path is required” | allow or allowAndName was selected without downloadPath. |
Pass a path explicitly; this is required by CDP and Puppeteer for these policies. |
| Permission denied or file not writable | The Chrome process cannot write to the chosen directory, common in containers or restricted CI users. | Create a per-job directory under a location writable by the same user that launches Chrome; check ownership and mount permissions. |
| Browser exits before the file is complete | The script treats the click or navigation as completion. | Wait on a download completion event or poll for the finished file, then validate it before closing the browser. |
| Only a partial file is found | The transfer is still in progress, or the server stalled. | Ignore temporary partial extensions, wait until completion, set a deadline, and inspect network/server behavior if it expires. |
| Unexpected filename | The server supplied a Content-Disposition filename or Chrome used GUID naming. |
Enumerate the run’s directory after completion or use allowAndName consistently and map the resulting identifier. |
| Selenium cannot resolve a DevTools class | The generated binding does not match the Chrome major version or dependency. | Use the matching Selenium DevTools module and check its versioned API. Do not copy an import from a different vNN. |
| Works locally but fails in CI | Different Chrome binary/version, user permissions, container filesystem, or missing browser installation. | Log the executable/version, verify Puppeteer installation or configured executablePath, and test writes as the browser’s OS user. |
| HTML page saved instead of a document | The download endpoint redirected to a login, error, or bot-check page. | Check authentication state, cookies, redirects, response status, and content type. Validate the downloaded content instead of trusting the extension. |
8. Performance, reliability, and cost
Browser startup and page rendering usually dominate a simple file transfer in automation, while browser installation is a separate setup cost. Reuse a browser for multiple jobs only when contexts and download directories are isolated and cleanup is reliable; otherwise one browser per job provides clearer failure boundaries at the price of repeated startup. Keep download directories local to the worker when possible, and copy completed artifacts to durable storage after validation.
Set both a download deadline and an overall job deadline. Large files need a longer transfer allowance; small files should not leave a worker waiting indefinitely. A stable-size check is inexpensive but can mistake a slow pause for completion, so prefer protocol completion events when available and validate content for important outputs. Retries should be limited to failures that may recover, such as transient network errors; avoid blindly repeating non-idempotent actions that generate or charge for a new report.
Chrome automation has infrastructure costs: CPU and memory for browser processes, disk space for binaries and downloaded files, and maintenance for compatible browser and driver versions. Puppeteer’s documented browser package sizes are useful for planning CI cache and image size, but do not imply a per-capture charge. Monitor directory growth and remove temporary files after the job completes.
Or skip the browser setup
If the job is to capture a web page as an image or PDF rather than download a file from the site, ScreenshotNeo provides a one-request screenshot API and an MCP server. It returns a PNG, JPEG, WebP, or PDF from a URL. See the API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Cookie banners, popups, and chat widgets are removed before the shot. Bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents use screenshot, page-info, and PDF tools. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for free and get 1,000 screenshots a month with no card.
Frequently asked questions
Can headless Chrome download without opening a save dialog?
Yes. Set the allow policy and destination path through CDP or the automation library before initiating the download.
Should I use allow or allowAndName?
Use allow when the server-provided filename is useful. Choose allowAndName when GUID-based naming better suits your collision handling or bookkeeping.
Does this work for a download started by navigation?
Yes, if the navigation triggers a file response and the policy is already configured. Wait for completion even if the page navigation promise resolves or rejects.
Can I use a relative download path?
Prefer an absolute path. It removes ambiguity about the browser process’s working directory and makes CI behavior easier to diagnose.
Is this the same as taking a screenshot?
No. Chrome’s download behavior saves files returned by a site. A screenshot API captures a rendered page as an image or PDF.


