Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Playwright with TypeScript, use await page.screenshot() for the current page and await page.locator(selector).screenshot() for one element. Add fullPage: true for the complete scrollable document. The same API can write an image file or return a buffer for a test attachment, upload, or image-processing pipeline.

Set up a TypeScript screenshot test

The examples below use the Playwright test runner. Install it in a project with npm init playwright@latest, choose TypeScript when prompted, and run tests with npx playwright test. A test should wait for the page state you need before capturing; navigation alone may finish before late content, fonts, or images are ready.

import { test, expect } from '@playwright/test';

test('capture a page', async ({ page }, testInfo) => {
  await page.goto('https://example.com');

  const image = await page.screenshot({ fullPage: true });
  await testInfo.attach('page screenshot', {
    body: image,
    contentType: 'image/png',
  });
});

page.screenshot() returns a Buffer when you omit path. Supplying path: 'artifacts/home.png' writes the image instead. The returned buffer is convenient when a reporter, cloud storage client, or another process consumes the image directly. The screenshots guide documents the page API and its options at Playwright’s screenshots guide.

Choose viewport or full-page capture

Current viewport

The default is the visible browser viewport:

await page.screenshot({ path: 'viewport.png' });

This is best for reproducing what a user sees at a particular device size. Set the viewport in the project configuration or per test when responsive layout matters.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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

Entire scrollable page

await page.screenshot({
  path: 'full-page.png',
  fullPage: true,
});

fullPage: true captures the full scrollable page rather than only the current viewport. Very long pages can create large files and may expose lazy content that is not loaded until it enters the viewport. If the page uses infinite scrolling, there is no stable “entire page” until you define how much content to load.

Control format and scale

Use a file extension or the type option to choose PNG, JPEG, or WebP where supported by your Playwright version. JPEG and WebP can reduce artifact size; PNG is normally preferable for pixel comparisons and text-heavy screenshots. quality applies to lossy formats. A retina-like image can be produced by running the context with a higher device scale factor, but keep that setting identical for visual baselines.

Capture one element with a locator

For a component, card, header, or chart, use a locator:

const header = page.locator('.header');
await header.screenshot({ path: 'header.png' });

Locator screenshots perform actionability checks and scroll the element into view. Prefer this API over ElementHandle.screenshot(), which Playwright marks as discouraged; see the Locator API and ElementHandle API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What an element screenshot does not fix

  • A covered element is not automatically uncovered; the pixels that are actually rendered are captured.
  • A scrollable container shows its current scroll position, not every item hidden inside it.
  • If the locator matches multiple nodes, strictness errors can occur. Narrow it with a role, text, test id, or .first() only when that choice is intentional.
await page.getByRole('button', { name: 'Save' }).screenshot({
  path: 'save-button.png',
});

Wait for the content you intend to capture

Make readiness explicit instead of relying on arbitrary sleeps. Wait for a meaningful selector, then optionally wait for a short animation or font transition:

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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
await page.goto('https://example.com/dashboard');
await page.locator('[data-testid="dashboard"]').waitFor();
await page.screenshot({ path: 'dashboard.png', fullPage: true });

For a specific image, wait until it is complete; for an application that renders after an API call, wait for the resulting UI state. A screenshot captures the browser’s current pixels, so animations, blinking cursors, rotating carousels, ads, and timestamps can make files differ between runs. Disable animations in a test stylesheet or freeze dynamic data when deterministic output matters.

Save screenshots automatically when a test fails

Configure the test runner rather than adding capture code to every test. In playwright.config.ts:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    screenshot: 'only-on-failure',
  },
});

Supported modes are off, on, only-on-failure, and on-first-failure. The practical diagnostic choice is usually only-on-failure, while on creates an artifact for every test. The option can also be an object, allowing screenshot options such as fullPage:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
export default defineConfig({
  use: {
    screenshot: {
      mode: 'only-on-failure',
      fullPage: true,
    },
  },
});

fullPage is false by default for this configuration. Confirm the exact option shape for your installed Playwright release in the TestOptions API.

Attach a screenshot to the test report

When you create a buffer yourself, attach it through testInfo.attach():

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.
test('attach a diagnostic image', async ({ page }, testInfo) => {
  await page.goto('https://example.com');
  const image = await page.screenshot({ fullPage: false });

  await testInfo.attach('viewport', {
    body: image,
    contentType: 'image/png',
  });
});

You may pass a path instead of a buffer. Await the attachment call before deleting a temporary file. Playwright copies attachments to a reporter-accessible location; details are in the TestInfo API.

Use screenshots for visual regression testing

For a pass/fail rendering comparison, use the test runner’s screenshot assertions rather than manually comparing files:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { test, expect } from '@playwright/test';

test('homepage matches its visual baseline', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveScreenshot('homepage.png');
});

test('component matches its baseline', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page.locator('.pricing-card')).toHaveScreenshot('pricing-card.png');
});

On the first run, Playwright creates a baseline; later runs compare against it. Before comparing, Playwright waits until two consecutive screenshots are identical and compares the last image, which helps with short-lived layout changes. Review baseline diffs deliberately: a changed font, browser version, operating system, viewport, device scale factor, locale, or color scheme can be a legitimate environment change rather than a regression. The assertion behavior is documented in the PageAssertions API.

Keep baselines organized

Projects that test Chromium, Firefox, and WebKit or multiple viewports should keep their snapshots separate. Configure snapshotPathTemplate with tokens for the test directory, test file path, project name, and snapshot argument:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  snapshotPathTemplate: '{testDir}/__snapshots__/{projectName}/{testFilePath}/{arg}{ext}',
});

The available template tokens and configuration rules are listed in the TestConfig API.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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

Useful capture patterns

Capture after a consent dialog is handled

const consent = page.getByRole('button', { name: /accept/i });
if (await consent.isVisible().catch(() => false)) {
  await consent.click();
}
await page.screenshot({ path: 'after-consent.png' });

Use a locator that reflects your application and avoid hiding a dialog merely to conceal a genuine user-facing problem in a regression test.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture a known state at a fixed viewport

test.use({ viewport: { width: 1440, height: 900 } });

test('desktop state', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page.locator('main')).toBeVisible();
  await page.screenshot({ path: 'desktop.png' });
});

Capture an element and attach it

const chart = page.locator('[data-testid="sales-chart"]');
const image = await chart.screenshot();
await testInfo.attach('sales chart', { body: image, contentType: 'image/png' });

Troubleshoot missing or unstable screenshots

Symptom Likely cause Fix
Timeout waiting for a locator The selector is wrong or the UI state never occurs. Check the locator with Playwright Inspector, wait for the actual state, and verify that navigation or authentication succeeded.
Element is clipped or only part of a list appears The target is inside a scrollable container. Scroll that container deliberately, capture each required state, or capture the page instead.
Full-page image is unexpectedly short The document has not expanded, or content is virtualized. Wait for the content that creates page height and load virtualized rows before capture.
Visual test fails intermittently Animations, network data, fonts, time, ads, or environment differences. Use deterministic fixtures, disable motion, wait for fonts and key selectors, and run baselines in a consistent browser/OS setup.
Attachment is absent from the report The test ended before attachment completion or the file was removed. Await testInfo.attach() and keep temporary files until it resolves.
Image is too large or slow Full-page PNG at a high device scale factor. Capture the viewport or a locator, use JPEG/WebP when pixel-perfect comparison is unnecessary, and avoid oversized scale factors.

Performance, reliability, and cost considerations

  • Viewport captures are faster and smaller than full-page images.
  • Stable selectors and explicit readiness checks reduce retries and false failures more effectively than increasing global timeouts.
  • Run visual baselines with pinned browser versions, fixed viewport and locale settings, and controlled test data.
  • Store failure artifacts and baselines separately: failure screenshots explain a test run, while baselines are reviewed source-controlled expectations.
  • For parallel projects, include the project name in snapshot paths so workers do not overwrite one another.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. A single GET request returns a PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and whether it was billed.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for all options. The same endpoint supports full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or a custom viewport, retina scale, PDF paper settings and page ranges, HTML/CSS rendering, custom JavaScript and CSS, pre-capture clicks, hidden selectors, selector/delay/network-idle waits, ad and tracker blocking, custom headers/cookies/user agents and Authorization, timezone and geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, an OpenAPI specification, and familiar parameter names used by other screenshot APIs.

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for 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. Growth is $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000; yearly billing gives two months free, and every feature is on every plan. Start with the free ScreenshotNeo account.

FAQ

Can I return screenshot bytes without writing a file?

Yes. Omit path; page.screenshot() and locator screenshots return a buffer that you can attach or upload.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use a page or locator screenshot for a component?

Use a locator. It targets the component and applies actionability checks; use a page screenshot when the surrounding layout is part of what you need to inspect.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.

Why is my visual baseline different on another machine?

Rendering depends on browser engine/version, operating system, fonts, viewport, scale factor, locale, color scheme, and dynamic data. Standardize those inputs before treating the difference as a product change.

Frequently Asked Questions

How do I capture a PDF instead of an image in Playwright?

The screenshot APIs produce images. For a PDF workflow, use Playwright’s page PDF capabilities in a Chromium context, or use ScreenshotNeo’s capture_pdf MCP/API option when the page is being captured remotely.

Can a locator screenshot include content outside the element’s box?

No. It captures the rendered locator element. Capture the page or a larger wrapper when surrounding context is required.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What is the safest default for CI failure evidence?

Configure the test runner with screenshot: 'only-on-failure', then use explicit locator waits in tests so the artifact represents the intended UI state.

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.