Playwright iFrame Handling: The Complete 2026 Guide
Playwright iframe handling is the technique of interacting with elements that live inside an <iframe>, a separate web document embedded within the main page, such as a payment form, chat widget, video player or rich text editor. Because each iframe has its own DOM, a normal page.locator() cannot see its contents and simply times out. Playwright solves this with locator.contentFrame() and page.frameLocator(), which point every locator, action and assertion into the iframe while keeping auto-waiting, strict matching and retries fully intact.
Table of Contents
ToggleUnlike Selenium, there is no switching in and out: the page and the frame are separate objects you use side by side. The same approach scales to nested iframes through chaining, works across different domains without extra setup, and stays stable even when an iframe reloads, which makes it the most reliable way to automate embedded content in modern web apps.

How Does Playwright Handle iFrames?
Playwright handles iframes by switching the search area from the main page to the inner document, using page.locator(‘iframe’).contentFrame() or page.frameLocator(‘iframe’). After that, every locator, click, fill and assertion runs inside the iframe with full auto-waiting, so you never need a manual “switch to frame” and “switch back” step like in Selenium.
In one line: find the iframe, open its content frame, then locate elements inside it.
await page.locator(‘#payment-frame’).contentFrame().getByLabel(‘Card number’).fill(‘4242 4242 4242 4242’);
Key facts to remember:
- A normal page locator cannot see inside an iframe, because an iframe is a separate web page living inside the main page.
- locator.contentFrame() (Playwright 1.43+) is now the preferred, official way to enter an iframe.
- page.frameLocator() still works and does the same job in a shorter form.
- page.frame() and page.frames() give a live Frame object for advanced work like running JavaScript or checking a frame’s URL.
- Nested iframes are handled by chaining: contentFrame() → locate inner iframe → contentFrame() again.
- Playwright works with cross-origin iframes (for example a Stripe or YouTube iframe on your site) without extra setup.
This guide is written by the Playwright trainers at Playwright Masters and is part of our free Playwright automation testing tutorial series. Every code sample was written for the current Playwright Test runner in TypeScript, with Python and Java versions where they matter.
What Is an iFrame?
An iframe is a window on a web page that shows a completely different web page inside it. The name means “inline frame”, and in HTML it looks like <iframe src=”https://another-site.com”></iframe>.
Think of a TV in your living room. Your living room is the main web page. The TV is the iframe. The show on the TV comes from a TV channel far away, not from your living room. You can see the show, but you cannot reach into the screen and grab the actor’s cup. To change what is on the TV, you must pick up the remote that belongs to that TV.
In Playwright, contentFrame() is that remote.
Where you meet iframes in real projects:
- Payment boxes from Stripe, Razorpay, PayPal or Braintree, where card fields live on the payment company’s server for security.
- Rich text editors such as TinyMCE and older CKEditor setups, where the typing area is its own small document.
- Embedded YouTube or Vimeo players, Google Maps, and social media posts.
- Login widgets such as “Sign in with Google” buttons and single sign-on screens.
- CAPTCHA and bot-check boxes.
- Live chat bubbles, help desks and feedback forms (Intercom, Zendesk, HubSpot).
- Old enterprise apps and admin dashboards built with frames to show reports.
Frame vs iframe, in one sentence: the old <frame> tag split a whole browser window into parts and is no longer supported in modern HTML, while <iframe> places one page inside another and is used everywhere today. Playwright treats both the same way, as a Frame.
Why Do Normal Playwright Locators Fail Inside iFrames?
Normal locators fail inside iframes because page.locator() only searches the main page’s document, and every iframe has its own separate document. The element is truly on screen, but it lives in a different “house”, so Playwright keeps searching the wrong house until the timeout runs out.
Here is the mistake almost every beginner makes:
// Fails: the email box is inside an iframe
await page.getByPlaceholder(‘Email’).fill(‘kid@example.com’);
// Error: Timeout 30000ms exceeded. waiting for getByPlaceholder(‘Email’)
And here is the fix:
// Works: enter the iframe first
const signupFrame = page.locator(‘iframe[title=”Signup form”]’).contentFrame();
await signupFrame.getByPlaceholder(‘Email’).fill(‘kid@example.com’);
How to know an element is inside an iframe (30-second check):
- Right-click the element in Chrome and choose Inspect.
- Scroll up in the Elements panel from the highlighted line.
- If you pass an <iframe> tag with #document under it before reaching <body>, the element is inside that iframe.
- Another quick sign: the DevTools Console has a dropdown at the top that says top. If it lists other names, the page has iframes.
A simpler trick is to run npx playwright codegen your-url and click the element. If the generated line contains contentFrame(), the element is inside an iframe. Learn more in our Playwright Codegen guide.
If you are new to how Playwright finds elements, read the Playwright locators guide first. Everything you learn there works inside iframes too, once you have entered the frame.
The 3 Ways to Handle iFrames in Playwright
Playwright gives you three ways to reach an iframe: locator.contentFrame(), page.frameLocator(), and the Frame object from page.frame(). Use the first one for almost every test, the second if your team already uses it, and the third only when you need frame-level powers like evaluate() or the frame’s URL.
Method 1: locator.contentFrame() (recommended)
contentFrame() turns a locator that points at an <iframe> tag into a FrameLocator that searches inside it. It arrived in Playwright 1.43, and the official docs now use it as the standard form.
const editor = page.getByTitle(‘Rich Text Area’).contentFrame();
await editor.locator(‘body’).fill(‘Hello from Playwright Masters’);
await expect(editor.locator(‘body’)).toHaveText(‘Hello from Playwright Masters’);
Why it is the best choice:
- You can find the iframe with any locator you already know, including getByTitle(), getByTestId() and .filter().
- You can pick one iframe out of many with .first(), .last() or .nth(i) before calling contentFrame().
- It reads like plain English: “find this iframe, then look inside it.”
Method 2: page.frameLocator() (short form)
page.frameLocator(selector) takes a CSS or XPath selector for the iframe and returns the same kind of FrameLocator in one step.
const checkout = page.frameLocator(‘iframe[name=”checkout”]’);
await checkout.getByRole(‘button’, { name: ‘Pay now’ }).click();
It is still fully supported, so old tests do not need rewriting. Note that frameLocator.first(), .last() and .nth() are deprecated; use page.locator(‘iframe’).nth(1).contentFrame() instead.
To go backwards from a FrameLocator to the <iframe> element itself (for example to check that the iframe is visible or read its src), use owner():
const frameTag = checkout.owner();
await expect(frameTag).toBeVisible();
await expect(frameTag).toHaveAttribute(‘src’, /secure-pay/);
Method 3: The Frame object (page.frame and page.frames)
page.frame() returns a live Frame handle that you find by its name attribute or its URL. Use it when a FrameLocator is not enough.
const reportFrame = page.frame({ url: /\/reports\// });
console.log(reportFrame?.url());
const rows = await reportFrame?.evaluate(() => document.querySelectorAll(‘tr’).length);
// List every frame on the page (main page included)
for (const f of page.frames()) console.log(f.name(), f.url());
A Frame is a snapshot of one live document. If the iframe reloads or is removed, that handle becomes useless, and you get a “Frame was detached” error. A FrameLocator never goes stale, because it finds the iframe again every time you use it.
Which method should you use?
Your goal | Use this | Example |
Click, type, assert inside an iframe | locator.contentFrame() | page.getByTitle(‘Chat’).contentFrame() |
Keep using older test code | page.frameLocator() | page.frameLocator(‘#chat’) |
Pick the 2nd of many same iframes | locator.nth(1).contentFrame() | page.locator(‘.ad’).nth(1).contentFrame() |
Check the iframe tag itself | frameLocator.owner() | expect(fl.owner()).toBeVisible() |
Run JavaScript inside the frame | frame.evaluate() | page.frame(‘report’)?.evaluate(…) |
Read a frame’s URL or name | page.frame() / page.frames() | page.frames().map(f => f.url()) |
Go up to the parent frame | frame.parentFrame() | inner.parentFrame() |
Step-by-Step: Your First Playwright iFrame Test
You can practise iframe handling without any website, because Playwright’s page.setContent() can build a page with an iframe right inside your test. The example below works offline, never breaks because a demo site changed, and runs in under a second.
If Playwright is not installed yet, follow the Playwright installation guide and come back.
Step 1: Build a practice page with an iframe
The srcdoc attribute puts a mini web page straight into the iframe, so no server is needed.
Step 2: Enter the iframe with contentFrame()
Find the iframe by its title. A title is stable, readable and also helps screen-reader users, so it is the best attribute to target.
Step 3: Act and assert inside the frame
Use normal locators like getByLabel() and getByRole() on the frame, then check the result with a web-first assertion.
TypeScript (Playwright Test)
import { test, expect } from ‘@playwright/test’;
test(‘fill a form inside an iframe’, async ({ page }) => {
// Step 1: a page that contains an iframe
await page.setContent(`
<h1>Main page</h1>
<iframe title=”Newsletter” srcdoc=”
<label>Name <input id=’n’></label>
<button onclick="document.querySelector(‘p’).textContent=’Thanks, ‘+document.querySelector(‘#n’).value">Join</button>
<p></p>
“></iframe>
`);
// Step 2: enter the iframe
const newsletter = page.getByTitle(‘Newsletter’).contentFrame();
// Step 3: act and assert inside it
await newsletter.getByLabel(‘Name’).fill(‘Aarav’);
await newsletter.getByRole(‘button’, { name: ‘Join’ }).click();
await expect(newsletter.locator(‘p’)).toHaveText(‘Thanks, Aarav’);
// The main page is still reachable with page.*
await expect(page.getByRole(‘heading’, { name: ‘Main page’ })).toBeVisible();
});
Notice the last line. You never “switch back” to the main page. The page object always means the main page, and the frame variable always means the iframe, so both can be used side by side.
Python (pytest-playwright)
In Python the method is frame_locator(), and content_frame is a property, so it has no brackets.
from playwright.sync_api import Page, expect
def test_fill_form_inside_iframe(page: Page):
page.goto(“https://your-app.example/newsletter”)
newsletter = page.get_by_title(“Newsletter”).content_frame
newsletter.get_by_label(“Name”).fill(“Aarav”)
newsletter.get_by_role(“button”, name=“Join”).click()
expect(newsletter.locator(“p”)).to_have_text(“Thanks, Aarav”)
# Short form that also works:
# page.frame_locator(“iframe[title=’Newsletter’]”).get_by_label(“Name”)
More Python patterns are in our Playwright with Python guide.
Java (Playwright for Java)
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
FrameLocator newsletter = page.getByTitle(“Newsletter”).contentFrame();
newsletter.getByLabel(“Name”).fill(“Aarav”);
newsletter.getByRole(AriaRole.BUTTON, new FrameLocator.GetByRoleOptions().setName(“Join”)).click();
assertThat(newsletter.locator(“p”)).hasText(“Thanks, Aarav”);
// Frame object by name or URL
Frame report = page.frame(“report”);
Frame payment = page.frameByUrl(java.util.regex.Pattern.compile(“.*pay.*”));
Java learners can go deeper with the Playwright with Java guide, and TypeScript learners with Playwright with TypeScript.
Same task, three languages
Action | TypeScript / JavaScript | Python | Java |
Enter iframe from a locator | locator.contentFrame() | locator.content_frame | locator.contentFrame() |
Enter iframe by selector | page.frameLocator(sel) | page.frame_locator(sel) | page.frameLocator(sel) |
Back to the iframe tag | frameLocator.owner() | frame_locator.owner | frameLocator.owner() |
Frame by name | page.frame(‘name’) | page.frame(name=’name’) | page.frame(“name”) |
Frame by URL | page.frame({ url: /x/ }) | page.frame(url=re.compile(‘x’)) | page.frameByUrl(pattern) |
All frames | page.frames() | page.frames | page.frames() |
Nested, Dynamic and Multiple iFrames
How do you handle nested iframes in Playwright?
You handle nested iframes by chaining: enter the outer iframe, locate the inner iframe inside it, and call contentFrame() again. Each step goes one level deeper, like opening a box that holds another box.
const dashboard = page.locator(‘#dashboard-frame’).contentFrame();
const chart = dashboard.locator(‘#chart-frame’).contentFrame();
const tooltip = chart.locator(‘#tooltip-frame’).contentFrame();
await expect(tooltip.getByText(‘Sales: 1,200’)).toBeVisible();
// Same thing in one line with frameLocator
await page.frameLocator(‘#dashboard-frame’)
.frameLocator(‘#chart-frame’)
.getByRole(‘button’, { name: ‘Export’ }).click();
The rule to remember: you cannot skip a level. Searching for #chart-frame from page will fail, because that iframe lives inside #dashboard-frame, not on the main page.
To walk up instead of down, a Frame object has parentFrame() and childFrames(), which is handy when printing the full frame tree while debugging.
How do you wait for an iframe that loads late?
You usually do not need to wait at all, because every action and web-first assertion on a FrameLocator waits for the iframe to appear, then waits for the element inside it. The best explicit wait is an assertion on something inside the frame.
const chat = page.getByTitle(‘Live chat’).contentFrame();
// Good: waits for the iframe AND for its content to be ready
await expect(chat.getByRole(‘textbox’, { name: ‘Message’ })).toBeVisible({ timeout: 15_000 });
// Weak: only proves the <iframe> tag exists, not that its page has loaded
await expect(page.getByTitle(‘Live chat’)).toBeVisible();
Avoid page.waitForTimeout(5000) to “give the iframe time”. Fixed sleeps make tests slow when the iframe is fast and flaky when it is slow. Our guide to fixing flaky Playwright tests explains why sleeps cause random failures.
For iframes that are added by JavaScript after a click, you can also listen for frame events:
const framePromise = page.waitForEvent(‘frameattached’);
await page.getByRole(‘button’, { name: ‘Open support’ }).click();
const supportFrame = await framePromise;
await supportFrame.waitForLoadState();
Playwright also emits framenavigated (an iframe went to a new URL) and framedetached (an iframe was removed), which help when a widget reloads itself.
How do you choose one iframe when several match?
You choose one iframe by narrowing the locator before calling contentFrame(). If a selector matches two or more iframes, Playwright stops with a strict mode violation instead of guessing, which protects you from clicking in the wrong box.
// Error: strict mode violation, locator(‘iframe’) resolved to 3 elements
await page.locator(‘iframe’).contentFrame().getByRole(‘button’).click();
// Best: pick by a unique, meaningful attribute
await page.locator(‘iframe[title=”Billing address”]’).contentFrame().getByLabel(‘City’).fill(‘Hyderabad’);
// Good: pick by part of the iframe’s src URL
const videoFrame = page.locator(‘iframe[src*=”youtube.com/embed”]’).contentFrame();
// Last resort: pick by position (breaks if the order changes)
await page.locator(‘iframe.widget’).nth(1).contentFrame().getByText(‘Accept’).click();
Best attributes to target, from most to least stable: title → data-testid → name → id → a part of src (iframe[src*=”youtube”]) → position with nth(). Ask your developers to add a title or data-testid to every iframe; it is a one-line change that makes tests far more reliable.
Cross-Origin, Sandbox and srcdoc iFrames
Can Playwright handle cross-origin iframes?
Yes. Playwright can click, type and assert inside an iframe from a different domain, such as a payment form from js.stripe.com embedded on your-shop.com. It talks to the browser through its own automation channel, so the browser’s normal “same-origin” wall does not block it. This is one of Playwright’s biggest advantages over tools that run inside the page, which is explained in our Playwright architecture guide.
Two things still behave differently with cross-origin frames:
- JavaScript runs per frame. page.evaluate() runs only in the main page and cannot read the iframe’s variables. Use frame.evaluate() on that specific frame instead.
- Third parties protect themselves. Payment and CAPTCHA providers may detect automation or block repeated test traffic. Use their official test mode and test keys rather than fighting their protection.
// Read a value from inside a cross-origin frame
const payFrame = page.frame({ url: /stripe\.com/ });
const ready = await payFrame?.evaluate(() => document.readyState);
How do sandboxed iframes behave?
An iframe with a sandbox attribute has its powers switched off unless each one is allowed, for example sandbox=”allow-scripts allow-forms”. Playwright can still find and read elements inside it, but if allow-scripts is missing, the iframe’s own JavaScript will not run, so buttons that depend on scripts will do nothing when clicked. If a click “works” but nothing happens, check the sandbox value before blaming your test.
How do you handle srcdoc and about:blank iframes?
An iframe built with srcdoc or one that a script fills in has no real URL; its URL shows as about:srcdoc or about:blank. That means page.frame({ url }) is a poor way to find it. Target it by title, name, id or data-testid with contentFrame() instead, exactly as in the practice test above.
Do Playwright locators pierce iframes automatically?
No. Playwright locators pierce open Shadow DOM automatically, but they never cross into an iframe on their own. You must always enter the iframe with contentFrame() or frameLocator(). Mixing these two ideas up is a very common interview mistake; you can practise more like it in our Playwright interview questions.
Real-World Playwright iFrame Scenarios
These are the iframe situations testers in Hyderabad, Bengaluru and around the world hit most often in real projects, with a working pattern for each.
1. Payment card fields (Stripe, Razorpay, Braintree)
Modern payment forms often put each card field in its own tiny iframe. Treat every field as a separate frame and always use the provider’s test card numbers in a test or sandbox environment.
const cardNumber = page.locator(‘iframe[title*=”card number” i]’).contentFrame();
const expiry = page.locator(‘iframe[title*=”expiration” i]’).contentFrame();
const cvc = page.locator(‘iframe[title*=”CVC” i]’).contentFrame();
await cardNumber.getByPlaceholder(/card number/i).fill(‘4242424242424242’);
await expiry.getByPlaceholder(/MM/).fill(’12/34′);
await cvc.getByPlaceholder(/CVC/i).fill(‘123’);
The i after the attribute value makes the match case-insensitive, which protects you when the provider changes “Card Number” to “card number”. Never run automated tests with real card numbers.
2. Rich text editors (TinyMCE and similar)
In iframe-based editors, the typing area is the <body> of the inner document.
const editorBody = page.locator(‘iframe.tox-edit-area__iframe’).contentFrame().locator(‘body’);
await editorBody.fill(‘Release notes for v2.4’);
await expect(editorBody).toContainText(‘Release notes’);
Toolbar buttons such as Bold usually sit outside the iframe on the main page, so click them with page, and check the text with the frame.
3. A popup or new tab opened from inside an iframe
When a link inside an iframe opens a new tab, the popup event still fires on the main page. Start waiting before you click.
const help = page.getByTitle(‘Help widget’).contentFrame();
const popupPromise = page.waitForEvent(‘popup’);
await help.getByRole(‘link’, { name: ‘Open full article’ }).click();
const article = await popupPromise;
await expect(article).toHaveTitle(/Help Center/);
4. Alerts and confirm dialogs triggered inside an iframe
JavaScript dialogs raised by an iframe are also caught by page.on(‘dialog’). Register the handler first, then click.
page.once(‘dialog’, dialog => dialog.accept());
await page.locator(‘#settings-frame’).contentFrame().getByRole(‘button’, { name: ‘Delete’ }).click();
5. File upload inside an iframe
setInputFiles() works on a file input inside a frame exactly as it does on the main page. See more patterns in our file upload and download guide.
const uploader = page.getByTitle(‘Document uploader’).contentFrame();
await uploader.locator(‘input[type=”file”]’).setInputFiles(‘tests/fixtures/invoice.pdf’);
await expect(uploader.getByText(‘invoice.pdf’)).toBeVisible();
6. Mocking network calls made by an iframe
page.route() also catches requests sent from iframes, so you can stub a slow third-party widget and keep your test fast and stable. Learn the full technique in Playwright network interception.
await page.route(‘**/chat-widget/config’, route =>
route.fulfill({ json: { enabled: true, greeting: ‘Hi there!’ } })
);
7. Embedded video players and maps (YouTube, Google Maps)
For third-party embeds you do not own, test that they are present and pointing at the right content, rather than testing the provider’s own buttons.
const video = page.locator(‘iframe[src*=”youtube.com/embed”]’);
await expect(video).toBeVisible();
await expect(video).toHaveAttribute(‘src’, /VIDEO_ID/);
8. CAPTCHA inside an iframe
Do not try to solve a CAPTCHA in automation. Ask your developers for a test environment where CAPTCHA is turned off, or use the provider’s official test keys, which always pass. This keeps tests honest and respects the provider’s terms.
9. Login pages inside an iframe
When the sign-in form lives in an iframe, log in once through the frame, save the session, and reuse it in every test. This avoids repeating slow iframe logins. Our Playwright authentication guide shows how to save and reuse storageState.
10. Keeping iframe code clean with the Page Object Model
Wrap each iframe in its own class so tests never repeat selectors. If the iframe’s title changes, you fix one line.
export class CheckoutFrame {
constructor(private page: Page) {}
private get frame() {
return this.page.getByTitle(‘Secure checkout’).contentFrame();
}
async pay(card: string) {
await this.frame.getByLabel(‘Card number’).fill(card);
await this.frame.getByRole(‘button’, { name: ‘Pay’ }).click();
}
}
The Page Object Model guide and Playwright fixtures guide show how to inject classes like this into every test automatically.
Debugging Playwright iFrame Errors: Causes and Fixes
Most iframe failures come from one of five causes: a missing contentFrame(), a selector that matches several iframes, a skipped nesting level, a frame that reloaded, or content that has not loaded yet. The table below maps each error message to its fix.
Error message you see | What it really means | How to fix it |
Timeout 30000ms exceeded while the element is clearly on screen | You searched the main page, but the element is inside an iframe | Add locator(‘iframe…’).contentFrame() before the element locator |
strict mode violation: locator(‘iframe’) resolved to N elements | Your iframe selector matches more than one iframe | Use a unique title, name or data-testid, or .nth(i) before contentFrame() |
Frame was detached | You held a Frame object, and the iframe was removed or replaced | Switch to a FrameLocator (it re-finds the iframe each time), or call page.frame() again |
Execution context was destroyed | The iframe navigated while evaluate() was running | Wait for the frame’s new content first, then evaluate |
page.frame() returns null | The name or URL is wrong, or the iframe has not attached yet | Print page.frames().map(f => f.url()), or wait with page.waitForEvent(‘frameattached’) |
Element found in the outer frame but not the inner one | A nested iframe level was skipped | Chain one contentFrame() per level |
Click passes but nothing happens | Sandboxed iframe without allow-scripts, or an overlay covers it | Check the sandbox attribute; check the trace screenshot for overlays |
Tools that make iframe debugging easy
- Playwright Inspector: run npx playwright test –debug, then hover the pick-locator tool over the element. It writes the full frame chain for you.
- Codegen: npx playwright codegen records iframe steps as ready-to-use contentFrame() chains.
- Trace Viewer: open npx playwright show-trace trace.zip to see a DOM snapshot of every step, including the inside of each iframe, along with network calls and console logs. Our Playwright Trace Viewer guide shows how to turn traces on for CI failures.
- UI Mode: npx playwright test –ui lets you step through a test and watch the iframe update in real time.
- Print the frame tree: a quick helper for any test that is lost.
function printFrames(frame = page.mainFrame(), indent = ”) {
console.log(`${indent}${frame.name() || ‘(no name)’} ${frame.url()}`);
for (const child of frame.childFrames()) printFrames(child, indent + ‘ ‘);
}
printFrames();
For a complete debugging workflow beyond iframes, see the Playwright debugging guide.
Best Practices for Playwright iFrame Handling
FrameLocator vs Frame: what is the difference?
A FrameLocator is a recipe for finding an iframe each time you need it, while a Frame is a live handle to one specific document at one moment.
Feature | FrameLocator | Frame |
Created by | locator.contentFrame(), page.frameLocator() | page.frame(), page.frames(), elementHandle.contentFrame() |
Auto-waits for the iframe | Yes | No, the iframe must already exist |
Survives iframe reload | Yes, it re-finds the iframe | No, it becomes detached |
Strict mode (one match only) | Yes | Not applicable |
Run JavaScript with evaluate() | No | Yes |
Read URL, name, parent, children | No (use owner() for the tag) | Yes |
Best for | Clicking, typing, asserting | Debugging, scripting, frame events |
Playwright vs Selenium: how iframe handling differs
In Selenium you must call driver.switchTo().frame(…), work inside it, and then call driver.switchTo().defaultContent() to come back. Forgetting to switch back is a classic bug. In Playwright there is no switching at all: the frame and the page are two separate variables you can use in any order.
Task | Selenium | Playwright |
Enter an iframe | driver.switchTo().frame(“pay”) | page.locator(‘#pay’).contentFrame() |
Go back to main page | driver.switchTo().defaultContent() | Not needed; just use page |
Go to parent frame | driver.switchTo().parentFrame() | Not needed; keep a variable for each level |
Wait for the frame | ExpectedConditions.frameToBeAvailableAndSwitchToIt | Built in, automatic |
Cross-origin iframes | Supported, with switching | Supported, no switching |
Moving an existing suite? Our Selenium to Playwright migration guide and the full Playwright vs Selenium comparison cover every other difference.
Frequently Asked Questions About Playwright iFrame Handling
How do I switch to an iframe in Playwright?
You do not switch in Playwright. You create a frame locator with page.locator(‘iframe’).contentFrame() and call actions on it, while page keeps pointing at the main page.
What is the difference between frameLocator() and contentFrame()?
Both return a FrameLocator that searches inside an iframe. page.frameLocator(selector) takes a selector string, while locator.contentFrame() starts from any locator, so it also works with getByTitle(), filter() and nth().
Is page.frameLocator() deprecated?
No, page.frameLocator() is still supported. Only frameLocator.first(), .last() and .nth() are deprecated, and the replacement is to call nth() on the iframe locator before contentFrame().
How do I get the text of an element inside an iframe?
Use await page.locator(‘iframe#news’).contentFrame().locator(‘h2’).textContent(). For tests, prefer await expect(frameElement).toHaveText(‘…’), because it retries until the text appears.
How do I count iframes on a page?
Use await page.locator(‘iframe’).count() for iframe tags on the main page, or page.frames().length for every frame, including nested ones and the main page itself.
How do I handle an iframe without an id or name?
Target it by title, a part of its src (iframe[src*=”maps”]), its parent container (page.locator(‘#sidebar iframe’)), or by position with nth() as a last option.
Can I take a screenshot of only an iframe?
Yes. Call await page.locator(‘iframe#chart’).screenshot({ path: ‘chart.png’ }) on the iframe tag. This is also the basis for visual checks, covered in our Playwright visual testing guide.
Does Playwright Codegen record actions inside iframes?
Yes. Codegen detects iframes and writes the full contentFrame() chain for every action you record, including nested frames.
Why does my iframe test pass locally but fail in CI?
CI machines are slower and often headless, so third-party iframes load later. Assert on content inside the frame, raise the timeout for that one assertion, mock slow widgets with page.route(), and collect traces. See our Playwright CI/CD guide.
Do iframes work in Playwright’s mobile emulation?
Yes. Frame handling is the same in emulated devices, though responsive sites may load a different iframe on small screens. Check the Playwright mobile emulation guide for device setup.
Is iframe handling asked in Playwright interviews?
Yes, it is one of the most common practical questions. Interviewers usually ask how to enter an iframe, handle nested frames, and how Playwright differs from Selenium’s switchTo().frame().
Conclusion
Playwright iframe handling comes down to one habit: find the iframe, call contentFrame(), and work inside it with the same locators and assertions you already know. Add chaining for nested frames, stable title attributes for multiple frames, and in-frame assertions instead of sleeps, and your iframe tests will stay green on every browser and in CI.
Want to practise iframes, payment flows and real project frameworks with a mentor beside you? Playwright Masters offers hands-on Playwright training in Hyderabad, online batches and corporate training. Talk to our team to ask about the next batch.

Playwright Masters Team
Playwright Automation Testing Experts | Industry-Focused Training & Practical Learning
Playwright Masters is a dedicated automation testing training platform focused on helping learners build practical skills in Playwright automation testing. Our training covers real-world automation concepts, framework practices, coding, debugging, API testing, cross-browser testing, CI/CD, and interview preparation to help learners develop job-ready testing skills.
