Playwright offers 2 type of screenshot functionalities: taking full-page screenshots and taking screenshots of specific DOM elements.
In this article, we'll discuss the latter: taking screenshots of individual DOM elements.
Why should one take screenshots of specific elements?
One use case to do this, is to compare specific parts of your website across various deploys.
For example: you could set up a CI/CD job that is triggered before each deploy to production, to check if your staging environment is still showing your CTA button correctly.
Together with some (basic) image-comparison tool, you could trigger an alert and halt the deploy if the CTA button is incorrectly rendered.
Taking a screenshot
Playwright makes it very easy, see the elementHandle.screenshot() documentation for more information and options.
const pw = require('playwright-core');
(async () => {
const browser = await pw.chromium.connect({
wsEndpoint: 'wss://chrome.headlesstesting.com/?token=[TOKEN]&browserVersion=dev',
})
const context = await browser.newContext()
const page = await context.newPage()
await page.setViewport({ 'width' : 1280, 'height' : 1024 })
await page.goto('https://headlesstesting.com/support', { waitUntil: 'domcontentloaded' })
const element = await page.$('#search-input')
await element.screenshot({ path: 'element.png' })
await browser.close()
})()
The example above will navigate to our documentation area and take a screenshot of the DOM element with ID=#search-input
- our search feature.
The screenshot will be saved in a file called element.png
There are various options you can supply to this function:
path
: where to save the screenshottype
:png
orjpeg
, default ispng
quality
: forjpeg
only, from 0 to 100omitBackground
: removes the default white background and allows capturing screenshots with transparency. Can only be used withpng