Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Fix Blank Screenshots in Playwright Headless Chromium

· 6 min read · Home Tech

In this article
  1. Why Headless Screenshots Come Out Blank
  2. Setting a Viewport and Device Scale Factor
  3. Waiting for the Page to Be Ready
  4. Handling Lazy-Loaded Images and Content
  5. Using the Old Headless Mode vs. New Headless Mode
  6. Common Pitfalls and Troubleshooting Steps
  7. Frequently Asked Questions

To fix blank screenshots in Playwright with headless Chromium, ensure the page has fully rendered before capturing and set an explicit viewport size, as headless browsers often capture before layout or with a default 800x600 viewport. The most common causes are missing waits, animations still running, or the new headless mode's default behavior, all of which are addressed below with concrete code fixes.

Why Headless Screenshots Come Out Blank

Playwright's headless Chromium runs a real browser engine, but it differs from headed mode in several ways that affect screenshots. The primary reason for a blank image is timing: the screenshot is taken before the page's JavaScript has finished loading dynamic content, fonts, or images. Another frequent cause is an unset or incorrectly sized viewport, which can result in a screenshot of an empty or partially rendered page. Additionally, the newer headless mode (introduced in Chromium 112) behaves more like headed mode but still has subtle differences in rendering and resource loading that can lead to blank captures if not handled explicitly.

Setting a Viewport and Device Scale Factor

By default, Playwright's headless Chromium uses a viewport of 1280x720 pixels. However, if you create a browser context without specifying a viewport, or if the page sets its own viewport via meta tags, the screenshot may capture an unintended area. Always set a viewport explicitly to match the target device or your testing needs.

const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
  viewport: { width: 1920, height: 1080 },
  deviceScaleFactor: 2, // for high-DPI screenshots
});
const page = await context.newPage();
await page.goto('https://example.com');
await page.screenshot({ path: 'screenshot.png' });

If you need a full-page screenshot, use fullPage: true in the screenshot options. This captures the entire scrollable area, which is often blank if the viewport is too small to trigger lazy-loading of below-the-fold content.

Waiting for the Page to Be Ready

The most reliable way to avoid blank screenshots is to wait for the network to be idle and for the page to reach a stable state. Playwright provides several waiting mechanisms:

  • page.waitForLoadState('networkidle') – waits until there are no network connections for at least 500ms.
  • page.waitForSelector(selector) – waits for a specific element to appear, which is useful for SPAs.
  • page.waitForTimeout(ms) – a fixed delay, but avoid this as it's flaky and slows down tests.

A common pattern is to combine these:

await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.waitForSelector('#main-content'); // ensure the main content is rendered
await page.screenshot({ path: 'screenshot.png' });

For pages with animations or transitions, you may need to wait for them to finish. You can use page.waitForFunction() to check that an animation has completed, or simply wait for a selector that appears after the animation ends.

Handling Lazy-Loaded Images and Content

Many modern websites lazy-load images and content as the user scrolls. In headless mode, the viewport is static, so below-the-fold content may not load until you scroll. To capture a full-page screenshot with all content loaded, you can manually scroll through the page before taking the screenshot:

await page.goto('https://example.com', { waitUntil: 'networkidle' });
// Scroll to the bottom to trigger lazy loading
await page.evaluate(async () => {
  await new Promise((resolve) => {
    let totalHeight = 0;
    const distance = 100;
    const timer = setInterval(() => {
      const scrollHeight = document.body.scrollHeight;
      window.scrollBy(0, distance);
      totalHeight += distance;
      if (totalHeight >= scrollHeight) {
        clearInterval(timer);
        resolve();
      }
    }, 100);
  });
});
// Wait a bit for images to load after scrolling
await page.waitForTimeout(500);
await page.screenshot({ path: 'fullpage.png', fullPage: true });

Alternatively, you can use Playwright's built-in page.screenshot() with fullPage: true and it will automatically scroll and capture the full page, but it may not trigger lazy-loading unless you scroll first. The above approach ensures all content is loaded.

Using the Old Headless Mode vs. New Headless Mode

Playwright uses the new headless mode by default in recent versions (Chromium 112+). The new headless mode is more similar to headed mode, but it still has some differences. If you encounter blank screenshots that you suspect are due to the headless mode, you can try launching with the old headless mode using the channel option or by setting the headless flag to true and adding args: ['--headless=old'] (though this is deprecated). In practice, the new headless mode works well, but if you have legacy code or specific rendering issues, you can fall back to the old mode:

const browser = await chromium.launch({
  headless: true,
  args: ['--headless=old'], // use old headless mode if needed
});

However, note that the old headless mode is deprecated and will be removed in future Chromium versions. It's better to fix the underlying waiting issues than to rely on an older mode.

Common Pitfalls and Troubleshooting Steps

If you still get blank screenshots after trying the above, check these common issues:

  • Cookies and storage: If the page requires login or shows a cookie consent banner, the screenshot might be blank because the banner covers the content. Handle cookies or dismiss the banner before taking the screenshot.
  • Web fonts: Fonts loading after the screenshot can cause text to be invisible. Wait for document.fonts.ready using page.evaluate().
  • Canvas and WebGL: Some headless environments lack GPU support, causing canvas elements to render blank. Launch the browser with args: ['--use-gl=swiftshader'] or --enable-unsafe-swiftshader to force software rendering.
  • Iframes: Content inside iframes may not be captured if the iframe hasn't loaded. Wait for the iframe's content using page.frames() and wait for selectors within the frame.
  • Multiple pages or popups: If your code interacts with multiple pages, ensure you're taking the screenshot of the correct page object.

A systematic approach is to take a screenshot immediately after goto() and then again after waiting, and compare the two to see if the content loads later. You can also use page.on('console') to log any JavaScript errors that might prevent rendering.

Frequently Asked Questions

Why is my screenshot blank even after waiting for networkidle?

networkidle only waits for network requests to finish; it doesn't guarantee that JavaScript has finished rendering the page. Single-page applications often make additional API calls after the initial load, or they render content asynchronously. Use waitForSelector to wait for a specific element that indicates the page is ready, or increase the timeout for networkidle if the page has long-polling requests.

Does the viewport size affect the screenshot content?

Yes, the viewport determines what part of the page is visible and can affect lazy-loading. If the viewport is small, content below the fold may not load, resulting in a blank area in a full-page screenshot. Set a larger viewport or scroll through the page before capturing.

Can animations cause blank screenshots?

Yes, if an animation or transition is in progress when the screenshot is taken, elements may be transparent or in the middle of moving. Wait for animations to finish using page.waitForFunction() that checks for the end of the animation, or simply wait a fixed time after the page load.

Is there a difference between headless and headed mode for screenshots?

In headed mode, the browser is visible and often has more time to render because the user sees it. Headless mode runs as fast as possible, so it may capture before the page is fully painted. Also, some features like hardware acceleration are disabled in headless, which can affect rendering of certain elements.

How do I take a screenshot of a specific element instead of the whole page?

Use the locator.screenshot() method on an element locator. For example: await page.locator('#header').screenshot({ path: 'header.png' });. This captures only that element, which can help avoid blank areas if the rest of the page is still loading.

What if the page uses dark mode or prefers-color-scheme?

Some pages render differently based on the color scheme. In headless mode, the default is light mode, but you can emulate dark mode using page.emulateMedia({ colorScheme: 'dark' }) before navigating. If the page has dark backgrounds and white text, a blank screenshot might actually be a black image with invisible text; check the pixel values to confirm.