Frame Handling and Multi-Window Handling in Playwright

Frame Handling

In Playwright, the recommended and simplest way to interact with elements inside an iframe is by using frameLocator.

Basic Example

await page.frameLocator('iframe').locator('.userId').click();


This approach automatically waits for the frame and the element inside it.

Frame-Related Methods

Methods

Example

Purpose

page.frames()

const frames = page.frames();

Returns an array of all frames on the page.

page.frame({ name })

const f = page.frame({ name: 'myFrame' });

Gets a frame by its name attribute.

page.frame({ url: /partial-url/ })

const f = page.frame({ url: /example\.com/ });

Gets a frame by matching its URL.

page.frameLocator(selector)

const frameLocator = page.frameLocator('#frameId');

Preferred way to work with frames using locators.

frameLocator.locator(selector)

const title = frameLocator.locator('h1');

Creates a locator scoped inside the frame.

frame.name() / frame.url()

const name = f.name(); const url = f.url();

Retrieves frame metadata.


Multi-Window Handling

Handling a New Tab or Window

const [newPage] = await Promise.all([
  page.context().waitForEvent('page'),
  page.getByText('Open New Tab').click()
]);
await newPage.waitForLoadState();


Use this when clicking a link or button opens a new tab or window.

Handling a Popup

const popup = await page.waitForEvent('popup');
await popup.waitForLoadState();


This is useful when the application opens a popup window using window.open().

Switching Between Tabs

// We are currently on the original tab
// Clicking a button that opens a new tab
const [newTab] = await Promise.all([
  page.context().waitForEvent('page'),
  page.getByRole('button', { name: 'Open New Tab' }).click()
]);
// Wait until the new tab is fully loaded
await newTab.waitForLoadState();
// Perform actions in the new tab
await newTab.getByRole('button', { name: 'Confirm' }).click();
// Close the new tab after completing actions
await newTab.close();
// Bring focus back to the original tab
await page.bringToFront();


Explanation

     - waitForEvent('page') ensures Playwright waits for the new tab instead of guessing with indexes.
     - Promise.all() prevents race conditions between the click and tab creation.
     - bringToFront() explicitly switches control back to the original tab.
     - Avoids using pages()[1], which can break if tab order changes.

Related Tutorials