Viewport issue with page.screenshot in Puppeteer

I am relatively new to Puppeteer, so bear with me if it’s a beginner’s mistake.

Puppeteer versions tested: 6.0.0 / 9.0.0 / 10.0.0

When I take a screenshot using Puppeteer in headless: false mode, the viewport shrinks for a moment (seems to become almost half the size) right when the screenshot is being captured, then goes back to full size until the next screenshot.

Here is the relevant code snippet:

const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({
    args: ['--disable-features=site-per-process'],
    ignoreDefaultArgs: ['--hide-scrollbars'],
    headless: false
});

await page.setViewport({
    width: 1200,
    height: 800,
    deviceScaleFactor: 1
});

await page.screenshot({
    encoding: 'base64',
    captureBeyondViewport: false
});

I’ve read that setting captureBeyondViewport: false should fix this issue, but the flickering persists across all versions I’ve tried. Am I missing something here?

The flickering could be due to the dynamic content or other resources that are still loading when you take the screenshot. One trick you can try is to ensure the page is fully loaded using page.evaluate() method before taking the screenshot.

Try this snippet just before your page.screenshot() call:

await page.evaluate(() => {
  return new Promise((resolve) => {
    if (document.readyState !== 'complete') {
      window.addEventListener('load', resolve);
    } else {
      resolve();
    }
  });
});

This ensures everything is loaded properly. Also, check for any CSS animations that might be running and causing the viewport to resize unexpectedly.

It’s interesting that headless: false mode is giving you this flickering issue during screenshots. One possible solution to explore is incorporating a slight delay before taking the screenshot, which could stabilize the viewport. You can try adding await page.waitForTimeout(1000); immediately before the page.screenshot() call to see if it alleviates the flickering. Another approach might involve testing with fullPage: true, which some users have found reduces visual anomalies. Experimenting with these suggestions could help you troubleshoot the flickering problem effectively.

this happens to me when some CSS is loaded dynamically. try using a delay like 500ms before taking the screenshot. it might stabilize the viewport.