Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use the mask option with one or more Playwright locators when taking a visual screenshot. Playwright covers each matched element’s bounding box with an overlay (pink #FF00FF by default), so changing content does not create irrelevant screenshot diffs.
Mask a changing region with toHaveScreenshot()
For visual regression tests, pass a locator array to mask on expect(page).toHaveScreenshot() or expect(locator).toHaveScreenshot(). The assertion captures the rendered page, masks the selected boxes, and compares the result with the stored expectation.
import { test, expect } from '@playwright/test';
test('account page hides the volatile balance', async ({ page }) => {
await page.goto('https://example.test/account');
await expect(page).toHaveScreenshot('account.png', {
mask: [page.getByTestId('dynamic-account-value')],
});
});
Use a named screenshot, as in account.png, when you want a stable snapshot filename. You can also omit the name and let the test runner derive one from the test and project.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsChange the overlay color
Masked pixels are not transparent. Playwright paints the matched element’s bounding box with a solid overlay. The documented default is pink, #FF00FF. Set maskColor when another color makes review easier:
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
await expect(page).toHaveScreenshot('account-dark.png', {
mask: [page.getByTestId('dynamic-account-value')],
maskColor: '#202020',
});
Because the entire bounding box is covered, a locator that includes padding, a card, or neighboring content can hide more pixels than intended. Make the locator as narrow as the unstable region.
Choose the right screenshot scope
Masking works at both page and element scope. Select the scope that matches what the test is intended to protect.
| Scope | Example | Best fit | Trade-off |
|---|---|---|---|
| Whole page | expect(page).toHaveScreenshot(...) |
End-to-end visual regression of the complete rendered page | A broad mask can conceal unrelated changes if its locator is too large |
| Specific element | expect(card).toHaveScreenshot(...) |
Component or region-level regression | Changes outside the selected element are not covered |
| Standalone page capture | page.screenshot({ mask: [...] }) |
Saving an image without an expectation comparison | There is no baseline assertion unless you compare the file separately |
| Standalone locator capture | locator.screenshot({ mask: [...] }) |
Saving only one component or region | The output is limited to that locator |
For full-page captures, configure the page screenshot to cover the complete scrollable page when that is your intent. For locator captures, use the locator screenshot API rather than an ElementHandle screenshot; the API reference discourages the latter.
Element-level assertion
const profileCard = page.getByTestId('profile-card');
const changingName = profileCard.getByTestId('display-name');
await expect(profileCard).toHaveScreenshot('profile-card.png', {
mask: [changingName],
});
This protects the card’s layout while hiding only the value that changes between runs.
Build a locator that masks exactly what you mean
Playwright recommends locators because they describe the element in user-facing or test-facing terms and can be resolved at capture time. Built-in families include roles, text, labels, placeholders, alternative text, titles, and test IDs.
Prefer stable hooks for volatile data
await expect(page).toHaveScreenshot({
mask: [page.getByTestId('live-stock-price')],
});
A test ID is useful when the product team can guarantee that the hook remains attached to the changing region. For interactive controls, a role locator is usually clearer:
await expect(page).toHaveScreenshot({
mask: [page.getByRole('status', { name: 'Current exchange rate' })],
});
Use text locators for non-interactive content when the text is sufficiently unique. Avoid selectors that match an entire page section when only one number is unstable.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallRank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Mask several regions
await expect(page).toHaveScreenshot('dashboard.png', {
mask: [
page.getByTestId('last-updated'),
page.getByTestId('recommendation-carousel'),
page.getByRole('img', { name: 'Personalized avatar' }),
],
});
The array can contain one locator or many. Each matching element receives the overlay.
Constrain matching to visible elements
A crucial edge case is that Playwright applies the mask to invisible matching elements too. A hidden duplicate in a mobile menu, template, or dialog can therefore be masked even though it is not visible in the final rendering. When visibility matters, add a visibility filter:
const visiblePrice = page
.getByTestId('price')
.filter({ visible: true });
await expect(page).toHaveScreenshot({
mask: [visiblePrice],
});
Use the visibility-constrained form supported by your Playwright version and locator composition. If the page contains several visible matches, narrow the locator further with a parent region, an accessible name, or a test ID.
What masking changes—and what it does not
- It changes the captured image: the matched element’s bounding box is replaced by the overlay before comparison.
- It does not make the page deterministic: timers, animations, network responses, random data, and layout shifts still occur in the unmasked parts of the capture.
- It can cover nearby pixels: the covered area follows the locator’s box, not the exact glyphs or pixels that are volatile.
- It masks invisible matches: hidden elements are not automatically skipped.
- It is part of a screenshot assertion: it does not alter the DOM or application state for the rest of the test.
Screenshot assertions wait for two consecutive screenshots to be identical before comparing with the stored expectation. Masking reduces irrelevant differences during that comparison; it is not a replacement for stable test setup.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Do not confuse screenshot snapshots with other Playwright snapshots
Visual screenshot snapshots
toHaveScreenshot() is the visual-comparison API. It captures rendered pixels and supports mask and maskColor. These assertions are provided by the Playwright Test runner.
Generic snapshots
toMatchSnapshot() accepts a string or buffer and can compare text or other data. It is not the API to foreground for rendered screenshot masking. Use toHaveScreenshot() for visual screenshots.
ARIA snapshots
ARIA snapshots represent accessible structure rather than pixels and use toMatchAriaSnapshot(). They are a different assertion workflow; the ARIA documentation does not describe the screenshot mask option. Masking a visual region will not hide or change an element in an ARIA snapshot.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
A complete Playwright example
The following test combines stable setup, a narrowly scoped locator, a custom color, and a full-page screenshot:
Free tools Windows power users keep installed
One-click scans. No signup required.
import { test, expect } from '@playwright/test';
test('orders page remains visually stable', async ({ page }) => {
await page.goto('https://example.test/orders');
// Wait for the content that defines the page state.
await expect(page.getByRole('heading', { name: 'Orders' })).toBeVisible();
const volatileRegions = [
page.getByTestId('current-time'),
page.getByTestId('personalized-offer'),
];
await expect(page).toHaveScreenshot('orders-full-page.png', {
fullPage: true,
mask: volatileRegions,
maskColor: '#666666',
});
});
Keep page preparation explicit: select the same account or fixture data, wait for the relevant content, and control animation or time sources where they affect unmasked pixels. A mask should cover data that is intentionally irrelevant to this assertion, not hide a regression you still need to detect.
Troubleshoot unexpected masked screenshots
The mask is not visible where expected
Likely cause: the locator does not resolve at capture time, or it identifies a different element than the one displayed.
Fix: assert that the locator is present and inspect its count before the screenshot. Prefer a test ID or an accessible locator tied to the rendered region. If the content appears after navigation, wait for the page state that makes it available.
A large area is covered
Likely cause: the locator’s bounding box includes padding, a parent card, or multiple matched nodes.
Recommended Free Tools
Fix: target the smallest element containing the changing value and ensure the locator identifies only the intended match. Split a broad locator into several narrow locators if necessary.
A hidden duplicate is masked
Likely cause: invisible matches are included by design.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Fix: constrain the locator to visible content and scope it to the active panel, dialog, or viewport region.
The screenshot still changes despite masking
Likely cause: another dynamic region is outside the mask, or the page has not stabilized. The assertion’s consecutive-capture wait cannot correct an endlessly changing timer, animation, ad, or layout.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Fix: identify the remaining source of variation, freeze or disable it in test setup when appropriate, or add a narrowly scoped mask only if that content is outside the test’s purpose.
The test uses the wrong snapshot assertion
Likely cause: a generic toMatchSnapshot() or an ARIA snapshot is being used for a pixel comparison.
Fix: move the visual check to toHaveScreenshot() and keep ARIA assertions separate.
Different environments produce different results
Likely cause: browser, operating-system, font, viewport, device scale, or page state differs between baseline creation and comparison.
Fix: run the screenshot project with the same environment and deterministic fixture data. Masking only addresses selected page regions; it cannot normalize every rendering difference.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Performance and maintenance guidance
- Keep masks small: smaller boxes make diffs more meaningful and reduce the chance of hiding nearby regressions.
- Use semantic or test-facing locators: they are easier to review than brittle CSS chains.
- Review masks as test policy: document why each region is irrelevant to the assertion.
- Separate component and page tests: element screenshots can provide focused feedback, while page screenshots protect integration layout.
- Expect locator changes to be test changes: if markup moves, update the locator deliberately rather than replacing it with a broad selector.
There is no documented adoption or performance statistic associated with masking; its value is in making the pixels under test represent the behavior you actually want to protect.
Or skip the browser setup
If you need a production screenshot rather than a Playwright baseline assertion, ScreenshotNeo provides a website screenshot API and MCP server. It can remove cookie or consent banners, newsletter popups, and chat widgets before capture, while Playwright’s mask option is designed for a test’s rendered comparison. ScreenshotNeo also supports hide selectors and custom CSS when you need to exclude a page region from a standalone image.
One GET request returns PNG, JPEG, WebP, or PDF. The API base is https://api.screenshotneo.com/v1/shot; option details are in the ScreenshotNeo documentation.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', data);
ScreenshotNeo’s 63 options include full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF paper settings, custom CSS and JavaScript, click-before-capture actions, hide selectors, waits, request and resource blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which can simplify migration.
Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response reports the page verdict and billing status in X-Page-Verdict and X-Billed headers. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
The Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free. Create a free ScreenshotNeo account to try the 1,000 monthly shots without entering a card.
Frequently Asked Questions
Can I mask an element without using Playwright Test?
The documented toHaveScreenshot() assertions are Playwright Test runner features. For standalone captures, the page and locator screenshot APIs also accept mask; use those when you need an image file rather than a stored expectation comparison.
Does a mask remove the element from the page?
No. It changes the screenshot output by covering the locator’s bounding box. The DOM, accessibility tree, and application state remain unchanged.
What should I use when the requirement is accessibility structure instead of pixels?
Use an ARIA snapshot and toMatchAriaSnapshot(). ARIA snapshots represent accessible structure and are separate from visual screenshot masking.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

