Taking screenshots

Headless browsers are fully capable of taking screenshots, which is very useful in troubleshooting failures or faulty scripts. Using additional libraries and tools, it is also possible to automate visual comparisons.

# Generating and saving screenshots

The page.screenshot command is consistent across Puppeteer and Playwright, and allows us to save one or more screenshots of the current page to a specified path. Without any additional options, the size of the screenshot will depend on that of the viewport:

    # Full page screenshots

    Adding the fullPage: true option allows for the capture of full page screenshots, overriding the height parameter specified for our viewport:

    await page.screenshot({ path: 'my_screenshot.png', fullPage: true })

    # Clipped screenshots

    Having our screenshot limited to a smaller portion of the viewport is also possible. All we need to do is specify the coordinates of the top left corner of the screenshot, plus width and height. We then pass these options to:

      The above examples can be run as follows:

        # Use in visual regression testing

        Screenshots can be fed to image comparison libraries, such as Resemble.js (opens new window), pixelmatch (opens new window), Rembrandt.js (opens new window) or others in order to determine whether our latest sets of screenshots contains significant differences when measured against a baseline.

        Some libraries, like Differencify (opens new window) and jest-puppeteer-docker (opens new window), already combine Puppeteer with visual comparison libraries while exposing higher-level config to the user.

        # Further reading

        1. Official documentation for taking screenshots with Puppeteer (opens new window) and Playwright (opens new window)
        2. Blog post from baseweb.design on the whys and hows of visual regression testing (opens new window)
        3. Blog post from Gideon Pyzer looking at different visual regression testing tools (opens new window)