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
Use this when clicking a link or button opens a new tab or window.
Handling a Popup
This is useful when the application opens a popup window using window.open().
Switching Between Tabs
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.