Playwright 20 ๐ญ Frames and Iframes โ frameLocator and nested contexts
An <iframe> embeds a complete, separate HTML document inside the current page. Playwright’s page.locator() only searches the main document; it does not cross the iframe boundary. Elements that are visibly present on screen but live inside an iframe will never match a page-level locator, and the test will time out with a confusing “element not found” error even though the element is plainly there. Playwright solves this with frameLocator(), a lazy, auto-waiting gateway into an iframe’s document that preserves the same locator API used everywhere else.
This chapter covers the complete iframe workflow: entering a frame with frameLocator(), chaining calls to reach nested iframes, understanding why iframe locators are strict and how to handle multiple matches, and operating inside cross-origin frames without hitting the same-origin policy. It also covers the lower-level Frame API for cases that require the frame’s URL, navigation events, or evaluate() execution, and explains when frameLocator() is sufficient versus when the Frame object is necessary. By the end, you will be able to reach any element inside any iframe, no matter how deeply nested.
Key point: An iframe is a separate document. page.locator() cannot see into it. page.frameLocator('iframe-selector') returns a scoped locator that enters that document lazily, auto-waits for the iframe to load, and then applies the normal locator methods inside the frame’s DOM.
Why frameLocator exists
The document boundary problem. The DOM inside an iframe belongs to a different document, with its own <html>, <body>, and element tree. A page-level locator resolves against the main document’s tree and never descends into embedded documents, even though the iframe element itself is a child of the main document. This separation is intentional browser architecture, not a Playwright limitation, and it means iframe content requires an explicit entry point.
The lazy resolution advantage. The older page.frame() API returns a Frame object that is resolved immediately. If the iframe has not loaded yet, or if it is removed and recreated during a page’s lifecycle, the reference becomes stale. frameLocator() is lazy: it does not resolve the iframe until a locator method is actually called, and it re-resolves on each use. This makes it resilient to iframes that load late, iframes that are conditionally rendered, and single-page applications that replace iframe content without a full navigation .
The cross-origin transparency. A cross-origin iframe (one whose src points to a different domain) normally blocks JavaScript access to its contentDocument under the same-origin policy. Playwright operates at the browser automation protocol level, not through page JavaScript, so frameLocator() can enter and interact with cross-origin iframes exactly as it does same-origin ones. This is one of Playwright’s strongest advantages over evaluate-based approaches, which fail on cross-origin frames .
a. Entering a frame with frameLocator
The frameLocator() method accepts a selector that identifies the iframe element in the parent document. The selector can target the iframe by id, name, src pattern, title, or any CSS attribute. The returned object exposes the same locator methods as pageโgetByRole, getByText, getByLabel, locator, and the restโbut every match is scoped to the iframe’s document .
import { test, expect } from '@playwright/test';
test('interacting with a payment iframe', async ({ page }) => {
await page.goto('/checkout');
// Enter the iframe by its id; no await needed on frameLocator itself
const paymentFrame = page.frameLocator('#payment-iframe');
// Locate elements inside the iframe using the normal locator API
await paymentFrame.getByLabel('Card number').fill('4242 4242 4242 4242');
await paymentFrame.getByLabel('Expiry').fill('12/28');
await paymentFrame.getByLabel('CVC').fill('123');
// Assert on content rendered inside the iframe
await expect(paymentFrame.getByText('$49.99')).toBeVisible();
// Click the submit button that lives inside the iframe
await paymentFrame.getByRole('button', { name: 'Pay now' }).click();
});
The frameLocator() call itself does not wait or resolve anything. The first method called on the returned objectโfill(), click(), expect()โtriggers the iframe resolution, and Playwright auto-waits for the iframe to be attached and for its document to be ready before attempting the action. This means a test does not need an explicit waitForSelector on the iframe element .
For cases where the iframe selector is not known at authoring time, page.frameLocator() called with no arguments searches the main frame and every iframe for a matching element, provided Playwright 1.63 or later is in use. This is convenient for simple pages but loses precision when multiple iframes exist; an explicit selector is preferred whenever the iframe can be identified .
b. Chaining frameLocator for nested iframes
An iframe can contain another iframe, and the inner document is three levels deep: main page, outer iframe document, inner iframe document. Reaching an element in the innermost frame requires chaining frameLocator() calls, one per level. Each call scopes the search to the document of the iframe matched by the previous selector.
test('reaching an element in a nested iframe', async ({ page }) => {
await page.goto('/editor');
// The editor has an outer iframe containing an inner preview iframe
const editorFrame = page.frameLocator('#editor-outer');
const previewFrame = editorFrame.frameLocator('#preview-inner');
// Now interact with the element inside the innermost document
await previewFrame.getByRole('button', { name: 'Refresh preview' }).click();
// Assert on the innermost frame's content
await expect(previewFrame.getByText('Preview updated')).toBeVisible();
});
The chaining is not optional decoration: skipping the outer frameLocator() and calling page.frameLocator('#preview-inner') would search the main document for an iframe with that id, which does not exist. Each frameLocator() call returns a new scoped gateway, and the next call searches only within that gateway’s document . The same chaining pattern extends to any depth, though frames nested more than two or three levels deep are rare in practice.
Selectors should be specific at every level. Using positional selectors like frameLocator('iframe').nth(0) is fragile because the order of iframes can change when the page adds or removes embeds. Targeting by id, name, title, or a distinctive src pattern keeps the locator stable across layout changes .
c. Strictness, multiple frames, and cross-origin content
Frame locators are strict: if the selector matches more than one iframe, every operation on the frame locator throws an error rather than silently picking one. This is a deliberate design choice that prevents tests from interacting with the wrong frame when a page contains several identical-looking embeds. When multiple matches are expected and the first is intentionally desired, .first() must be applied to the frame locator explicitly .
test('handling multiple matching iframes with explicit first()', async ({ page }) => {
await page.goto('/dashboard');
// The page has several ad iframes with the same class
// page.frameLocator('.ad-frame') would throw on any operation
// Explicitly select the first one
const firstAd = page.locator('.ad-frame').first().contentFrame();
await expect(firstAd.getByRole('link')).toBeVisible();
// Alternatively, use a more specific selector to avoid the ambiguity
const promoAd = page.frameLocator('iframe[title="Promotion"]');
await promoAd.getByRole('button', { name: 'Claim offer' }).click();
});
The locator.contentFrame() method is the modern replacement for page.frame() and accepts a locator that points to the iframe element, which is useful when the iframe is located by a more complex locator than a simple CSS selector . Cross-origin iframes behave identically: frameLocator('iframe[src*="external-domain.com"]') enters the frame and allows interaction without any special configuration, because Playwright’s protocol-level access is not subject to the same-origin policy that blocks page JavaScript .
Complete Example Session
// ============================================
// PART 1: IMPORT AND TEST SETUP
// ============================================
import { test, expect } from '@playwright/test';
// ============================================
// PART 2: ENTERING A SIMPLE IFRAME
// ============================================
test('iframe interaction workflow', async ({ page }) => {
await page.goto('/checkout');
// Enter the payment iframe by its id
const payment = page.frameLocator('#payment-iframe');
// ============================================
// PART 3: FILLING INPUTS INSIDE THE FRAME
// ============================================
await payment.getByLabel('Card number').fill('4242 4242 4242 4242');
await payment.getByLabel('Expiry').fill('12/28');
await payment.getByLabel('CVC').fill('123');
// ============================================
// PART 4: ASSERTING ON FRAME CONTENT
// ============================================
await expect(payment.getByText('$49.99')).toBeVisible();
// ============================================
// PART 5: CLICKING INSIDE THE FRAME
// ============================================
await payment.getByRole('button', { name: 'Pay now' }).click();
await expect(page.getByText('Payment successful')).toBeVisible();
// ============================================
// PART 6: NESTED IFRAMES
// ============================================
await page.goto('/editor');
const outer = page.frameLocator('#editor-outer');
const inner = outer.frameLocator('#preview-inner');
await inner.getByRole('button', { name: 'Refresh' }).click();
await expect(inner.getByText('Updated')).toBeVisible();
// ============================================
// PART 7: CROSS-ORIGIN IFRAME
// ============================================
await page.goto('/integrations');
const external = page.frameLocator('iframe[src*="widget.example.com"]');
await external.getByRole('button', { name: 'Connect' }).click();
// ============================================
// PART 8: USING THE FRAME OBJECT FOR URL ACCESS
// ============================================
const frame = page.frame({ url: /widget\.example\.com/ });
expect(frame).not.toBeNull();
expect(frame!.url()).toContain('widget.example.com');
// ============================================
// PART 9: USING frameLocator WITH SPECIFIC SELECTOR
// ============================================
const specific = page.frameLocator('iframe[title="Support chat"]');
await specific.getByPlaceholder('Type a message').fill('Hello');
await specific.getByRole('button', { name: 'Send' }).click();
// ============================================
// PART 10: MULTIPLE IFRAMES WITH FIRST()
// ============================================
const firstAd = page.locator('.ad-slot').first().contentFrame();
await expect(firstAd.getByRole('link')).toBeVisible();
});
The ten parts above cover the full range: entering a frame by id, filling inputs, asserting on frame content, clicking inside a frame, chaining for nested frames, operating inside a cross-origin iframe, using the Frame object for URL verification, targeting a frame by title, and resolving ambiguous selectors with .first().contentFrame().
Quick Reference
FrameLocator Methods
| Method | Purpose | Example |
|---|---|---|
frameLocator(selector) | Enter an iframe | page.frameLocator('#pay') |
.frameLocator(selector) | Enter a nested iframe | outer.frameLocator('#inner') |
.getByRole(...) | Locate by ARIA role inside frame | frame.getByRole('button') |
.getByLabel(...) | Locate by label inside frame | frame.getByLabel('Email') |
.locator(selector) | CSS selector inside frame | frame.locator('.total') |
.first() | Resolve multiple matching frames | page.frameLocator('.ad').first() |
locator.contentFrame() | Convert iframe locator to FrameLocator | page.locator('#f').contentFrame() |
FrameLocator vs Frame API
| Aspect | frameLocator() | page.frame() |
|---|---|---|
| Resolution | Lazy, re-resolves each use | Eager, can become stale |
| Auto-wait | Yes | No |
| Locator methods | Full getBy* API | Element handles only |
| URL access | No | Yes (frame.url()) |
evaluate() | No | Yes (frame.evaluate()) |
| Cross-origin | Yes | Yes, but URL matching needed |
Common Selectors for iframes
| Selector | Matches |
|---|---|
#payment-iframe | Iframe with id payment-iframe |
iframe[name="editor"] | Iframe with name attribute |
iframe[title="Chat"] | Iframe with title attribute |
iframe[src*="widget.example.com"] | Iframe whose src contains domain |
.ad-slot | Iframe with class ad-slot |
Best Practices
โ Do This:
// Enter the frame with a specific, stable selector
const frame = page.frameLocator('#payment-iframe'); // โ
await frame.getByLabel('Card number').fill('4242');
// Chain frameLocator calls for nested iframes
const inner = page.frameLocator('#outer').frameLocator('#inner'); // โ
// Use .first() explicitly when multiple iframes match
const ad = page.locator('.ad-slot').first().contentFrame(); // โ
// Use frameLocator for interactions; Frame API only for URL/evaluate
const frame = page.frameLocator('iframe[title="Editor"]'); // โ
await frame.getByRole('button', { name: 'Save' }).click();
// Target cross-origin iframes the same way as same-origin ones
const external = page.frameLocator('iframe[src*="external.com"]'); // โ
// Assert on frame content with the same expect API
await expect(frame.getByText('Success')).toBeVisible(); // โ
โ Don’t Do This:
// Don't use page.locator() for elements inside an iframe
await page.locator('#card-number').fill('4242'); // โ element is inside iframe
// Don't use positional selectors that break when iframes reorder
const frame = page.frameLocator('iframe').nth(0); // โ fragile
// Don't resolve the Frame object once and reuse it across navigation
const frame = page.frame({ name: 'editor' }); // โ stale after frame reload
await frame.fill('#input', 'text'); // โ may fail
// Don't call frameLocator without a selector when multiple iframes exist
page.frameLocator().getByRole('button'); // โ ambiguous across frames
// Don't assume page.frame() auto-waits for the iframe to load
const frame = page.frame({ url: /widget/ }); // โ returns null if not loaded
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Element not found despite being visible | Used page.locator() on iframe content | Use page.frameLocator(selector) |
| frameLocator operation throws | Selector matches multiple iframes | Add .first() or use a more specific selector |
| Stale frame reference | Reused page.frame() after iframe reloaded | Use frameLocator() or re-acquire the frame |
| Nested iframe unreachable | Skipped a level in the chain | Chain frameLocator() once per level |
| Cross-origin frame inaccessible | Attempted JavaScript contentDocument access | Use frameLocator(), which bypasses same-origin policy |
| URL verification fails | FrameLocator has no url() method | Use page.frame({ url: /pattern/ }) for URL access |
Real-World Examples
1. Filling a credit card form inside a payment iframe
const payment = page.frameLocator('#stripe-card-element');
await payment.getByLabel('Card number').fill('4242424242424242');
2. Clicking a button in a nested preview iframe
const inner = page.frameLocator('#editor').frameLocator('#preview');
await inner.getByRole('button', { name: 'Refresh' }).click();
3. Verifying a cross-origin widget loaded
const widget = page.frameLocator('iframe[src*="widget.example.com"]');
await expect(widget.getByText('Connected')).toBeVisible();
4. Using contentFrame() for a locator-based iframe
const frame = page.locator('iframe[name="chat"]').contentFrame();
await frame.getByPlaceholder('Type a message').fill('Hello');
5. Checking the frame URL with the Frame API
const frame = page.frame({ url: /analytics\.example\.com/ });
expect(frame?.url()).toContain('analytics.example.com');
6. Resolving multiple matching iframes
const firstAd = page.locator('.ad-slot').first().contentFrame();
await expect(firstAd.getByRole('link')).toBeVisible();
7. Selecting an iframe by title
const support = page.frameLocator('iframe[title="Support chat"]');
await support.getByRole('button', { name: 'Start chat' }).click();
8. Running evaluate() inside a frame
const frame = page.frame({ name: 'editor' });
const title = await frame!.evaluate(() => document.title);
expect(title).toBe('Editor');
9. Waiting for frame navigation after a click
const navPromise = page.waitForEvent('framenavigated', {
predicate: (f) => f.url().includes('/reports'),
});
await page.frameLocator('#editor').getByRole('link', { name: 'Reports' }).click();
await navPromise;
10. Extracting text from inside an iframe
const total = await page.frameLocator('#payment').locator('.total').textContent();
expect(total).toBe('$49.99');
Visual
The Document Boundary
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MAIN DOCUMENT vs IFRAME DOCUMENT โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Main Document โ โ
โ โ โ โ
โ โ <body> โ โ
โ โ <h1>Checkout</h1> โ โ
โ โ <div id="payment-iframe"> โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ โ IFRAME DOCUMENT (separate) โ โ โ
โ โ โ โ โ โ
โ โ โ <input id="card-number"> โ โ โ
โ โ โ <button>Pay now</button> โ โ โ
โ โ โ โ โ โ
โ โ โ page.locator() cannot see this โ โ โ
โ โ โ frameLocator() can โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ </div> โ โ
โ โ </body> โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ page.locator('#card-number') โ NOT FOUND โ
โ page.frameLocator('#payment-iframe') โ
โ .getByLabel('Card number') โ FOUND โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Nested Iframe Chaining
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ REACHING A NESTED IFRAME ELEMENT โ
โ โ
โ Main Page โ
โ โโโ iframe#editor-outer โ
โ โโโ iframe#preview-inner โ
โ โโโ <button>Refresh</button> โ
โ โ
โ page.frameLocator('#editor-outer') โ
โ .frameLocator('#preview-inner') โ
โ .getByRole('button', { name: 'Refresh' }) โ
โ โ
โ Level 1: enter outer iframe document โ
โ Level 2: enter inner iframe document โ
โ Level 3: locate button in innermost document โ
โ โ
โ Each frameLocator call scopes one level deeper. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
FrameLocator vs Frame API
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WHEN TO USE WHICH โ
โ โ
โ frameLocator() page.frame() โ
โ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ โ
โ Lazy resolution Eager resolution โ
โ Auto-waits No auto-wait โ
โ Full getBy* API Element handles โ
โ Cross-origin OK URL matching โ
โ No URL access URL available โ
โ No evaluate() evaluate() works โ
โ โ
โ Use for: Use for: โ
โ โข Clicking โข Checking URL โ
โ โข Filling โข Running JS โ
โ โข Asserting โข Frame navigation โ
โ โข Any interaction โข Frame lifecycle โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Enter a frame | page.frameLocator('iframe-selector') |
| Nested frames | .frameLocator() chained per level |
| Locator methods inside frame | getByRole, getByLabel, locator, etc. |
| Multiple matching frames | .first().contentFrame() |
| Convert Locator to FrameLocator | locator.contentFrame() |
| Convert FrameLocator to Locator | frameLocator.owner() |
| Frame URL access | page.frame({ url }) โ frame.url() |
| JS execution inside frame | page.frame({ name }) โ frame.evaluate() |
| Cross-origin frames | Same as same-origin with frameLocator() |
| Strictness | Throws if selector matches multiple iframes |
Key takeaways:
- Iframes are separate documents.
page.locator()resolves only against the main document. Any element inside an<iframe>requires an explicitframeLocator()entry, regardless of how visible it appears on screen. frameLocator()is lazy and auto-waiting. It does not resolve the iframe until a method is called, and it waits for the iframe to be ready before acting. This makes it resilient to late-loading frames and SPA re-renders, unlike the eagerpage.frame()API.- Nesting requires chaining. An iframe inside an iframe requires two
frameLocator()calls, one per level. Skipping a level searches the wrong document and fails. - Strictness prevents silent mistakes. If a selector matches multiple iframes, the operation throws rather than guessing. Apply
.first()to the iframe locator when the first match is intentionally desired, or use a more specific selector. - Cross-origin frames work transparently. Playwright’s protocol-level access bypasses the same-origin policy that blocks page JavaScript.
frameLocator('iframe[src*="external.com"]')works identically to a same-origin frame. - Use the Frame API only when needed.
frameLocator()covers interaction and assertion. Reach forpage.frame({ url })only when you need the frame’s URL, want to runevaluate(), or need to wait for frame navigation events.
Remember: Every iframe is a wall that page-level locators cannot cross. frameLocator() is the door. It knows how to find the iframe, wait for it to load, and hand back a scoped locator that behaves exactly like a page locator inside that document. Chain it for nesting, add .first() when frames are ambiguous, and trust it for cross-origin content that would defeat JavaScript-based approaches. Once inside, the locator API is unchangedโthe frame is just another document, and Playwright treats it with the same auto-waiting, strictness, and resilience as the main page.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!