When a click opens a new tab, create the context.waitForEvent('page') promise before the click. If the tab opens before the listener registers, the event is gone and the call waits until the test times out. The Page you get back may still be loading, so call waitForLoadState() before reading its state with title() or url().

Key takeaways

  • Create the promise for a new tab before the click that opens it. The event fires once, and a listener added later never sees it, so the test sits there until its timeout.
  • A new Page can exist before it has loaded. Call waitForLoadState() before title() or url(), which return the current value at once. Locator actions and expect retry and need no such wait.
  • Tabs in one context share cookies and storage. To simulate a second user, create another context with browser.newContext().
  • frameLocator() takes the selector of the <iframe> element itself and chains for nested frames. Separate iFrames, such as the card number, expiry and CVC fields of Stripe, each need their own call.
  • When a popup closes itself after a click (an OAuth window, for instance), create the close promise before that click, or the event can be missed.

How Playwright models pages, contexts, and tabs

A Browser is the browser process. A BrowserContext is an isolated session within that browser, with its own cookies, storage, and network state. A Page represents a single tab or window within a context. When a user clicks a link that opens a new tab, Playwright sees that as a new Page being added to the existing BrowserContext.

import { chromium } from '@playwright/test';

const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage(); // Tab 1

const page2 = await context.newPage(); // Tab 2 in the same session

In practice:

  • Pages in the same context share Cookies and localStorage in Playwright: Read, Set, and Test. If page 1 is logged in, page 2 is also logged in.
  • Pages in different contexts are completely isolated. This is why Playwright uses separate contexts to simulate multiple users.
  • When you need to intercept events across all tabs (not just one), use context.on() and context.route(), not page.on() and page.route().

Detecting a new tab with context.waitForEvent('page')

A click on a link or button often opens a new tab, and the test needs a reference to it.

Set up the listener before the action that opens the tab. If you click first, the page event can fire before the listener is in place.

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

test('handles a new tab opened by a link click', async ({ page, context }) => {
  await page.goto('https://lab.becomeqa.com');

  // Set up the listener BEFORE clicking
  const newPagePromise = context.waitForEvent('page');

  // This click opens a new tab
  await page.getByRole('link', { name: 'Open in new tab' }).click();

  // Wait for the new page and let it load
  const newPage = await newPagePromise;
  await newPage.waitForLoadState('domcontentloaded');

  // Now interact with the new tab
  await expect(newPage).toHaveURL(/\/docs/);
  await expect(newPage.getByRole('heading', { level: 1 })).toBeVisible();

  // The original page is still accessible
  await expect(page).toHaveURL('https://lab.becomeqa.com');
});

context.waitForEvent('page') returns a promise that resolves with the new Page once it exists, which can be before it has finished loading. Call waitForLoadState() before title(), url() and other calls that return the current value at once. Locator actions and expect assertions retry on their own.

With await page.click(...) followed by await context.waitForEvent('page'), a fast tab opens between the two lines. The event is missed and the test hangs until its timeout.

Opening a new tab programmatically

To open a tab yourself, for example a specific URL next to the main page, call context.newPage(). A second user needs a separate context, because tabs in one context share a session.

test('two tabs in the same session', async ({ context }) => {
  const page1 = await context.newPage();
  const page2 = await context.newPage();

  await page1.goto('https://lab.becomeqa.com/dashboard');
  await page2.goto('https://lab.becomeqa.com/settings');

  // Both pages are in the same logged-in session
  await expect(page1.getByText('Welcome back')).toBeVisible();
  await expect(page2.getByRole('heading', { name: 'Account Settings' })).toBeVisible();

  // Bring page1 back into focus (matters for some browser-specific behaviors)
  await page1.bringToFront();
  await page1.getByRole('button', { name: 'New Trip' }).click();
});

bringToFront() activates the tab in the browser UI. Headless runs rarely need it, but a test that depends on which tab has focus may.

Handling popup windows

A popup opened with window.open() is a new Page too, so the waitForEvent('page') pattern is the same.

test('handles an OAuth popup window', async ({ page, context }) => {
  await page.goto('https://lab.becomeqa.com/login');

  // Listen for the popup before clicking
  const popupPromise = context.waitForEvent('page');

  await page.getByRole('button', { name: 'Login with Google' }).click();

  const popup = await popupPromise;
  await popup.waitForLoadState('domcontentloaded');

  // Interact with the OAuth popup
  await popup.getByLabel('Email').fill('test@example.com');
  await popup.getByRole('button', { name: 'Next' }).click();
  await popup.getByLabel('Password').fill('testpassword');
  const closePromise = popup.waitForEvent('close');
  await popup.getByRole('button', { name: 'Sign in' }).click();

  // After OAuth completes, the popup closes and the main page updates
  await closePromise;
  await expect(page).toHaveURL(/\/dashboard/);
});

OAuth popups usually close by themselves when the flow ends. Wait for the popup's close event before asserting on the original page, and create that promise before the final click, since the popup can close right after it.

Waiting for a new tab to load

A link with target="_blank" opens a tab that then navigates to the link's URL, so the Page you receive may not have finished loading.

test('waits for navigation in a new tab', async ({ page, context }) => {
  await page.goto('https://lab.becomeqa.com');

  const newPagePromise = context.waitForEvent('page');
  await page.getByRole('link', { name: 'Documentation' }).click();

  const newPage = await newPagePromise;

  // Wait for the specific navigation to complete, not just DOMContentLoaded
  await newPage.waitForLoadState('load');

  // Now it's safe to assert on the URL and content
  await expect(newPage).toHaveURL(/\/docs\//);
  await expect(newPage.getByRole('navigation')).toBeVisible();
});

waitForLoadState('load'), the default, waits for images and scripts as well. 'domcontentloaded' returns sooner and is enough when you only need the HTML. Avoid 'networkidle'. The Playwright docs discourage it for tests and recommend assertions on what the page shows.

If you know the URL the new tab will reach, waitForURL() waits for exactly that:

const newPage = await newPagePromise;
await newPage.waitForURL('**/docs/getting-started');
await expect(newPage.getByRole('heading', { name: 'Getting Started' })).toBeVisible();

iFrames and frameLocator

An iFrame is a separate document embedded in the page, with its own DOM and JavaScript context. Playwright Locators: Which One to Use and When such as page.getByRole() and page.getByText() do not search inside it.

The older approach gets a Frame object first and calls locator methods on it.

// Old way: works but verbose
const frame = page.frame({ name: 'payment-widget' });
await frame?.getByLabel('Card Number').fill('4111111111111111');

frameLocator() returns a locator scoped to the iFrame's content, so you chain locators as you do on the main page.

test('fills out a payment form inside an iFrame', async ({ page }) => {
  await page.goto('https://lab.becomeqa.com/checkout');

  // Locate the iFrame by its selector, then chain locators inside it
  const paymentFrame = page.frameLocator('iframe[name="payment-widget"]');

  await paymentFrame.getByLabel('Card Number').fill('4111111111111111');
  await paymentFrame.getByLabel('Expiry Date').fill('12/28');
  await paymentFrame.getByLabel('CVV').fill('123');

  // Back on the main page for the submit button
  await page.getByRole('button', { name: 'Pay Now' }).click();

  await expect(page.getByText('Payment successful')).toBeVisible();
});

You can use any valid CSS selector in frameLocator(): iframe#checkout-frame, iframe[src*="stripe.com"], iframe.payment-container. Frame locators are strict, so an operation throws if the selector matches more than one iFrame.

Inspect the <iframe> element in DevTools. Its name, id, src and class attributes all work in a frameLocator() selector.

Nested iFrames

Some embeds put an iFrame inside another iFrame. Chain frameLocator() calls to reach the inner one.

test('interacts with a nested iFrame', async ({ page }) => {
  await page.goto('https://lab.becomeqa.com/checkout');

  // Outer iFrame
  const outerFrame = page.frameLocator('iframe#payment-container');

  // Inner iFrame nested inside the outer one
  const innerFrame = outerFrame.frameLocator('iframe#card-number-frame');

  await innerFrame.getByPlaceholder('Card number').fill('4111111111111111');

  // Back to the outer iFrame for expiry and CVV (different inner frames)
  const expiryFrame = outerFrame.frameLocator('iframe#expiry-frame');
  await expiryFrame.getByPlaceholder('MM / YY').fill('12/28');

  const cvvFrame = outerFrame.frameLocator('iframe#cvv-frame');
  await cvvFrame.getByPlaceholder('CVV').fill('123');
});

Stripe Elements renders the card number, expiry and CVC fields in separate iFrames, so each field needs its own frameLocator().

Cross-origin iFrames, which serve content from a different domain than the host page, work with frameLocator() without extra configuration.

Shadow DOM

Shadow DOM encapsulates the internal DOM of a web component. Unlike iFrames, it needs no special handling in Playwright, because locators search open shadow roots by default. XPath locators do not pierce shadow roots, and closed-mode shadow roots are not supported.

test('locates elements inside shadow DOM', async ({ page }) => {
  await page.goto('https://lab.becomeqa.com/components');

  // This works even if the button is inside a shadow root
  await page.getByRole('button', { name: 'Submit' }).click();

  // CSS selectors pierce open shadow roots too
  await page.locator('custom-login-form input[type="email"]').fill('user@example.com');
});

Prefer semantic locators (getByRole, getByLabel) over CSS paths, since they do not depend on the component's internal structure. For a shadow root inside an iFrame, chain frameLocator() to reach the iFrame's document first, then use the same locators.

Common mistakes

Reading page state before the tab loads. newPage.title() and newPage.url() return the current value at once, so right after waitForEvent('page') the title can be empty. Locator actions and expect assertions retry and need no such wait.

// Wrong: title() does not wait
const newPage = await newPagePromise;
console.log(await newPage.title()); // Might be empty

// Correct
const newPage = await newPagePromise;
await newPage.waitForLoadState('domcontentloaded');
console.log(await newPage.title());

Losing reference to the original page. After working in a new tab, tests sometimes assert on the wrong page variable. Give each page its own name and keep it.

test('loses track of the original page', async ({ page, context }) => {
  const originalPage = page; // Rename for clarity when working with multiple tabs

  const newPagePromise = context.waitForEvent('page');
  await originalPage.getByRole('link', { name: 'Terms' }).click();

  const termsPage = await newPagePromise;
  await termsPage.waitForLoadState('load');

  // Assert on terms page
  await expect(termsPage.getByRole('heading', { name: 'Terms of Service' })).toBeVisible();
  await termsPage.close();

  // Back to original. Explicitly use originalPage, not page.
  await expect(originalPage.getByRole('heading', { name: 'Sign Up' })).toBeVisible();
});

Using page.frames() when frameLocator() is available. The older page.frames() returns an array of Frame objects and forces you to manage frame indexes or names yourself. frameLocator() chains, so default to it unless you need a Frame object.

Calling frame() before the iFrame is attached. page.frame() returns null when no matching frame exists yet and does not wait. frameLocator() retries until it finds a match or times out.

FAQ

How do I get a popup and the page that opened it?

The context.waitForEvent('page') promise from this article resolves with any new page in the context, popups from window.open() included, and the opener stays available as page. page.waitForEvent('popup') fires only for popups opened by that one page.

Which load state should I wait for in a new tab?

load is the default and waits for images and scripts. domcontentloaded returns sooner and is enough when you need only the HTML. Skip networkidle, because the Playwright docs discourage it for tests.

Why does frameLocator() throw an error about several elements?

Frame locators are strict. The selector must match exactly one iFrame, or the operation throws. Narrow it with the name, id, src or class of the <iframe> element.

Do I need a special selector for shadow DOM?

Not for open shadow roots. Role locators and CSS selectors reach into them as on any page. XPath does not pierce them, and closed-mode shadow roots are not supported.

→ See also: Network Interception, Mocking, and Stubbing in Playwright | Page Object Model in Playwright: From Messy to Maintainable | Playwright Locators: Which One to Use and When | Waiting Strategies in Playwright: No More sleep() | How to Select a Dropdown Option in Playwright