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

In JavaScript, read the current address with page.url(), turn its hostname and pathname into a safe filename, then pass the result to page.screenshot({ path }). The example below adds a short hash of the full URL so pages with different query strings or fragments do not overwrite each other.

Save a screenshot using the current page URL

This runnable Node.js example uses Playwright, creates a screenshots directory if needed, and saves a full-page PNG. Install Playwright in your project first; the Chromium browser must also be installed for the selected browser to launch.

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

function filenameFromUrl(rawUrl) {
  const url = new URL(rawUrl);
  const readable = `${url.hostname}${url.pathname}`
    .replace(/[^a-zA-Z0-9._-]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 100) || 'page';

  // Include the full URL in the hash to distinguish query strings and fragments.
  const hash = createHash('sha256').update(rawUrl).digest('hex').slice(0, 10);
  return `${readable}-${hash}.png`;
}

const browser = await chromium.launch();
try {
  const page = await browser.newPage();
  await page.goto('https://example.com/products?id=42');

  const outputDir = path.resolve('screenshots');
  await mkdir(outputDir, { recursive: true });
  const outputPath = path.join(outputDir, filenameFromUrl(page.url()));
  await page.screenshot({ path: outputPath, fullPage: true });
  console.log(`Saved ${outputPath}`);
} finally {
  await browser.close();
}

The official Playwright Page API documents page.url() and the screenshot path option. Playwright accepts the path; it does not prescribe this filename scheme. Sanitizing, limiting the length, and deciding how to handle collisions are application choices.

How the filename policy works

Readable hostname and path

The visible part uses the hostname and pathname, for example example.com-products-.... Characters outside letters, digits, periods, underscores, and hyphens are replaced with hyphens, preventing URL path separators from becoming filesystem directories. The readable portion is capped at 100 characters before the hash and extension are added.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sandisk 2TB Extreme Portable SSD, Up to 1050MB/s, USB-C, USB 3.2 Gen 2, IP65 Water and Dust Resistance, Updated Firmware, External Solid State Drive, SDSSDE61-2T00-G25
  • Get NVMe solid state performance with up to 1050MB/s read and 1000MB/s write speeds in a portable, high-capacity drive(1) (Based on internal testing; performance may be lower depending on host device & other factors. 1MB=1,000,000 bytes.)
  • Up to 3-meter drop protection and IP65 water and dust resistance mean this tough drive can take a beating(3) (Previously rated for 2-meter drop protection and IP55 rating. Now qualified for the higher, stated specs.)
  • Use the handy carabiner loop to secure it to your belt loop or backpack for extra peace of mind.
  • Help keep private content private with the included password protection featuring 256‐bit AES hardware encryption.(3)
  • Easily manage files and automatically free up space with the SanDisk Memory Zone app.(5). Non-Operating Temperature -20°C to 85°C

Query strings, fragments, and collisions

The hash uses the full URL. Thus two URLs that have the same host and path but different query strings or fragments produce different names, while potentially sensitive query values do not appear in readable form. A short hash makes accidental collisions unlikely, but it is not a guarantee of uniqueness. If query parameters are only tracking values and should not create distinct files, hash a normalized URL with those parameters removed instead. That changes the naming policy and may cause distinct page states to share a filename.

Relative paths and output format

path.resolve('screenshots') makes the output directory absolute from the current working directory. The explicit .png extension matches Playwright’s default PNG screenshot format. For an ordinary viewport screenshot, omit fullPage: true; full-page capture is an explicit option, not the default. See the Playwright screenshots guide for the screenshot workflow and full-page examples.

Rank #2
Sandisk 1TB Portable SSD, Up to 800MB/s Read Speeds, Black (Old Model)
  • Solid state performance with up to 800MB/s read speeds in a portable drive. (Based on internal testing; performance may be lower depending on host device, interface, usage conditions and other factors. 1MB=1,000,000 bytes.)
  • Back up your content and memories on a storage solution that fits seamlessly into your mobile lifestyle.
  • Take it with you on your adventures—up to two-meter drop protection means this durable drive can take a beating. (Based on internal testing.)
  • Secure it to your belt loop or backpack for extra peace of mind thanks to the tough rubber hook.
  • From Sandisk, a brand professional photographers trust to take on assignments.

Choose the right URL-to-filename behavior

Policy Useful when Trade-off
Hostname and pathname only Query values do not represent different pages and stable names matter. Different query-driven page states can overwrite one another.
Readable hostname/path plus hash of the full URL You want recognizable names and separation for query or fragment variants. The suffix is not human-readable; changing any URL component changes the name.
Include query text directly The query is short, safe to expose, and operators need to inspect it in filenames. Names can become long, contain awkward characters, or expose tokens and personal data.

Do not put raw URLs into filenames without sanitizing them. Query strings can contain credentials, session identifiers, email addresses, or other sensitive values; prefer a hash when those values should not be visible in directory listings or logs.

Other useful Playwright variants

Save only the viewport

Use the same generated path but call await page.screenshot({ path: outputPath }). Without fullPage: true, Playwright captures the current viewport.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
SSK Portable SSD 500GB External Solid State Hard Drive USB C Up to 1050MB/s
  • Capacity Display Variance: 500GB external ssd often appears as around 465GB on Windows. MacOS can show full 500 GB capacity. This is binary calculation difference and doesn’t affect SSD hard drive actual physical storage
  • 1050 MB/s Speed: Instantly access to your files with blazing-fast 10Gbps external SSD read up to 1050MB/s and write up to 1000MB/s. LED Light indicates USB SSD instant activity
  • Data Security: Solid state drives S.M.A.R.T. health diagnostics​ and adaptive TRIM optimizing data block management ensures consistent write speeds and extends the longevity of the portable SSD
  • USB-C & USB-A Cable: Both cables featuring rapid USB 3.2 Gen2, this USB SSD effortlessly bridges devices, enabling seamless cross-platform file transfers and backup between computers, smartphones, tablets and iPhone
  • Always Fast: No slowdowns for large file transfers. With SLC caching (25% of current available capacity allocated as high-speed cache), this external SSD delivers steady 10Gbps for transfers within the cache capacity

Keep the bytes for upload or processing

You can omit path and capture the returned image buffer instead: const image = await page.screenshot({ fullPage: true });. Your script can then upload or process image rather than writing directly to a file. The Page API documents both the path option and screenshot output behavior.

Playwright Test snapshots

For screenshot assertions in Playwright Test, test.info().snapshotPath(name, { kind: 'screenshot' }) returns a path governed by the test project’s configured snapshot layout. That is useful for test snapshots; for an arbitrary filename derived from the live page URL, generate your own path and pass it to page.screenshot(). See the TestInfo API documentation.

Rank #4
Sale
Sandisk 1TB Extreme Portable SSD, Up to 2000MB/s Transfer Speeds-New Model
  • NEARLY 2X FASTER THAN OUR PREVIOUS GENERATION(8) – move 1,000 high-res photos in under 60 seconds(6) with up to 2000MB/s transfer speeds(2).
  • IP65 RATING AND UP TO 3M DROP PROTECTION(3) – protects against spills and drops.
  • POCKET-SIZED – fits easily in pockets and small bags.
  • SPACE TO OWN YOUR AI CONTENT – speed and capacity to download your high-res clips and photo edits.
  • 256-BIT AES ENCRYPTION(4) – helps keep private files secure with password protection.

Troubleshoot common failures

  • Invalid URL: new URL(rawUrl) requires a valid absolute URL. Ensure navigation completed and that the page has a usable address before deriving the filename.
  • Browser launch failure: Install the browser binary for the Playwright package in the environment where the script runs, and verify that the selected browser is available.
  • Directory or permission error: Check that the process can create or write to the output directory. The sample creates the directory recursively, but cannot override filesystem permissions.
  • Screenshot not found where expected: The sample resolves screenshots from the process’s current working directory. Log the absolute outputPath or use a configured absolute output directory.
  • Unexpected overwrite: Confirm whether query parameters and fragments should distinguish captures. The sample hashes the full URL; a hostname/path-only strategy intentionally does not.
  • Very long filename: The readable host/path portion is capped at 100 characters, but the hash and extension are added afterward. Adjust the cap if the target filesystem has stricter limits.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you need an image from a URL without managing a local Playwright browser, ScreenshotNeo offers a screenshot API. This call saves a WebP screenshot; its API documentation describes the available parameters.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/products?id=42 -o shot.webp
  • Cookie banners are accepted and removed, along with known newsletter popups and chat widgets, before the shot; each step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers identify the page verdict and whether it was billed.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and other MCP clients.
  • The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to try 1,000 screenshots a month with no card.

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.

Quick Recap

Bestseller No. 2
Sandisk 1TB Portable SSD, Up to 800MB/s Read Speeds, Black (Old Model)
Sandisk 1TB Portable SSD, Up to 800MB/s Read Speeds, Black (Old Model)
From Sandisk, a brand professional photographers trust to take on assignments.
$188.90
SaleBestseller No. 4
Sandisk 1TB Extreme Portable SSD, Up to 2000MB/s Transfer Speeds-New Model
Sandisk 1TB Extreme Portable SSD, Up to 2000MB/s Transfer Speeds-New Model
IP65 RATING AND UP TO 3M DROP PROTECTION(3) – protects against spills and drops.; POCKET-SIZED – fits easily in pockets and small bags.
$209.99
SaleBestseller No. 5
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.99
Best Value
Sale
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

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.