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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Configure downloads before the action that starts them, and register popup or file-chooser listeners before clicking the control that opens them. The reliable Puppeteer pattern is to start the event wait and the triggering action together with Promise.all(), then verify the resulting file or page with your own timeout.

What you need before writing the script

  • Node.js and a project with Puppeteer installed.
  • A writable, absolute directory for downloaded files.
  • Stable selectors for the download, popup, or upload control.
  • A timeout and completion check appropriate to the site and file size.

npm i puppeteer downloads a compatible Chrome browser. puppeteer-core does not download Chrome automatically, so you must provide a browser executable. If your package manager blocks install scripts, the official installation guidance documents npx puppeteer browsers install as a manual browser-install route. Check the API for the version installed in your project because event names, download defaults, and helper methods can change.

Download a file with Puppeteer

1. Create the directory and configure download behavior

Set the download policy and destination before navigation or before the click that triggers the response. Puppeteer’s DownloadBehavior has a policy and optional downloadPath; downloadPath is required when the policy is allow or allowAndName.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const puppeteer = require('puppeteer');
const fs = require('fs/promises');
const path = require('path');

const downloadDir = path.resolve(__dirname, 'downloads');

async function main() {
  await fs.mkdir(downloadDir, { recursive: true });

  const browser = await puppeteer.launch({ headless: true });
  const context = await browser.createBrowserContext({
    downloadBehavior: {
      policy: 'allow',
      downloadPath: downloadDir,
    },
  });

  const page = await context.newPage();
  try {
    await page.goto('https://example.com/reports', {
      waitUntil: 'domcontentloaded',
      timeout: 30_000,
    });
    await page.click('a.download');
    const file = await waitForCompletedDownload(downloadDir, 60_000);
    console.log(`Downloaded: ${file}`);
  } finally {
    await context.close();
    await browser.close();
  }
}

async function waitForCompletedDownload(dir, timeoutMs) {
  const started = Date.now();
  while (Date.now() - started < timeoutMs) {
    const names = await fs.readdir(dir);
    const candidates = names.filter(name =>
      !name.endsWith('.crdownload') && !name.endsWith('.tmp')
    );
    if (candidates.length) {
      const files = await Promise.all(candidates.map(async name => {
        const full = path.join(dir, name);
        const stat = await fs.stat(full);
        return { full, mtimeMs: stat.mtimeMs, size: stat.size };
      }));
      files.sort((a, b) => b.mtimeMs - a.mtimeMs);
      if (files[0].size > 0) return files[0].full;
    }
    await new Promise(resolve => setTimeout(resolve, 250));
  }
  throw new Error(`No completed download within ${timeoutMs} ms`);
}

main().catch(error => {
  console.error(error);
  process.exitCode = 1;
});

The policy permits the transfer; it does not prove that the transfer has finished. Chrome can expose a temporary .crdownload file while bytes are arriving, so production code should wait for a final filename and verify that it is non-empty (or validate a known checksum, size, or file format). For multiple downloads, record the directory contents before the click and accept only new files.

#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

2. Preserve authentication and browser state

A browser download is useful when the request depends on cookies, an authenticated session, a CSRF token, a generated report, or JavaScript that prepares the response. Keep the same page and browser context for login and download. If the site exposes a stable authenticated URL, a direct HTTP request can be faster, but then you must copy the required cookies or authorization headers and implement HTTP-level completion and error handling yourself.

3. Avoid races and ambiguous files

  • Create the directory before launching or creating the context.
  • Use a unique temporary directory for each job when parallel workers run.
  • Clear or snapshot old files so an earlier report is not mistaken for the new one.
  • Use a bounded timeout; never wait forever for a server that stalled.
  • Close the page, context, and browser in a cleanup path even after a failed download.

Wait for a popup or new tab

Page-scoped popup handling

Puppeteer documents the popup event as emitted when a page opens a new tab or window. The event gives you a new Page. Register the wait before clicking the opener, and start both promises together:

const [popup] = await Promise.all([
  page.waitForEvent('popup'),
  page.click('button.open-window'),
]);

await popup.waitForNavigation({
  waitUntil: 'domcontentloaded',
  timeout: 30_000,
}).catch(() => {});
console.log('Popup URL:', popup.url());
console.log(await popup.title());

// When finished:
await popup.close();

Use the equivalent event-wait API supported by your installed Puppeteer release. Some applications open a blank page first and navigate it later; in that case wait for the popup’s navigation or a selector that proves the expected document loaded. A popup opened by a different page will not be delivered to this page-scoped listener.

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

Browser-wide target detection

When the opener is unknown, or you need to observe every new page, listen at browser scope. BrowserEvent.TargetCreated fires when a target is created, including a page created by window.open.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
function waitForNewPage(browser, timeoutMs = 30_000) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      browser.off('targetcreated', onTarget);
      reject(new Error('No new page target appeared in time'));
    }, timeoutMs);

    const onTarget = async target => {
      if (target.type() !== 'page') return;
      clearTimeout(timer);
      browser.off('targetcreated', onTarget);
      resolve(await target.page());
    };
    browser.on('targetcreated', onTarget);
  });
}

const newPagePromise = waitForNewPage(browser);
await page.click('button.open-window');
const newPage = await newPagePromise;

Browser-wide listening has broader scope and therefore needs filtering and careful cleanup. Prefer the page event when you know which page owns the action.

Handle file chooser dialogs and uploads

Call waitForFileChooser() before the action that launches the chooser. It will not return a chooser that is already active, and it does not intercept every modern DOM picker API such as window.showOpenFilePicker.

const [chooser] = await Promise.all([
  page.waitForFileChooser(),
  page.click('button.choose-file'),
]);
await chooser.accept(['/absolute/path/report.csv']);

For an ordinary <input type="file">, setting the real input is usually simpler and avoids a native dialog:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const input = await page.$('input[type=file]');
await input.uploadFile('/absolute/path/report.csv');
await page.click('button.submit');

Do not confuse uploads and downloads. A download writes a browser response to disk; a chooser supplies a local path to an upload control. They require different waits and different verification.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Choosing the right event strategy

Approach Scope Best use Trade-off
Page popup event One opener page A known button or link opens one tab Precise, easy to filter and clean up
Browser targetcreated All targets in the browser Unknown opener or centralized monitoring Requires filtering and broader cleanup
Browser-managed download Authenticated browser session Cookies, JavaScript, generated files, or protected URLs Needs filesystem completion checks
Direct HTTP request One HTTP endpoint Stable URL and portable authentication You must reproduce browser state and HTTP error handling

Common failures and fixes

“The download went to the wrong folder”

Usually the policy was set after the click, the context was not the one containing the page, or the path was relative and resolved somewhere unexpected. Resolve an absolute path, create it first, and configure downloadBehavior when creating the browser context.

“The script hangs waiting for a popup”

The listener was registered after the click, the control did not open a new page, or a different page was the opener. Put the wait and click in one Promise.all(), confirm the selector’s behavior manually, and switch to browser-wide target detection when the opener is unknown.

“The popup exists but has no content”

The new page may have opened as about:blank and navigated asynchronously. Wait for navigation or a meaningful selector, and allow for sites that block popups or redirect through an intermediate URL.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

“The file is missing even though the click succeeded”

A successful click is not a completed transfer. Check for temporary download extensions, wait for a new final file, and increase the bounded timeout for large or slow responses. Also check that the server returned a download rather than an HTML error page.

Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

“The file chooser wait never resolves”

Register it before the click, and verify that the control actually invokes a supported file-input chooser. For a normal file input, use uploadFile(); for window.showOpenFilePicker, design a separate strategy because waitForFileChooser() does not intercept it.

“Chrome is not installed”

Use puppeteer if you want installation to download a compatible browser, or configure an executable path when using puppeteer-core. If install scripts were skipped, run npx puppeteer browsers install.

Reliability, performance, and security

  • Use waitUntil: 'domcontentloaded' when you only need the document and then wait for the exact selector required by the workflow.
  • Set navigation, popup, chooser, and download timeouts explicitly; make them long enough for the expected workload but always finite.
  • Use one isolated browser context per account or job to prevent cookies and downloaded files from crossing workflows.
  • Sanitize or isolate downloaded filenames before passing them to later tools. Do not execute downloaded content automatically.
  • Close popup pages promptly and close contexts in finally blocks to prevent memory and file-descriptor leaks.
  • Log the URL, event type, elapsed time, final path, and verification result, but avoid logging credentials or private file contents.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean image or PDF of a web page rather than an interactive download workflow, ScreenshotNeo provides a single screenshot API request. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

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

See the ScreenshotNeo API documentation for all options.

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}`);

ScreenshotNeo includes full-page and element captures, lazy-image loading, device and viewport controls, retina scale, PDF settings, custom CSS and JavaScript, clicks, selector waits, delays, network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs, which can simplify migration. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Frequently Asked Questions

Can Puppeteer detect a popup opened by JavaScript from an iframe?

Use browser-level target detection when the opener is not the top-level page, then filter the created target by type, URL, or opener relationship before obtaining its Page.

Should I wait for a network-idle event to declare a download complete?

No. Network idle describes page activity, not whether a file has been fully written. Verify the filesystem result or a known response-level condition instead.

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

Can I use a file chooser wait for a download button?

No. A file chooser supplies a local file for upload. Configure download behavior and monitor the destination directory for downloads.

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.