Puppeteer Screenshot: Full Page, Element, and Every Option
How to take screenshots with Puppeteer in Node.js: viewport and device scale, full-page and element captures, clipping, PNG vs JPEG vs WebP and quality, buffers and base64, lazy-loaded images, cookie banners, waiting strategies and batch capture. Tested on Puppeteer 25.19 with Chrome 158.
Last updated
Short answer
Launch Chrome with puppeteer.launch(), set a viewport with page.setViewport({ width: 1440, height: 900 }) (the default is 800×600), open the page with page.goto(), then call page.screenshot({ path: 'page.png' }). Add fullPage: true for the whole page, call screenshot() on an element handle for one element, and use type: 'jpeg' with quality for smaller files.
page.screenshot() is one call, but production screenshots fail in predictable ways: the wrong size, a spinner instead of content, blank gaps where lazy images should be, a cookie banner over the hero, or a process that runs out of memory on a long page. This guide covers each option and each failure, with code we ran against Puppeteer 25.19.0 and Chrome 158 in November 2026.
Take a screenshot with Puppeteer in Node.js
Install with npm install puppeteer (Node.js 22.12 or newer; Puppeteer 25 is ESM-only), which also downloads a matching Chrome. Then:
import puppeteer from "puppeteer";
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.setViewport({ width: 1440, height: 900 }); // the default is 800 x 600
await page.goto("https://example.com", { waitUntil: "networkidle2" });
await page.screenshot({ path: "example.png" });
} finally {
await browser.close();
}Always close the browser in finally; otherwise a failed navigation leaves Chrome running. Use networkidle2 (no more than two network connections for 500 ms) rather than networkidle0 for arbitrary websites: analytics and chat widgets often keep one connection open, so a page may never reach zero.
Viewport and deviceScaleFactor
Puppeteer opens pages at 800×600 unless told otherwise, which is why so many first screenshots look like a cramped tablet layout. setViewport sets the CSS size; deviceScaleFactor multiplies the pixels. A 1280×800 viewport at deviceScaleFactor: 2 produced a 2560×1600 image in our test:
import puppeteer, { KnownDevices } from "puppeteer";
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Retina-quality: 1440 x 900 CSS pixels becomes a 2880 x 1800 image
await page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 2 });
// Or emulate a device: viewport, scale factor, touch, mobile flag and user agent
await page.emulate(KnownDevices["iPhone 15 Pro"]); // 393 x 659 at 3x- Set the viewport before `goto()`, so the page loads its layout, breakpoints and
srcsetimage sizes for that width from the start. - `deviceScaleFactor: 2` quadruples memory. Both dimensions double, so a capture holds four times the pixels. Use it for crisp marketing images, not bulk thumbnails.
- Default for every page: pass
defaultViewport: { width: 1440, height: 900 }topuppeteer.launch()instead of callingsetViewporteach time. - Devices:
KnownDevicesships presets with the right viewport, scale factor, touch support and user agent.isMobile: truein a manual viewport also makes the page honor<meta name=viewport>.
Puppeteer screenshot full page
// The whole scrollable page, top to bottom
await page.screenshot({ path: "full.png", fullPage: true });
// Alternative: resize the viewport to the page height first. Lazy images load,
// but anything sized in vh (hero sections, full-screen modals) grows with it.
await page.screenshot({ path: "full.png", fullPage: true, captureBeyondViewport: false });
// Very long pages: capture only the top 8,000 CSS pixels
await page.screenshot({ path: "top.png", clip: { x: 0, y: 0, width: 1440, height: 8000 } });By default fullPage: true captures beyond the viewport without resizing it (captureBeyondViewport defaults to true). That keeps 100vh sections their normal height, but the browser still thinks only the first 900 pixels are on screen. Setting captureBeyondViewport: false makes Puppeteer resize the viewport to the full scroll height before capturing, which wakes up lazy loaders but stretches anything sized in vh.
- Long pages are expensive. A 1,440×20,000 capture is about 115 MB of raw pixels before PNG encoding, and about 461 MB at
deviceScaleFactor: 2. Cap the height with aclip, as above, for pages that scroll forever. - Infinite scroll has no bottom. Full-page capture takes the height at that moment. Scroll a fixed distance (the helper below caps at 20,000 px) rather than waiting for the end.
- Sticky headers and chat bubbles sit on top of content. Hide them with CSS before capturing (see cookie banners below).
Lazy-loaded images: scroll before you capture
This is the most common full-page complaint, and it's real: in our test, a default fullPage: true capture loaded neither a native loading="lazy" image nor an IntersectionObserver-driven image below the fold. Both appear as empty boxes. Scrolling through the page first fixes both:
async function autoScroll(page, maxScroll = 20_000) {
await page.evaluate(async (maxScroll) => {
const step = Math.floor(window.innerHeight * 0.8);
for (let y = 0; y < Math.min(document.documentElement.scrollHeight, maxScroll); y += step) {
window.scrollTo(0, y);
await new Promise((resolve) => setTimeout(resolve, 150));
}
window.scrollTo(0, 0);
}, maxScroll);
}
await page.goto(url, { waitUntil: "networkidle2" });
await autoScroll(page); // trigger lazy loaders on the way down
await page.waitForNetworkIdle({ idleTime: 500 }); // let the images finish downloading
await page.screenshot({ path: "full.png", fullPage: true });The scroll pause (150 ms) gives observers time to fire; waitForNetworkIdle then waits until no requests have started for half a second. Scrolling back to the top before capturing keeps sticky headers in their normal place. If you control the page, adding loading="eager" to images is simpler still.
Puppeteer screenshot of a specific element
Call screenshot() on an element handle. Puppeteer scrolls the element into view, measures its bounding box, and captures exactly that rectangle:
// Wait until the element is in the DOM and visible, then capture just that element
const chart = await page.waitForSelector("#revenue-chart", { visible: true });
await chart.screenshot({ path: "chart.png" });
// With breathing room: clip is relative to the element's top-left corner
const box = await chart.boundingBox();
const pad = 16;
await chart.screenshot({
path: "chart-padded.png",
clip: { x: -pad, y: -pad, width: box.width + pad * 2, height: box.height + pad * 2 },
});- Wait with `{ visible: true }`. An element that exists but has
display: nonethrowsNode is either not visible or not an HTMLElement; an empty container that hasn't been filled yet throwsNode has 0 width. - Elements taller than the viewport work, because element captures go beyond the viewport too.
- `clip` on an element is relative to the element, which makes padding easy (we got a 332×232 image for a 300×200 element with 16 px padding). On
page.screenshot(),clipis relative to the document. - Several elements: loop over
page.$$(selector)and callscreenshot()on each handle; each capture scrolls its element into view first.
Clip a region of the page
// A fixed region, in CSS pixels from the top-left of the document
await page.screenshot({
path: "region.png",
clip: { x: 0, y: 0, width: 1200, height: 630 }, // e.g. an Open Graph image
});Coordinates and sizes are CSS pixels, so the output is multiplied by deviceScaleFactor: a 400×300 clip at 2x came out as 800×600. clip and fullPage can't be combined; Puppeteer throws 'clip' and 'fullPage' are mutually exclusive. An optional scale inside clip scales just that capture.
Puppeteer screenshot options and quality
| Option | Default | What it does |
|---|---|---|
path | none | Save to this file; the extension sets the type when type isn't given. |
type | png | png, jpeg or webp. |
quality | none | 0–100 for jpeg and webp. Passing it for PNG throws. |
fullPage | false | Capture the full scrollable page. |
clip | none | { x, y, width, height, scale? } region in CSS pixels. |
omitBackground | false | Drop the default white background, for transparent PNG or WebP. |
encoding | binary | base64 returns a string instead of a Uint8Array. |
captureBeyondViewport | true | Capture outside the viewport without resizing it; false resizes the viewport for full-page captures. |
fromSurface | true | Capture from the compositor surface rather than the view. |
optimizeForSpeed | false | Trade encoding effort for speed. |
PNG, JPEG or WebP?
- PNG: lossless, sharp text and UI edges, supports transparency. Largest files, especially for photos.
- JPEG: much smaller for photographic pages; quality 75–85 is a sensible range. No transparency, and text edges can show artifacts at low quality.
- WebP: usually smaller than JPEG at similar quality, and supports transparency. Check that whatever consumes the image accepts WebP.
// JPEG and WebP take a quality from 0 to 100; PNG doesn't (it throws)
await page.screenshot({ path: "page.jpg", quality: 80 }); // type inferred from .jpg
await page.screenshot({ path: "page.webp", type: "webp", quality: 75 });
// Transparent background: the page itself must not paint one
await page.setContent('<div style="font: 700 64px system-ui; color: #0f172a">Acme</div>');
await page.screenshot({ path: "logo.png", omitBackground: true });omitBackground only removes Chrome's default white canvas. If the page sets body { background: #fff }, the screenshot is still opaque, so for logos and badges render your own HTML with no background, as above.
Screenshot to buffer, base64, or file
// 1. A file: the image type follows the extension (.png, .jpg/.jpeg, .webp)
await page.screenshot({ path: "page.png" });
// 2. In memory: screenshot() resolves to a Uint8Array
const bytes = await page.screenshot({ type: "webp", quality: 80 });
const buffer = Buffer.from(bytes); // for APIs that insist on a Node Buffer
// 3. A base64 string, e.g. for a data: URL or a JSON response
const base64 = await page.screenshot({ encoding: "base64" });
const dataUrl = `data:image/png;base64,${base64}`;In current Puppeteer, screenshot() resolves to a Uint8Array, not a Node Buffer. Most APIs accept it: fs.writeFile, fetch bodies, the AWS SDK. Some older code checks Buffer.isBuffer(), and Express 4's res.send() turns a Uint8Array into JSON, so wrap it in Buffer.from() before sending. Base64 adds about a third to the size, so use it only when you need text, such as a data URL or JSON.
Waiting strategies: when to press the shutter
Screenshots taken too early show spinners, skeleton loaders or fallback fonts. Combine a navigation wait with a wait for the thing you actually care about:
// Before navigating: freeze animations that respect reduced-motion
await page.emulateMediaFeatures([{ name: "prefers-reduced-motion", value: "reduce" }]);
await page.goto(url, { waitUntil: "networkidle2" }); // at most 2 connections for 500 ms
await page.waitForSelector(".hero img", { visible: true }); // the part you care about is there
await page.evaluate(async () => { await document.fonts.ready; }); // web fonts have swapped in
await page.screenshot({ path: "page.png" });| Wait | Use it when | Watch out for |
|---|---|---|
waitUntil: "load" | Static pages, your own HTML | Content fetched by JavaScript after load |
waitUntil: "networkidle2" | Most websites | Long-polling pages can still be busy |
waitUntil: "networkidle0" | Your own app, fully under control | Times out on pages with persistent connections |
page.waitForSelector(sel, { visible: true }) | You know what "ready" looks like | Selectors that change between deploys |
page.waitForFunction(fn) | Your app sets a flag when rendering finishes | Needs code in the page |
document.fonts.ready | Web fonts must be in the shot | Only covers fonts already requested |
| A fixed delay | Last resort for animations | Slow, and still flaky under load |
Cookie banners, ads and popups
Consent banners are the other big source of bad screenshots, especially when your server is in the EU. Three approaches, in order of reliability for sites you don't control:
// 1. Accept the banner if it appears (OneTrust's button id), without waiting long
await page.locator("#onetrust-accept-btn-handler").setTimeout(3000).click().catch(() => {});
// 2. Or hide consent banners and widgets with CSS before capturing
await page.addStyleTag({
content: "#onetrust-consent-sdk, #CybotCookiebotDialog, .chat-widget { display: none !important; }",
});
// 3. Block ad and analytics hosts before navigating
const BLOCKED = ["doubleclick.net", "googlesyndication.com", "google-analytics.com"];
await page.setRequestInterception(true);
page.on("request", (request) => {
if (request.isInterceptResolutionHandled()) return;
const { hostname } = new URL(request.url());
if (BLOCKED.some((host) => hostname === host || hostname.endsWith("." + host))) {
return request.abort();
}
request.continue();
});- Clicking accept gives the most natural page, because the site removes its own overlay and any scroll lock. The short
setTimeoutplus.catch()makes it a no-op when no banner appears; without the timeout, the click waits 30 seconds for a button that never comes. - Hiding with CSS works when you know the consent platform. OneTrust and Cookiebot use the ids above; build up a list for the sites you capture. Some banners also set
overflow: hiddenonbody, so you may need to reset that. - Blocking hosts with request interception speeds pages up and removes ad slots. Once interception is on, every request waits for your handler to continue or abort it, and blocking a script the site depends on can break the page.
Taking many screenshots: batch capture
For a list of URLs, reuse one browser, give each URL its own context, and cap how many pages run at once. This worker-pool version keeps four captures in flight and keeps going when one URL fails:
import puppeteer from "puppeteer";
import { writeFile } from "node:fs/promises";
const urls = ["https://example.com", "https://example.org", "https://example.net"];
const CONCURRENCY = 4; // pages in flight; measure memory before raising it
const browser = await puppeteer.launch();
try {
let next = 0;
async function worker() {
while (next < urls.length) {
const i = next++;
const context = await browser.createBrowserContext(); // isolated cookies per URL
try {
const page = await context.newPage();
await page.setViewport({ width: 1280, height: 800 });
await page.goto(urls[i], { waitUntil: "networkidle2", timeout: 30_000 });
await writeFile(`shot-${i}.png`, await page.screenshot());
} catch (err) {
console.error(urls[i], err.message); // one bad URL doesn't stop the batch
} finally {
await context.close();
}
}
}
await Promise.all(Array.from({ length: CONCURRENCY }, worker));
} finally {
await browser.close();
}Memory scales with pages in flight and with pixels per capture, so the right concurrency depends on your URLs. Measure peak memory for the whole process tree, Node plus every Chrome child, at two, four and eight; why Puppeteer eats your RAM walks through it. For containers, fonts (emoji and CJK glyphs show as boxes in a bare image) and sandbox flags, see headless Chrome in Docker.
Common Puppeteer screenshot problems
| Problem | Cause | Fix |
|---|---|---|
| Image is 800×600 and looks cramped | The default viewport | page.setViewport() or defaultViewport at launch |
png screenshots do not support 'quality'. | quality without type: 'jpeg' or 'webp' | Set the type, or drop quality |
'clip' and 'fullPage' are mutually exclusive | Both options passed | Use one; cap long pages with clip alone |
Node is either not visible or not an HTMLElement | The element is hidden or not rendered yet | waitForSelector(sel, { visible: true }) |
Node has 0 width. | An empty container captured before content arrived | Wait for the content inside it |
| Spinner, skeleton or blank area | Captured before data loaded | Wait for a selector or a ready flag |
| Blank boxes lower down a full-page shot | Lazy-loaded images never triggered | Scroll first with the helper above |
| Boxes instead of emoji or Chinese text | Fonts missing in the container | Install fonts-noto-color-emoji and fonts-noto-cjk |
Navigation timeout of 30000 ms exceeded | networkidle0 never reached | networkidle2 or load plus waitForSelector |
| Process killed on long pages | Huge full-page captures at high scale | Cap height with clip, lower deviceScaleFactor, reduce concurrency |
Puppeteer screenshot API alternative: RenderKit
If screenshots are a feature rather than your product, the browser fleet behind them (Chrome versions, fonts, banner rules, memory limits, retries) is a lot to own. A screenshot API takes the same options as JSON. RenderKit is ours, so weigh this accordingly. Here's a full-page, retina, banner-free capture:
// npm install renderkit-sdk
import { RenderKit } from "renderkit-sdk";
const rk = new RenderKit(process.env.RENDERKIT_API_KEY);
const shot = await rk.screenshot({
url: "https://example.com/pricing",
viewport_width: 1440, // default 1440 x 900
viewport_height: 900,
device_scale: 2,
full_page: true,
format: "webp",
quality: 80,
block_ads: true,
block_cookie_banners: true,
hide_selectors: [".chat-widget"],
wait_for_selector: ".pricing-table",
});
console.log(shot.url, shot.credits_used); // hosted image on cdn.renderkit.tech, 1 credit
// One element instead of the page:
const chart = await rk.screenshot({ url: "https://example.com/report", selector: "#revenue-chart" });curl https://api.renderkit.tech/v1/screenshot \
-H "x-api-key: $RENDERKIT_API_KEY" \
-H "content-type: application/json" \
-d '{
"url": "https://example.com",
"full_page": true,
"format": "jpeg",
"quality": 80,
"block_cookie_banners": true
}'| Puppeteer | RenderKit /v1/screenshot | Note |
|---|---|---|
setViewport({ width, height }) | viewport_width, viewport_height | Default 1440×900 |
deviceScaleFactor | device_scale | 1 to 3 |
page.emulate(KnownDevices[...]) | mobile: true plus a viewport | Touch and a mobile user agent |
fullPage, clip, elementHandle.screenshot() | full_page, clip, selector | Same three capture modes |
type, quality, omitBackground | format, quality, omit_background | quality defaults to 80 |
addStyleTag to hide elements | hide_selectors, block_cookie_banners, block_chats | Banner hiding covers OneTrust, Cookiebot, Usercentrics and similar |
| Request interception | block_ads, block_resources | Built-in ad and tracker host list |
| Locator click before capture | click, scroll_to | One selector each |
waitUntil, waitForSelector() | wait_until, wait_for_selector, delay | wait_until defaults to networkidle |
| Resize afterwards with an image library | thumbnail_width | Proportional resize on the server |
- What you get: no Chrome to install or patch, fonts already in place, hosted image URLs, and identical requests served from cache at 0 credits. A screenshot costs 1 credit, and failed renders are refunded.
- Trade-offs: each capture is a network call; renders run from France (EU), so some sites show EU versions and consent banners (
country: "us"is available on Growth and up); results are public, unguessable URLs on cdn.renderkit.tech;dark_mode, cookies and custom headers need a paid plan. There's no SLA. - Price: a 14-day free trial with 500 credits (10 requests a minute, 1 concurrent render, 15-second timeout), then from $9/month for 5,000 credits. See pricing.
Keep Puppeteer when you need to log in through several steps, drive the page before capturing, or keep everything inside your own network.
Related
PDFs from the same browser: Puppeteer PDF. Other tools: Playwright screenshots, Selenium screenshots. Use cases: full-page screenshots, Open Graph images, thumbnails. API: Screenshot API and the screenshot reference.
Common questions
Call page.screenshot({ path: 'full.png', fullPage: true }) after the page has loaded. If images lower on the page are lazy-loaded, scroll through the page first (window.scrollTo in steps inside page.evaluate), wait for the network to go idle, then capture. Very long pages are memory-hungry, so cap the height with a clip if needed.
Get a handle with const el = await page.waitForSelector('#chart', { visible: true }), then call await el.screenshot({ path: 'chart.png' }). Puppeteer scrolls it into view and crops to its bounding box. To add padding, pass a clip relative to the element, e.g. { x: -16, y: -16, width: box.width + 32, height: box.height + 32 }.
Use JPEG or WebP and set quality from 0 to 100: page.screenshot({ type: 'jpeg', quality: 80 }). PNG is lossless and has no quality option; passing quality for a PNG throws. For sharper images, raise deviceScaleFactor in setViewport rather than quality.
Leave out path: const bytes = await page.screenshot() returns a Uint8Array, and Buffer.from(bytes) gives a Node Buffer. For a string, pass encoding: 'base64' and build a data URL with data:image/png;base64, followed by the string.
They're lazy-loaded. A default fullPage capture doesn't scroll, so images that load when they come into view never request their files. Scroll through the page in steps with page.evaluate, call page.waitForNetworkIdle(), then take the screenshot. captureBeyondViewport: false also triggers them but stretches vh-sized sections.
Pass omitBackground: true with a PNG or WebP type. It removes Chrome's default white background, but only areas the page doesn't paint become transparent, so the page (or your own HTML) must not set a background color on html or body.
Set the viewport before navigating: page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 2 }). The default is 800x600. The image size is the viewport (or clip) multiplied by deviceScaleFactor. For a fixed output size, use clip; to resize after capture, use an image library.
Click the accept button if it appears, with a short timeout so it's a no-op otherwise: page.locator('#onetrust-accept-btn-handler').setTimeout(3000).click().catch(() => {}). Or hide known banner containers with page.addStyleTag and display: none !important. Screenshot APIs such as RenderKit offer this as a flag (block_cookie_banners).
Ship your first render in 60 seconds.
500 free credits to start. No card. Cancel by ignoring it.