Use Playwright’s visual assertions to capture the iframe state that matters, save one capture as a baseline, and compare later renders with toHaveScreenshot(). Address iframe content with page.frameLocator(), wait for a stable element, and run the baseline and comparison in the same browser and operating-system environment. This catches genuine visual regressions while limiting noise from animations, fonts, timestamps and other unstable pixels.
What you are actually comparing
An iframe can be compared at three different scopes. Decide this before writing the test, because scope determines which changes count as failures.
| Target | Use it when | Trade-off |
|---|---|---|
| Whole page screenshot | The iframe’s placement, size, surrounding controls and page shell are part of the visual contract. | Unrelated page content can add noise and make failures harder to diagnose. |
| Specific iframe child locator | A component inside the frame is the thing you promise to keep visually stable. | It does not test the parent page’s layout, iframe boundary or integration. |
| Screenshot bytes plus an external diff | You need custom image processing or a comparison engine outside Playwright Test. | Your team must choose, configure and maintain that separate workflow. |
Playwright Test provides page and locator screenshot assertions, while its screenshot API can also return bytes for another diff tool. The visual-comparisons documentation describes the baseline workflow, and the Page API documents frameLocator().
Build a stable iframe screenshot test
1. Install and configure Playwright
In an existing Node project, install Playwright Test and its browser binaries:
Recommended Free Tools
#1 Best Overall
- 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.
npm install -D @playwright/test
npx playwright install
Keep the browser project, viewport, device scale factor, fonts and operating system consistent between baseline generation and comparison. Playwright warns that rendering can vary with the host OS, browser version, settings, hardware, power source and headless mode; those differences can create pixels that are not application regressions.
2. Navigate and wait for the iframe’s real readiness signal
Do not use an arbitrary sleep as your only synchronization. Wait for a selector inside the frame that appears only when the state is ready. The child locator below is intentionally an example; replace it with a selector owned by your application.
import { test, expect } from '@playwright/test';
test('iframe component matches visual baseline', async ({ page }) => {
await page.goto('/page-with-iframe');
const frameContent = page
.frameLocator('iframe[name="example-frame"]')
.locator('.component-to-compare');
await frameContent.waitFor({ state: 'visible' });
await expect(frameContent).toHaveScreenshot('iframe-component.png');
});
This follows the documented pattern used in Microsoft Learn’s Power Platform Playwright sample: select a named iframe, chain a locator into it, wait for that child, then assert its screenshot. Replace the frame selector, readiness condition and baseline name with values from your application. A frame locator scopes subsequent locators to the selected iframe; it avoids brittle manual frame lookup.
3. Create the first baseline
Run the test once. If no reference exists, Playwright writes a snapshot image in the test’s snapshot directory. Commit that image with the test so every later run compares against a known artifact:
npx playwright test tests/iframe-visual.spec.ts
Treat the first image as a reviewed specification, not as an unquestioned truth. Inspect its dimensions, loaded fonts, scroll position, color scheme and any data shown before committing it.
4. Compare a second state
To compare two rendered states, make the test produce state A for the baseline and state B for the later run. State B might be a new build, a feature flag, a different fixture or the same route after a controlled interaction. Keep navigation and setup deterministic so the image difference represents the change you intend to test.
Rank #2
- 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.
test('new iframe state is compared with the approved image', async ({ page }) => {
await page.goto('/page-with-iframe?fixture=approved');
const frame = page.frameLocator('iframe[name="example-frame"]');
const panel = frame.locator('.component-to-compare');
await panel.waitFor({ state: 'visible' });
await expect(panel).toHaveScreenshot('iframe-component.png');
});
If the surrounding page is part of the requirement, assert the page instead:
await expect(page).toHaveScreenshot('page-and-iframe.png');
A page capture validates composition and iframe placement; a child capture isolates the component. Use both only when they represent separate contracts, otherwise you create duplicate maintenance work.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated 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 matchControl pixels that should not decide the result
Wait for content, not time
Wait for a visible, meaningful child such as a chart canvas, heading or “loaded” marker. If the application exposes a network-idle or data-ready condition, use that in addition to the locator. A visible element can still be changing, so disable transitions or wait for the final class/state when your app provides one.
Freeze animation, fonts and user state
- Use a fixed viewport and device scale factor.
- Load the same web fonts and wait until they are available; fallback-font swaps alter line breaks.
- Set a deterministic locale, timezone, color scheme and reduced-motion preference where those affect rendering.
- Use fixed test data instead of current timestamps, random IDs or live counters.
- Start from the same hover, focus, scroll and authentication state.
- Keep browser version and headless/headed mode consistent.
These controls matter for iframe content as much as for the parent page. Cross-origin content may also depend on resources, cookies or headers that differ between environments; arrange a stable test fixture or use the frame’s production-like URL with controlled data.
Mask genuinely volatile regions
When a timestamp, rotating ad slot or changing column is not part of the visual contract, mask that locator instead of accepting broad differences. Microsoft’s applied example masks a changing column. A mask should cover only the known volatile region: an oversized mask can hide a real regression.
await expect(panel).toHaveScreenshot('iframe-component.png', {
mask: [frame.locator('.last-updated')]
});
Confirm the masking option against the Playwright version used by your project, and review failures to ensure the mask did not conceal layout movement around the region.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #3
- 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.
Use tolerances as an explicit policy
Playwright exposes a per-pixel threshold and an overall maxDiffPixelRatio. Microsoft Learn shows illustrative settings of threshold: 0.2 and maxDiffPixelRatio: 0.01 (1%); these are examples, not universal defaults or measured limits. Start strict, inspect the actual/expected/diff images, then document why a small tolerance is appropriate for your controlled environment. Increasing a threshold until a meaningful UI defect disappears defeats the test.
await expect(panel).toHaveScreenshot('iframe-component.png', {
maxDiffPixelRatio: 0.01,
threshold: 0.2
});
Read and approve a failure
A failed assertion should produce expected, actual and diff images. Compare them in that order:
- Check whether the iframe loaded the intended document and fixture.
- Look for a coherent product change (spacing, color, missing control or typography), rather than isolated antialiasing pixels.
- Check test setup for animation, font loading, data or environment drift.
- Fix the application or stabilize the test when the change is unintended.
- When the change is intentional, regenerate the reference, inspect it, and commit it with the code change.
Use Playwright’s update command only after review:
npx playwright test --update-snapshots
Updating snapshots accepts new output; it does not prove that the new output is correct. Require code review for the image and the reason it changed.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsCommon iframe comparison failures
The locator times out
The frame selector may be wrong, the iframe may be created later, or the child selector may belong to a different document. Verify the iframe’s name, id or stable attribute, then wait for the child inside frameLocator(). Avoid selecting by a generated index when several frames exist.
The screenshot is blank or partially rendered
The assertion ran before data, fonts or lazy content arrived. Wait for a frame-owned readiness element, ensure the test fixture returns data, and remove transitions. For a full-page capture, make sure the intended scroll and lazy-loading behavior has completed before asserting.
Rank #4
- 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
Only one operating system fails
Compare the browser version, OS font set, device scale factor, headless mode and power state. Either standardize the execution image or maintain baselines per supported environment. Do not hide a platform-specific layout defect with a large diff tolerance.
Every run has small random differences
Look for clocks, random content, rotating media, caret/focus state, animation and network responses. Replace live data with fixtures, freeze time where possible, disable motion, and mask only the remaining volatile locator. A broad page-level tolerance is usually less informative than a stable, smaller target.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →The iframe changed but the page screenshot did not reveal why
Run the narrow child assertion to isolate the component, then a page assertion to check integration. Conversely, a child assertion can pass while the iframe is clipped or misplaced; that is why scope must match the visual contract.
You use another test runner
Screenshot assertions are a Playwright Test feature. With another runner, call the screenshot API and pass the returned bytes to your chosen image-diff facility. The workflow still requires deterministic setup, an approved reference and human review of intentional changes.
Performance, reliability and maintenance
- Capture less when you can: a focused locator is faster and produces smaller, more diagnostic artifacts than a whole page.
- Keep fixtures deterministic: stable data reduces retries and makes failures reproducible.
- Separate contracts: use names that identify route, frame and state, and store snapshots beside the owning test.
- Run a controlled matrix: choose the browser/OS combinations your product supports and generate each baseline in that same combination.
- Review diffs as code: include the image change and explanation in the pull request; do not update all snapshots blindly.
- Prefer explicit readiness: a reliable signal reduces wasted retries compared with long global sleeps.
For a bespoke pipeline, Playwright’s screenshot bytes let you defer storage and comparison to another service, but that adds responsibility for image formats, retention, diff algorithms and artifact review.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If you need a rendered reference image rather than an in-process Playwright assertion, ScreenshotNeo returns a website screenshot or PDF from one GET request. Before capture it accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be turned off. Only clean shots are billed: bot checks/CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and response headers report the page verdict and billing result.
Its 63 options cover full-page capture with lazy images, a CSS-selected element, dark mode, 12 device presets or any viewport, retina scale, PDF paper settings and page ranges, custom CSS/JavaScript, clicks, selector or network-idle waits, request/resource blocking, headers, cookies, user-agent, Authorization, timezone, geolocation, transparent backgrounds, resizing, selectable cache TTL, signed image links, asynchronous jobs with signed webhooks, up to 100 URLs per bulk call, usage reporting and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which can simplify migration. An MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.
Best Value
- 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.
For an iframe URL or page that hosts it, call the API and then compare the returned file with your approved image:
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 request options. The same request in 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)
And in 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}`);
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is on every plan. Create a free ScreenshotNeo account to try the 1,000 monthly captures.
FAQ
Can frameLocator select a cross-origin iframe?
It scopes locators to the selected frame. Your test still needs the frame to load and the target to be accessible to Playwright; application authentication and readiness must be configured for that document.
Should I compare two images in one test?
Usually keep one approved snapshot per named visual contract. Produce the alternate state through controlled test setup, then assert it against that reference so a failure identifies the state and scope clearly.
How do I know whether a diff is rendering noise?
Re-run under the same environment, inspect expected/actual/diff artifacts, and check fonts, animation, data and device scale before changing thresholds. Repeatable, localized differences are more likely to be product changes than scattered antialiasing noise.
Frequently Asked Questions
Can frameLocator select a cross-origin iframe?
It scopes locators to the selected frame. Your test still needs the frame to load and the target to be accessible to Playwright; application authentication and readiness must be configured for that document.
Should I compare two images in one test?
Usually keep one approved snapshot per named visual contract. Produce the alternate state through controlled test setup, then assert it against that reference so a failure identifies the state and scope clearly.
How do I know whether a diff is rendering noise?
Re-run under the same environment, inspect expected/actual/diff artifacts, and check fonts, animation, data and device scale before changing thresholds. Repeatable, localized differences are more likely to be product changes than scattered antialiasing noise.
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.

