October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
APIs

How to Set a Screenshot Filename with an API (Playwright, Puppeteer, and Test Artifacts)

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

Set the screenshot filename by passing a path in the screenshot options. In Playwright, use await page.screenshot({ path: 'screenshots/login.png' });; in Puppeteer, use the same path option. The path controls both the directory and the basename, while the extension determines the image format. A relative path is resolved from the process’s current working directory.

The filename option you need

Most browser screenshot APIs do not have a separate “filename” setting. They accept a filesystem path instead. For example:

await page.screenshot({ path: 'screenshots/login.png' });

This writes login.png inside the screenshots directory. If the directory is relative, it is interpreted from the current working directory of the process running your script, not necessarily from the directory containing the source file.

Use an extension that matches the format you want. Playwright and Puppeteer infer the screenshot type from the extension. A .png path produces PNG, .jpeg or .jpg produces JPEG, and .webp produces WebP where that format is supported by the API and browser version. Do not name a JPEG file with a .png suffix merely to change its appearance; the extension is part of the format selection.

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.

Playwright: save a screenshot with a custom name

Basic JavaScript example

import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');

await page.screenshot({ path: 'screenshots/home.png' });

await browser.close();

The call returns after the file has been written. Create the destination directory ahead of time when your environment does not create it automatically:

import { mkdir } from 'node:fs/promises';
import { chromium } from 'playwright';

await mkdir('screenshots', { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({ path: 'screenshots/home.png', fullPage: true });
await browser.close();

Use a generated filename safely

When names contain dates, IDs, or user input, sanitize those values before putting them in a path. Avoid slashes, backslashes, null bytes, and .. segments that could escape the intended directory.

const safeId = String(orderId).replace(/[^a-z0-9_-]/gi, '_');
const file = `screenshots/order-${safeId}.png`;
await page.screenshot({ path: file });

Element and full-page captures

The same path option works with a locator screenshot and with full-page capture:

await page.locator('#invoice').screenshot({ path: 'screenshots/invoice.png' });
await page.screenshot({ path: 'screenshots/entire-page.png', fullPage: true });

Keep the image in memory instead

Omit path when you want bytes rather than a file. Playwright returns image data that you can upload, transform, or write later.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const image = await page.screenshot({ type: 'png' });
await uploadToStorage(image);

This is useful when a storage SDK, database, HTTP response, or test attachment—not your local filesystem—should own the final name.

Puppeteer: the equivalent path

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'networkidle2' });
await page.screenshot({ path: 'screenshots/home.png', fullPage: true });
await browser.close();

Puppeteer’s ScreenshotOptions.path is the output file path. As in Playwright, a relative path is based on the current working directory, the extension selects the image type, and leaving out path returns image data without writing a file.

Capture one element

const card = await page.$('.product-card');
if (!card) throw new Error('Product card was not found');
await card.screenshot({ path: 'screenshots/product-card.png' });

Choosing the right storage approach

Requirement Use What controls the name and location?
Standalone image on disk page.screenshot({ path }) Your supplied path and the process working directory
Upload or transform before saving Screenshot without path Your upload or filesystem code
Attach to a test report Playwright Test output or attachment APIs The test runner’s artifact rules, plus your attachment label
Run a CLI or MCP wrapper That wrapper’s documented filename argument The wrapper’s output root and filename rules

Playwright Test: filenames for artifacts and reports

If the screenshot belongs to a test result, prefer the per-test output directory instead of inventing a global path. This keeps retries, workers, and reports from overwriting each other.

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

test('login page', async ({ page }, testInfo) => {
  await page.goto('https://example.com/login');
  await page.screenshot({ path: testInfo.outputPath('login.png') });
});

testInfo.outputPath() asks Playwright Test for a path associated with the current test. The resulting filename can still be login.png, but the runner chooses the correct root and keeps it with the test’s output.

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

Attach a buffer to a report

test('visual evidence', async ({ page }, testInfo) => {
  const buffer = await page.screenshot({ type: 'png' });
  await testInfo.attach('login-screen', {
    body: buffer,
    contentType: 'image/png'
  });
});

An attachment label and a filesystem path are different controls. The label shown in a report is sanitized and used as a filename prefix in report storage; it is not the same as passing path to the screenshot method.

CLI and MCP wrappers use different names

When you call a Playwright command through a CLI or MCP surface, follow that wrapper’s schema. Those interfaces use a filename argument rather than the library API’s path option, and they may place files under a wrapper-specific output root. Do not paste a wrapper example into a Node.js library call or assume the current working directory is unchanged.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API when you need a named response file without maintaining Playwright or Puppeteer. One GET request returns PNG, JPEG, WebP, or PDF; save the response under any filename you choose.

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)
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}`);

See the ScreenshotNeo documentation for request options. Before capture, it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

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

The Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan. Create a free ScreenshotNeo account.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting filename problems

The file is in the wrong directory

Print or inspect the process working directory before changing the path. In Node.js, process.cwd() shows the base used for a relative path. A test runner, container, IDE, or CI job may start your process somewhere different from your project directory. Use an absolute path or the runner’s output helper when that location must be deterministic.

No file appears

  • Confirm that you supplied path; without it, the method returns bytes only.
  • Check that the parent directory exists and that the process can write there.
  • Wait for the screenshot promise to resolve before the process exits.
  • In a test, check the runner’s artifact directory rather than the project root.

The format is not what you expected

Make the extension match the intended type. If the API supports an explicit type, use it consistently with the extension. A mismatch can cause confusing files, downstream decoder errors, or a format different from what another tool expects.

Two tests overwrite one another

Use unique names or testInfo.outputPath(). Include a test ID, worker ID, or timestamp only after sanitizing it, and avoid relying on a shared fixed filename in parallel runs.

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

The screenshot is blank or incomplete

Filename handling does not control page readiness. Wait for navigation, a specific selector, or the application’s data request before calling the screenshot method. For lazy-loaded pages, use full-page capture and an explicit readiness condition, then inspect the resulting file.

Visual snapshots differ between machines

Host operating system, browser version, settings, hardware, power source, and headless mode can change pixels. Pin the browser and runtime where possible, use a consistent viewport and font environment, and configure the test runner’s snapshot path separately from ordinary screenshot filenames.

Operational guidance for reliable names

  • Choose one convention: for example, area-state-viewport.ext such as checkout-error-desktop.png.
  • Keep extensions truthful: consumers often use them to select decoders and MIME types.
  • Create directories explicitly: use recursive directory creation during setup.
  • Prevent collisions: include a stable identifier for parallel or repeated captures.
  • Separate temporary and published files: write to a temporary name, then rename after a successful capture when readers must never see partial output.
  • Record the resolved path: logging the final path makes CI failures and container volume mistakes easier to diagnose.
  • Control retention: screenshots can consume substantial disk space, especially full-page PNGs; clean old artifacts or upload them to durable storage.

Which method should you use?

Use path when your application needs a normal local file with a predictable name. Omit it when an upload service or image processor should receive bytes directly. Use testInfo.outputPath() or report attachments when the screenshot is evidence for a Playwright Test result. Use a wrapper’s filename only when you are invoking that wrapper. For hosted, repeatable captures without browser maintenance, ScreenshotNeo is the alternative to try first because it removes common page clutter, bills only clean successful shots, and has a $5 paid entry plan.

Frequently Asked Questions

Can I use a filename without an extension?

You can pass a path, but relying on extension-based format inference becomes ambiguous. Use an extension that states the intended image type.

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

Does changing the filename change screenshot quality?

No. The name controls storage; quality, scale, viewport, and capture settings control the pixels.

Can I save directly to cloud storage?

The browser libraries return bytes when no path is supplied. Upload that buffer with your storage SDK and choose the object key there.

Why does a CLI example use filename while my code uses path?

CLI and MCP wrappers define their own argument schemas. The library API uses path; wrapper commands may use filename and a different output root.

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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.

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.