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

To save a file that a web page downloads after a click, configure Chrome’s download behavior and a writable directory before activating the control. Listen for download events, wait for a terminal state, then verify the completed file on disk before closing the browser. The exact helper methods vary by Puppeteer and browser version, so the example below uses the Chrome DevTools Protocol (CDP), whose current Browser domain documents Browser.setDownloadBehavior, downloadWillBegin, and downloadProgress.

Choose the right download workflow

There are two different operations that are often called a “download.” A page may initiate an attachment download when you click a link or button, or you may already know a file URL and retrieve it directly from Node.js. Use browser automation when the click, JavaScript, cookies, login state, CSRF tokens, or other session details are required. Use a direct HTTP request when the URL and required authentication are already available; it is usually simpler to stream and validate.

Case What Puppeteer must do Verification
Browser-triggered attachment Open the page, preserve session state, allow downloads, click the control, and observe CDP events. Wait for downloadProgress with state: "completed", then check the file.
Known file URL Send an HTTP request from Node, optionally reusing cookies or authorization from the browser. Check status, content type, length or checksum, and write the response as a stream.
PDF opened in a viewer Determine whether the server returned an attachment or a document navigation. Do not assume a visible PDF viewer means a download occurred.

The Puppeteer Page API documents a headless-shell limitation for navigation to PDF documents. A valid HTTP error status may also be returned without goto() throwing, so inspect the response when navigating.

Install Puppeteer and confirm a browser is available

puppeteer installs the library and downloads a compatible Chrome during installation. puppeteer-core installs only the library and expects you to provide a browser executable. Modern package managers can block install scripts; the Puppeteer documentation provides npx puppeteer browsers install for a manual browser installation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
npm install puppeteer
# If installation scripts were skipped:
npx puppeteer browsers install

For a quick launch check:

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch({headless: true});
  console.log('browser started');
  await browser.close();
})();

If this fails, fix the browser installation or executable path before debugging downloads.

Complete example: click and save a browser download

This example creates a known directory, configures Chrome through a CDP session, subscribes to lifecycle events before clicking, applies a deadline, and checks the resulting file. Replace the URL and selector with the site you are automating.

const fs = require('node:fs/promises');
const path = require('node:path');
const puppeteer = require('puppeteer');

const targetUrl = 'https://example.com/account';
const downloadDir = path.resolve(__dirname, 'downloads');
const selector = 'a[data-download]';

(async () => {
  await fs.mkdir(downloadDir, {recursive: true});
  const browser = await puppeteer.launch({headless: true});
  try {
    const page = await browser.newPage();
    const cdp = await page.createCDPSession();
    await cdp.send('Browser.setDownloadBehavior', {
      behavior: 'allow',
      downloadPath: downloadDir
    });

    const downloads = new Map();
    let finished;
    const completion = new Promise((resolve, reject) => {
      finished = {resolve, reject};
    });

    cdp.on('Browser.downloadWillBegin', event => {
      downloads.set(event.guid, {
        filename: event.suggestedFilename,
        url: event.url
      });
    });
    cdp.on('Browser.downloadProgress', event => {
      if (event.state === 'completed') {
        finished.resolve({guid: event.guid, path: event.filePath});
      } else if (event.state === 'canceled') {
        finished.reject(new Error(`Download canceled (${event.guid})`));
      }
    });

    const response = await page.goto(targetUrl, {waitUntil: 'networkidle2'});
    if (response && !response.ok()) {
      throw new Error(`Page returned HTTP ${response.status()}`);
    }
    await page.waitForSelector(selector, {visible: true});

    // Start listeners before this action; fast downloads can otherwise be missed.
    await page.click(selector);
    const result = await Promise.race([
      completion,
      new Promise((_, reject) => setTimeout(() => reject(new Error('Download timed out')), 90000))
    ]);

    const record = downloads.get(result.guid);
    const filename = record?.filename || path.basename(result.path || '');
    const filePath = result.path || path.join(downloadDir, filename);
    const stat = await fs.stat(filePath);
    if (!stat.isFile() || stat.size === 0) {
      throw new Error(`Downloaded file is missing or empty: ${filePath}`);
    }
    console.log({filePath, bytes: stat.size, filename});
  } finally {
    await browser.close();
  }
})();

The CDP method’s documented behavior values include deny, allow, allowAndName, and default. A downloadPath is required for allow or allowAndName. Protocol event names and fields can change, so compare this code with the CDP reference matching your installed browser and Puppeteer release: Browser domain and Puppeteer’s Page API.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Why the order matters

  1. Create a directory that the running user can write.
  2. Set download behavior before the click or other page action.
  3. Register downloadWillBegin and downloadProgress before triggering the action.
  4. Wait for a terminal event, not merely the click promise or a fixed sleep.
  5. Verify existence and size, and apply a production deadline.
  6. Close the browser only after completion or a deliberate cancellation.

Direct retrieval when the URL is already known

If the page merely reveals a stable file URL, a Node request avoids browser download policy. You may need to copy authenticated cookies from Puppeteer into the request and include an authorization header. Check the HTTP status because goto() and many HTTP clients do not treat every error status as a thrown exception.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const fs = require('node:fs');
const {pipeline} = require('node:stream/promises');
const {Readable} = require('node:stream');

async function download(url, output) {
  const response = await fetch(url, {redirect: 'follow'});
  if (!response.ok || !response.body) {
    throw new Error(`Download failed: HTTP ${response.status}`);
  }
  await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(output));
}

download('https://example.com/file.pdf', './downloads/file.pdf').catch(console.error);

Prefer the browser route when the server checks browser state or the URL is short-lived. Prefer direct retrieval for large, known files when authentication can be represented safely and reproducibly.

PDFs, viewers, and attachment headers

A response with Content-Disposition: attachment normally invokes download handling. A response with Content-Type: application/pdf may instead navigate to a PDF viewer. Inspect the network response and server headers, then choose the appropriate route. Headless shell’s documented PDF-navigation restriction means a viewer-oriented test can fail even though an attachment workflow would work. See the Puppeteer installation and documentation for current browser-mode notes.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Troubleshooting checklist

No file appears

  • Confirm Browser.setDownloadBehavior ran before the click and that downloadPath is absolute and writable.
  • Verify the selector clicked the intended control and that the page did not require a login, consent action, or a second confirmation.
  • Subscribe to CDP events before triggering the action; a very fast download can otherwise be missed.

The script hangs

  • Add a deadline around the completion promise.
  • Handle both completed and canceled states.
  • Check whether the control opens a new tab or navigates instead of downloading.

Browser will not launch

  • Use puppeteer or install a browser manually with npx puppeteer browsers install.
  • With puppeteer-core, supply an executable path for an installed compatible browser.
  • Check permissions and sandbox requirements in your deployment environment.

A PDF test fails

Determine whether you are navigating to a PDF document in headless shell rather than receiving an attachment. Test the response headers and use direct retrieval or the browser download workflow accordingly.

The saved file is corrupt

Do not treat a completed event as proof of application-level validity. Check size, content type, a known signature such as PDF’s %PDF-, or an expected checksum when the publisher provides one. Also ensure your code did not close the browser while Chrome was still writing.

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

Performance, reliability, and security

  • Reuse one browser process for multiple pages, but isolate download directories per job when filenames could collide.
  • Use a unique job directory and retain the CDP GUID, suggested filename, URL, status, and byte count for diagnostics.
  • Set explicit navigation and download deadlines; clean up partial files after cancellation.
  • Do not trust a server-supplied filename blindly. Sanitize it and prevent path traversal before moving files.
  • Limit file size and validate type before handing the file to downstream parsers.
  • Preserve cookies and authorization only as long as necessary, and never log their values.

Or skip the browser setup

If your goal is a clean image or PDF of a web page rather than the site’s own attachment, ScreenshotNeo provides a single website-screenshot API call. It accepts consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. A one-call example:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

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)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Every plan includes its features. The Free plan provides 1,000 screenshots per month without a card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Further reading

For API details that are release-sensitive, consult the current Chrome DevTools Protocol Browser reference, the Puppeteer Page API, and the project’s installation guide. Match protocol fields to your installed browser rather than assuming every convenience method exists in every Puppeteer version.

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

Frequently Asked Questions

Can Puppeteer download a file without clicking?

Yes. If you have a valid file URL, retrieve it directly from Node.js; use Puppeteer’s browser download controls when the site requires a page action or session state.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Why does a click open a PDF instead of saving it?

The server may return an inline PDF for viewer navigation rather than an attachment. Inspect response headers and account for headless-shell’s documented PDF-navigation limitation.

Is a fixed sleep enough to detect completion?

No. Download duration varies. Use CDP download lifecycle events, a deadline, and a filesystem or content validation check.

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.

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