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

Replace images at the layer that matches your test: inject CSS or change the DOM when the page already contains the right element, or intercept network requests when the page must receive different image bytes. Register replacements before navigation, wait for decoding and layout to settle, disable motion, and keep the rendering environment fixed. The patterns below cover Playwright, Puppeteer, synchronization, service workers, troubleshooting, and a no-browser alternative.

Choose the replacement layer

Situation Recommended method Why
Existing <img> or CSS background and the box should stay the same DOM/CSS override Fast and local; matching dimensions preserve layout.
The page must consume replacement bytes, or images are inserted dynamically Network interception Substitutes the resource before rendering, including elements created later.
Third-party hosts, signed URLs, or expiring image URLs URL- or resource-type interception Decouples the test from unstable remote assets.
Visual-regression baseline Either method plus a stable environment Removes asset, animation, and rendering noise together.

Playwright: replace an image with CSS for one screenshot

Playwright can apply a stylesheet only for a screenshot with the style option. The style is applied through Shadow DOM and inner frames, making it useful for hiding an image or painting a fixture over its box without changing application state.

import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 });
await page.goto('https://example.com', { waitUntil: 'networkidle' });

await page.screenshot({
  path: 'page.png',
  style: `
    img.hero {
      content-visibility: hidden;
      background: url('file:///tmp/replacement.png') center/cover no-repeat;
    }
  `,
  animations: 'disabled'
});
await browser.close();

Use a selector specific enough to avoid replacing unrelated images. Keep the replacement’s aspect ratio and sizing rules compatible with the original; otherwise text may reflow and the screenshot will test layout changes rather than the intended page.

Swap the source in the DOM

A source swap is preferable when application code should see the replacement URL. Set src (or a CSS background), then wait for the new resource to finish loading and decoding before capture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });

await page.evaluate(() => {
  const image = document.querySelector('img.hero');
  if (!image) throw new Error('img.hero was not found');
  image.src = '/fixtures/hero-test.png';
});

await page.waitForFunction(() => {
  const image = document.querySelector('img.hero');
  return image && image.complete && image.naturalWidth > 0;
});
await page.evaluate(async () => {
  const image = document.querySelector('img.hero');
  if (image?.decode) await image.decode();
});
await page.screenshot({ path: 'page.png', fullPage: true, animations: 'disabled' });

If the fixture is served by your test server, use an absolute URL when the page’s base URL would otherwise resolve it incorrectly. For a CSS background, set element.style.backgroundImage and wait for an explicit preload or for the browser to report the image complete through a temporary Image object.

Playwright: intercept image responses

Route interception replaces bytes before the browser renders them. Register the route before navigation so early requests are covered. The example uses a narrow URL pattern and a local fixture.

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

test('uses deterministic image fixtures', async ({ page }) => {
  await page.route('**/*', async route => {
    const request = route.request();
    if (request.resourceType() === 'image' && request.url().includes('/cdn/')) {
      await route.fulfill({
        path: 'tests/fixtures/replacement.png',
        contentType: 'image/png'
      });
    } else {
      await route.continue();
    }
  });

  await page.goto('https://example.com', { waitUntil: 'networkidle' });
  await expect(page).toHaveScreenshot('page.png', { fullPage: true });
});

Service-worker caveat

A service worker can own requests before page routing sees them. Configure the browser context to block service workers when interception is required, or arrange the application’s worker so fixture requests are handled intentionally. If a route appears correct but the original image still renders, inspect service-worker registration and cache state first.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Puppeteer: respond to image requests

Puppeteer request interception exposes respond(), abort(), and continue(). Once interception is enabled, every request stalls until one of those outcomes is chosen (or the browser completes it from cache), so every branch must resolve the request.

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.
import puppeteer from 'puppeteer';
import fs from 'node:fs/promises';

const browser = await puppeteer.launch();
const page = await browser.newPage();
const replacementPngBuffer = await fs.readFile('./fixtures/replacement.png');

await page.setRequestInterception(true);
page.on('request', request => {
  if (request.resourceType() === 'image' && request.url().includes('/cdn/')) {
    request.respond({
      status: 200,
      contentType: 'image/png',
      body: replacementPngBuffer
    }).catch(() => {});
  } else {
    request.continue().catch(() => {});
  }
});

await page.goto('https://example.com', { waitUntil: 'networkidle2' });
await page.screenshot({ path: 'page.png', fullPage: true });
await browser.close();

Use request.abort() to test missing-image states, but expect broken-image icons and changed layout unless the page reserves dimensions. Match by URL when only selected assets should change; matching every image resource also catches icons, sprites, and tracking pixels.

Make the capture deterministic

Wait for the replacement, not merely navigation

networkidle or networkidle2 says little about whether a lazy image has decoded. Wait for the target selector, verify complete and naturalWidth, and call decode() where available. For lazy-loaded content, use a full-page capture or scroll the page so the image enters an intersection observer’s viewport before waiting.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Freeze motion and visual state

Disable CSS transitions, animations, and blinking cursors. Playwright screenshot assertions disable animations and wait for two consecutive screenshots to be identical before comparing. Apply an explicit color scheme, locale, timezone, viewport, device scale factor, and font set; otherwise legitimate rendering differences can appear as image failures.

Control the rendering environment

Browser rendering can vary with host operating system, browser version and settings, hardware, power source, headless mode, and related environment details. Pin browser binaries in CI, run captures in the same container or runner image, and install the exact fonts used by the page. Choose CSS-pixel scaling for stable dimensions; choose a device scale factor greater than one only when high-DPI output is part of the requirement.

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

Preserve layout deliberately

  • Give replacement files the same intrinsic dimensions or enforce an explicit width, height, or aspect-ratio.
  • Keep object-fit, object-position, and background sizing consistent with production CSS.
  • For responsive pages, set a fixed viewport and test each breakpoint separately.
  • Use fullPage: true when replaced content can occur below the initial viewport.

Common failures and fixes

The original image still appears

The route may have been registered after navigation, the selector may not match, or a service worker may have served a cached response. Register interception first, log matching URLs, use a precise selector check, and clear or block the service worker for the test context.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The screenshot contains a broken-image icon

The replacement path may be inaccessible from the browser, the response may have the wrong content type, or capture happened before decoding. Serve the fixture from a reachable origin, set contentType, verify the HTTP status, and wait for naturalWidth > 0 plus decode().

Requests hang after enabling interception

One event branch did not resolve its request. Ensure every request is continued, fulfilled/responded, or aborted, including requests that throw during logging or fixture loading. Remove interception when the test is finished if the page object is reused.

Only some lazy images are replaced

They may not have requested an image yet. Capture full page, scroll through the document, or trigger the application’s lazy-load condition before waiting. Also check whether the source is a CSS background or a responsive srcset candidate rather than a plain src.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Pixels differ between machines

Pin browser and OS images, fonts, viewport, device scale, color scheme, and headless configuration. Disable animations and transitions, and avoid comparing a page while web fonts or replacement bitmaps are still loading.

A cross-origin replacement is blocked

Network interception avoids most page-level CORS issues because the browser receives the fulfilled response directly. A DOM swap still follows normal page security rules; serve the fixture from an allowed origin or use a test-server route.

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 returns a screenshot or PDF from one GET request, with options for full-page capture, element selectors, custom CSS and JavaScript, clicks, waits, hidden selectors, request blocking, headers, cookies, user agents, timezone, geolocation, resizing, caching, signed links, asynchronous jobs, bulk capture, and more. Its cleanup step accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

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 complete parameter list in the ScreenshotNeo documentation. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

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

Python and Node.js alternatives

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(`${res.status} ${res.statusText}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

Operational and cost notes

  • Fixture interception minimizes dependence on remote hosts but requires maintaining representative assets.
  • DOM overrides are usually faster and less invasive, while byte replacement better tests image decoding, MIME handling, and dynamic insertion.
  • Keep request matching narrow to avoid replacing icons, CSS resources, or unrelated third-party images.
  • Record the browser version, viewport, scale factor, fixture hash, and replacement rule with each baseline so a changed asset is explainable.
  • When using a hosted API, inspect verdict and billing headers so failed or non-clean responses can be handled separately from successful captures.

Frequently Asked Questions

Should I replace an image in the DOM or intercept its request?

Use a DOM or CSS override when you only need a visual fixture. Intercept the request when the page must receive replacement bytes or creates image elements dynamically.

Why does my replacement work locally but not in CI?

Check browser and OS versions, fonts, viewport, device scale, service-worker state, and whether the fixture path is reachable in the CI environment.

Can I test a missing image intentionally?

Yes. Abort the selected image request, but reserve layout space if you want to test the surrounding page rather than a reflow caused by a broken-image icon.

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.