User Agents

Web browsers and everyday web tech, explained

Puppeteer Full Page Screenshots via Chrome DevTools

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Capturing a full-page screenshot with Puppeteer allows you to render an entire webpage from top to bottom as a single image, regardless of the viewport size. While Puppeteer provides a built-in fullPage: true option in its page.screenshot() method, leveraging the Chrome DevTools Protocol (CDP) offers more granular control over the rendering process, allowing you to force specific device metrics and override the page layout before the capture occurs. This is particularly useful for sites with sticky elements, lazy-loading content, or complex CSS that behaves differently when the viewport is expanded.

What You'll Need

  • Node.js installed on your system (LTS version recommended).
  • A project directory initialized with npm init -y.
  • The Puppeteer library installed via npm install puppeteer.
  • Basic familiarity with JavaScript asynchronous functions (async/await).

Step-by-Step

  1. Initialize Puppeteer: Start by requiring the puppeteer module and launching a headless browser instance. Using headless: "new" ensures you are using the most up-to-date rendering engine.
  2. Open a New Page: Create a new browser tab using browser.newPage(). This provides the page object needed to interact with the site and the CDP session.
  3. Navigate to the Target URL: Use page.goto(url, { waitUntil: 'networkidle0' }). The networkidle0 option is critical because it ensures the screenshot isn't taken while images or scripts are still loading.
  4. Establish a CDP Session: To access low-level browser commands, create a session using const client = await page.target().createCDPSession(). This client allows you to send commands directly to the Chrome DevTools Protocol.
  5. Override Device Metrics: Use the Emulation.setDeviceMetricsOverride command. This tells Chrome to treat the page as having a specific width and height, effectively forcing the layout to render the full height of the document. You must fetch the page's total height first using page.evaluate(() => document.body.scrollHeight).
  6. Execute the Override: Send the following command via the CDP client:
    await client.send('Emulation.setDeviceMetricsOverride', {
          width: 1920,
          height: pageHeight,
          deviceScaleFactor: 1,
          mobile: false
        });
  7. Capture the Screenshot: Now that the browser believes the viewport is the size of the entire page, call await page.screenshot({ path: 'fullpage.png' }). Since the viewport is already expanded via CDP, the resulting image will encompass the entire layout.
  8. Clean Up: Close the browser instance using await browser.close() to free up system memory.

Common Mistakes

  • Ignoring Lazy Loading: Many modern websites only load images as the user scrolls. If you take a screenshot immediately after goto, the bottom of the page will contain empty placeholders. You must implement a scroll-to-bottom script before capturing.
  • Wrong Wait Condition: Using domcontentloaded instead of networkidle0 often results in screenshots of partially rendered pages, especially those relying on heavy JavaScript frameworks.
  • Forgetting the Scale Factor: On Retina or High-DPI displays, the deviceScaleFactor can cause the screenshot to be double or triple the requested resolution, leading to unexpectedly massive file sizes.
  • Overlooking Sticky Headers: When forcing a full-page render, some position: fixed elements may repeat or overlap strangely. These may need to be hidden via page.addStyleTag before the capture.

Tips

  • Automate Scrolling: To handle lazy-loaded content, use a loop that scrolls the page down in increments of 500-1000 pixels, waiting a few milliseconds between each jump, before triggering the CDP override.
  • Optimize Image Format: If the page is extremely long, PNG files can become enormous. Consider using type: 'jpeg' with a quality setting of 80 to reduce file size without significant loss of detail.
  • Set a Consistent Viewport: Always set a standard width (e.g., 1920px) to ensure that the layout is consistent across different runs and environments.
  • Hide Scrollbars: Use page.addStyleTag({ content: 'body { overflow: hidden !important; }' }) to prevent the vertical scrollbar from appearing in the final image.

Troubleshooting

If the screenshot is cut off, the most common cause is an incorrect height calculation. Ensure you are measuring document.body.scrollHeight after all dynamic content has loaded. If the page uses a wrapper div for scrolling instead of the body, you may need to target that specific element's height.

If the image appears blurry, check your deviceScaleFactor. Setting it to 2 will provide a high-resolution "Retina" quality image, but will double the pixel dimensions of the output.

In cases where the CDP session fails to override the metrics, ensure you are not running Puppeteer in a restricted environment (like some very old Docker containers) that may limit the browser's ability to resize the window.

Frequently Asked Questions

Why use CDP instead of the built-in fullPage option?

The built-in option sometimes struggles with complex CSS layouts or specific JavaScript-driven heights. CDP allows you to explicitly define the browser's viewport metrics, providing more reliable results for non-standard pages.

How do I handle pages with infinite scroll?

You must write a custom JavaScript function using page.evaluate that scrolls to the bottom of the page repeatedly until the scrollHeight stops increasing, then proceed with the screenshot.

Can I capture specific elements instead of the whole page?

Yes, you can use elementHandle.screenshot() to capture only a specific DOM node. However, this will not use the CDP viewport override logic.

Does this work for mobile views?

Yes, by changing the width in setDeviceMetricsOverride to a mobile width (e.g., 375px) and setting mobile: true, you can capture full-page mobile renders.

Will this capture content behind a login?

Yes, as long as you use Puppeteer to perform the login steps (filling forms and clicking submit) or set the browser cookies before navigating to the page.