Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 35 ยท Actions and Assertions

Iframes, New Tabs and Dialogs

Test embedded iframes, popups, new tabs, alert and confirm dialogs and shadow DOM in Cypress and Playwright, and learn where each tool has limits.

Real pages are not one flat document. A payment form lives in an iframe from another company, a link opens a receipt in a new tab, "Delete" asks for confirmation through a dialog, and a design-system component hides its buttons inside a shadow root. Each of these creates a boundary the test must cross, and this is where Cypress and Playwright differ most, because of how they are built.

This lesson shows how to cross each boundary in both tools, explains why Cypress has hard limits with tabs and cross-origin frames while Playwright does not, and ends with a model of nested contexts you can run. It assumes you know locators (Locators in Playwright, Selecting Elements in Cypress). The architectural reason for the differences is explained in Cypress vs Playwright.

Real versus stand-in. The Cypress (js) and Playwright (ts) code in static blocks is real and read-only: the site cannot open browser tabs or load third-party frames. The runnable example is a model of nested contexts (frames, shadow roots, tabs, dialogs) with two simplified "drivers". It illustrates the rules; it is not either tool's implementation.

Why boundaries matter

The browser enforces the same-origin policy: JavaScript running in one page cannot read the contents of a frame from a different origin (a different scheme, host or port). Cypress runs its test code inside the browser, next to your app, so it inherits those limits. Playwright drives the browser from outside through a protocol, so it can reach into any frame, tab or open shadow root that the browser itself can render.

flowchart TD
  T["Top page: shop.test"] --> A["iframe: promo<br/>(shop.test, same origin)"]
  T --> B["iframe: payment<br/>(pay.test, cross origin)"]
  T --> S["theme-switch element<br/>with a shadow root"]
  T --> P["Popup tab: receipt"]
  T --> D["Dialog: confirm(...)"]

Five kinds of boundary a test may need to cross.

Iframes in Playwright

Playwright treats a frame as just another scope. frameLocator() returns a locator that is scoped inside the frame, and everything else works as usual, including auto-waiting for the frame to load.

TypeScript
const payment = page.frameLocator('iframe[name="payment"]');

await payment.getByLabel('Card number').fill('4242 4242 4242 4242');
await payment.getByLabel('Expiry').fill('12 / 30');
await payment.getByRole('button', { name: 'Pay now' }).click();

await expect(page.getByRole('heading', { name: 'Thank you' })).toBeVisible();

// Nested frames: chain frameLocator calls
const widget = page.frameLocator('#outer').frameLocator('#inner');
await widget.getByText('Loaded').waitFor();

Cross-origin frames work the same way. Use the frame's name, title or test attribute to find the <iframe> element, then locate inside it. (The lower-level page.frame({ name: 'payment' }) returns a Frame object you can query directly, which is handy when you need its URL.)

Third-party payment frames are a special case: test cards and sandbox environments exist for that reason. Do not enter real card numbers into any test, and prefer your payment provider's documented test mode.

Iframes in Cypress

Cypress has no built-in iframe command. For a same-origin frame you reach into the frame's document yourself and wrap the body, so that further Cypress commands can chain from it:

JavaScript
const getIframeBody = (selector) =>
  cy.get(selector)
    .its('0.contentDocument.body')
    .should('not.be.empty')        // waits until the frame has loaded
    .then(cy.wrap);

getIframeBody('iframe[name=promo]').find('[data-cy=close]').click();

Many teams put this in a custom command. For a cross-origin frame, the browser blocks access to contentDocument, so the snippet fails. The usual options are to disable web security for Chromium-family browsers (chromeWebSecurity: false in the Cypress config), to test the third-party piece at its own level (their sandbox or your own contract tests), or to stub the integration in your app during the test. Note that cy.origin() solves a different problem: it lets a test continue after the top-level page navigates to another origin (for example an identity provider login), and it does not open up a cross-origin iframe.

New tabs and popups

Playwright models each tab as a Page inside a browser context. When something opens a tab, you wait for the event, and you must start waiting before the click:

TypeScript
const popupPromise = page.waitForEvent('popup');
await page.getByRole('link', { name: 'Open receipt' }).click();
const receipt = await popupPromise;

await receipt.waitForLoadState();
await expect(receipt.getByRole('heading', { name: 'Receipt' })).toBeVisible();
await receipt.close();
// `page` is still the original tab and still usable.

A test can have many pages at once (context.pages()), and a context can also listen for page events for tabs opened from any page.

Cypress runs inside a single tab and cannot switch to another one. The common patterns avoid opening a second tab at all:

JavaScript
// 1. Remove target so the link opens in the same tab
cy.get('a[data-cy=receipt]').invoke('removeAttr', 'target').click();
cy.url().should('include', '/receipt/');

// 2. Or check the link's destination without following it
cy.get('a[data-cy=receipt]')
  .should('have.attr', 'href')
  .and('match', /\/receipt\/\d+/);

// 3. Or stub window.open and assert the call
cy.window().then((win) => cy.stub(win, 'open').as('open'));
cy.get('[data-cy=print]').click();
cy.get('@open').should('have.been.calledWith', '/receipt/17');

Such tests prove that the link is correct but not that the new tab renders; if that matters, cover it with Playwright or a manual check.

Dialogs: alert, confirm and prompt

Native dialogs block the page until someone answers. The two tools handle them differently by default:

  • Cypress auto-accepts alert and confirm and logs them. To assert on the message or to answer "Cancel", listen for the event:
JavaScript
cy.on('window:confirm', (message) => {
  expect(message).to.equal('Delete this order?');
  return false;                     // false means Cancel
});
cy.get('[data-cy=delete]').click();
cy.get('[data-cy=order]').should('exist');   // nothing was deleted

cy.on('window:alert', (message) => {
  expect(message).to.contain('Saved');
});
  • Playwright automatically dismisses dialogs if no listener is registered, which means a confirm returns false. Register a handler to accept, or to read the message:
TypeScript
page.once('dialog', async (dialog) => {
  expect(dialog.type()).toBe('confirm');
  expect(dialog.message()).toBe('Delete this order?');
  await dialog.accept();            // dialog.dismiss() answers Cancel
});
await page.getByRole('button', { name: 'Delete' }).click();
await expect(page.getByTestId('order')).toHaveCount(0);

// A prompt takes an answer:
page.once('dialog', (dialog) => dialog.accept('Ada'));

Register the handler before the action that triggers the dialog, and use once unless you want it for every dialog. Custom HTML modals (a <dialog> element or a div role="dialog") are not native dialogs: treat them like any other element and find them with getByRole('dialog').

Shadow DOM

Web components can hide their internals inside a shadow root. In Playwright, role, text, label and CSS locators automatically see into open shadow roots, so page.getByRole('button', { name: 'Toggle dark mode' }) simply works (XPath does not pierce them, and closed roots are unreachable by design). In Cypress, shadow roots are opaque by default; enable them for the whole project or for one query:

JavaScript
// cypress.config.js
module.exports = defineConfig({ e2e: { includeShadowDom: true } });

// or per command
cy.get('theme-switch').shadow().find('button').click();
cy.get('button', { includeShadowDom: true }).contains('Toggle dark mode');

A model of nested contexts

The stand-in below builds a page as a tree: a main frame, a same-origin promo frame, a cross-origin payment frame, and some text that sits in a shadow root. Two drivers try to reach the same elements. The in-page driver stops at cross-origin frames and cannot see shadow content (like Cypress with default settings). The protocol driver can reach everything (like Playwright). A small Browser class models tabs, and dialog() models a handler. Run it and compare the two driver sections.

JS Reaching through frames, tabs and dialogs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output reproduces the rules above. The in-page driver reads the same-origin promo frame but fails on payment with a security error and does not find the shadow text. The protocol driver finds all four. In the tab section, the promise for the popup is created before the click that opens it, which is the real-life ordering you must follow. In the dialog section, the unhandled confirm is dismissed (Playwright's default), and the handler turns it into an accept. Cypress would auto-accept the unhandled one instead; the model follows Playwright for brevity.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can Playwright interact with a cross-origin iframe when Cypress's in-page approach cannot?

    Cypress runs test code in the page and is bound by the same-origin policy. Playwright drives the browser over a protocol from outside, so it can reach frames the browser renders.
  2. 2. What does cy.origin() do?

    cy.origin() handles top-level navigation across origins, such as an identity provider login. It does not make a cross-origin iframe accessible.
  3. 3. When should the popup wait be created in Playwright?

    waitForEvent('popup') returns a promise. Create it first, click, then await it, otherwise the event may fire before you are listening.
  4. 4. If no dialog handler is registered, what does Playwright do with a confirm()?

    Unhandled dialogs are dismissed automatically. Register page.once('dialog', ...) before the triggering click to accept it or inspect the message.

Summary

  • Frames, tabs, dialogs and shadow roots are boundaries; the tool's architecture decides how easily you cross them.
  • Playwright: frameLocator() for iframes (any origin), waitForEvent('popup') for tabs, page.once('dialog') for native dialogs, and open shadow roots are pierced automatically.
  • Cypress: same-origin frames need a body-wrapping helper, cross-origin frames are limited, a second tab is not reachable (remove target, check href, or stub window.open), dialogs use cy.on('window:confirm'), and shadow DOM needs includeShadowDom.
  • Register listeners before the action that triggers the event, and use test modes for third-party widgets such as payments.
  • The nested-context model is a teaching sketch of these rules, not either tool's code.

Next: How Cypress Commands Really Work.