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
To save a PDF that a link opens in a new tab, capture the popup before clicking, listen to that page’s network responses, identify the response whose content type is application/pdf, read it with response.buffer(), and write those bytes with Node.js. Do not use page.pdf() for this task: that method renders the current page into a new PDF instead of downloading the document the site already served.
The reliable popup-download sequence
A new tab is represented by a Puppeteer Page. The originating page emits a popup event when the click opens a tab or window. Register that event handler before the click, attach a response listener as soon as the popup exists, then save the matching response body.
- Start the browser and open the page containing the PDF link.
- Register a
popuphandler before clicking. - In that handler, inspect every response from the new page.
- Match a PDF by the
Content-Typeheader, the URL suffix, or both. - Check the HTTP status and
ok()result. - Call
buffer()and write the binary buffer to disk. - Close the popup and browser only after the file write has completed.
Complete Node.js example
Install Puppeteer in your project with npm install puppeteer. Replace the page URL and selector with the site you are automating.
const puppeteer = require('puppeteer');
const fs = require('node:fs/promises');
function waitForPdfResponse(pdfPage, timeoutMs = 30000) {
return new Promise((resolve, reject) => {
let timer;
const finish = (error, response) => {
clearTimeout(timer);
pdfPage.off('response', onResponse);
if (error) reject(error);
else resolve(response);
};
const onResponse = response => {
const headers = response.headers();
const contentType = (headers['content-type'] || '').toLowerCase();
const url = response.url().toLowerCase();
if (contentType.includes('application/pdf') || url.endsWith('.pdf')) {
finish(null, response);
}
};
pdfPage.on('response', onResponse);
timer = setTimeout(() => {
finish(new Error('Timed out waiting for a PDF response'));
}, timeoutMs);
});
}
(async () => {
const browser = await puppeteer.launch({headless: true});
try {
const page = await browser.newPage();
await page.goto('https://example.com/account', {waitUntil: 'domcontentloaded'});
let popupPage;
let pdfResponsePromise;
page.once('popup', popup => {
popupPage = popup;
// Register immediately: the popup may begin navigating at once.
pdfResponsePromise = waitForPdfResponse(popup);
});
await page.click('a[data-download="invoice"]');
if (!pdfResponsePromise) {
throw new Error('The click did not open a popup');
}
const response = await pdfResponsePromise;
if (!response.ok()) {
throw new Error(`PDF request failed: HTTP ${response.status()}`);
}
const bytes = await response.buffer();
await fs.writeFile('invoice.pdf', bytes);
console.log(`Saved ${bytes.length} bytes from ${response.url()}`);
if (popupPage) await popupPage.close();
} finally {
await browser.close();
}
})();
The response listener is installed inside the popup event callback, rather than after an arbitrary delay. The code accepts either a PDF content type or a URL ending in .pdf; the header is the stricter signal when a URL is extensionless.
#1 Best Overall
- INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
- COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
- ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
- HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
Why the listener must be early
Many PDF viewers navigate immediately when their tab is created. If you click first and only then add a response listener, the document response can already be gone. Setting up the popup and response promises before page.click() removes that race.
Correlating the correct new tab
page.once('popup') scopes the event to the page that performed the click and is usually the simplest choice. It is less suitable when the application opens several tabs, creates a target from script, or uses a non-page target.
Browser-wide target handling
Use browser.on('targetcreated') when you need browser-wide visibility. Check the target type, opener, and URL before converting it to a page.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →const targetPromise = new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Timed out waiting for target')), 30000);
const onTarget = async target => {
if (target.type() !== 'page') return;
// target.opener() lets you verify which page caused this target.
if (target.opener() !== page) return;
clearTimeout(timer);
browser.off('targetcreated', onTarget);
resolve(target);
};
browser.on('targetcreated', onTarget);
});
await page.click('a[data-download="invoice"]');
const target = await targetPromise;
const pdfPage = await target.page();
if (!pdfPage) throw new Error('The target has no page');
const response = await waitForPdfResponse(pdfPage);
if (!response.ok()) throw new Error(`HTTP ${response.status()}`);
await fs.writeFile('invoice.pdf', await response.buffer());
Top-level targets have no opener, so target.opener() is a useful correlation check. Some Puppeteer releases expose target.asPage() for non-page targets; use it only when the target type supports that conversion.
Matching and validating the PDF response
Content-Type matching
Prefer application/pdf in the response headers. It distinguishes a PDF from an HTML login page served at a URL that happens to contain “download”. Header values can include parameters such as application/pdf; charset=binary, which is why the example uses includes().
URL matching
A URL ending in .pdf is a useful fallback when a server omits or mislabels the content type. It is less strict: a URL can end in .pdf while returning an error page. Combining URL and header checks, then validating the status, is safer than relying on the suffix alone.
Rank #2
- CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
- INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
- PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
- ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴
Status and body checks
response.ok() reports whether the status is successful, while status() gives the exact code for diagnostics. Save buffer(), not text(); converting binary PDF bytes to text can corrupt the file. If a site returns a successful HTML login page, inspect the headers and URL, then authenticate the browser context before clicking.
Existing PDF bytes versus a newly generated PDF
These are different operations:
| Goal | Puppeteer operation | Result |
|---|---|---|
| Download the document opened by the site | Capture the popup response and call response.buffer() |
The original response bytes, subject to redirects and server-side processing |
| Print the current HTML page | page.pdf() |
A newly rendered PDF using print CSS and Puppeteer’s PDF options |
Use page.pdf({path: 'file.pdf'}) only when rendering is what you want—for example, producing a report from HTML. It does not download an existing PDF opened in a new tab.
Authentication, redirects, and download endpoints
Authenticated documents
Perform login in the same browser context before clicking. The popup normally inherits cookies from that context, but a site may require an authorization header, a signed URL, or a separate download request. If the captured response is a login page, confirm the popup URL, session cookies, and any required headers.
Redirects
A PDF link can redirect through a tracking or authorization URL. Match the final response by its headers and verify response.url() when logging. Do not assume the first response from the popup is the document; pages also request HTML, scripts, fonts, and images.
Download endpoint instead of PDF navigation
Some applications open a tab that runs JavaScript and then requests a PDF from an API endpoint. Keep the response listener on the popup so it can observe that later request. If the endpoint is requested by the opener rather than the popup, listen on the page that actually makes the request or use browser-wide request/response handling with an opener check.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Common failures and fixes
“The click did not open a popup”
The link may open in the same tab, be blocked by a missing user gesture, or be rendered only after another action. Confirm the selector, wait for it with page.waitForSelector(), and use a real page.click() rather than triggering navigation long after the click. If the site intentionally navigates the current page, capture responses on the original page instead.
Rank #3
- SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
- INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
- KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
- PREMIUM SUPPORT - Strong technical expertise to solve issues faster
- THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.
Timeout waiting for a PDF
The popup may have loaded an HTML viewer, the selector may be wrong, or the server may be slow. Log every popup response URL and content type temporarily, increase the timeout for the known environment, and verify that a PDF request actually occurs.
Only an HTML login page was saved
A successful HTTP status does not guarantee a PDF. Check content-type, preserve the response URL, and complete authentication before opening the tab. Reuse the same browser context and cookies.
“Target has no page”
You captured a worker, iframe, or another non-page target. Filter with target.type() === 'page'; for supported non-page targets, use the Puppeteer conversion method available in your pinned release.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →The saved file is corrupt
Write the result of await response.buffer() directly with fs.writeFile. Do not call response.text(), JSON-encode the bytes, or close the browser before the write promise resolves.
The response listener misses the document
Move listener registration into the popup/target-created handler and establish that handler before page.click(). Avoid fixed sleeps as a synchronization mechanism.
Operational tips for repeatable jobs
- Pin the Puppeteer version used by your project and verify API behavior when upgrading.
- Use a per-download filename and write to a temporary path before renaming if another process consumes the file.
- Record the response URL, status, content type, and byte count for troubleshooting.
- Always close popup pages and the browser in a
finallyblock. - Set an explicit timeout so a failed site cannot leave a worker waiting indefinitely.
- When several downloads can run concurrently, create one promise and one output path per click, and correlate each target with
target.opener().
Or skip the browser setup
If you only need a clean PDF or screenshot of a URL, ScreenshotNeo provides a single HTTP request instead of maintaining Puppeteer popup code. Its capture pipeline accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks, CAPTCHAs, 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. It also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
See the parameter reference in the ScreenshotNeo documentation. The same endpoint can return PNG, JPEG, WebP, or PDF; use the documented PDF option for your request.
Rank #4
- Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
- No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
- Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
- Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
- The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o document.pdf
ScreenshotNeo includes full-page capture, lazy-image loading, CSS-selector element capture, device and viewport controls, retina scale, PDF paper size, margins, landscape mode and page ranges, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, easing migrations.
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to try it.
FAQ
Can I use page.waitForEvent('popup') instead?
Use the popup event API available in your pinned Puppeteer release. The essential requirement is unchanged: subscribe before clicking and attach response handling immediately.
Should I wait for networkidle before saving?
Not necessarily. Save when the matching PDF response arrives. Network-idle waits can be unreliable on pages with analytics, streaming, or long-lived connections.
Why does the browser viewer show a PDF but no response matches?
The viewer may be embedded in an iframe or the PDF request may be made by another page. Log target creation and response URLs, then move the listener to the target that performs the request.
Frequently Asked Questions
Can I download a PDF opened by a new tab without saving a screenshot?
Yes. Capture the popup’s network response and write its binary buffer; screenshot APIs and page.pdf() are separate workflows.
What should I do when a PDF requires a signed URL?
Complete the site’s authentication flow first and capture the final response after redirects; a signed or authorization-bearing URL may expire if reused later.
Quick Recap
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.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errors

