Automation with playwright - Part 6 Handling Frames and Iframes
Playwright: Handling Frames and Iframes
In web pages, frames or iframes embed another HTML page inside a parent page.
Get Total Frames on the Page
// Returns all frames loaded in the current page.
const allFrames = page.frames();
console.log("Number of frames:", allFrames.length);
Access a frame
To interact with elements inside a frame, you must first switch to the frame context. 2 ways
Approach 1: Using page.frame()
page.frame()
locates a specific frame usingname
orurl
.
Example: Access frame by URL and fill input inside it
// Use regex in `url` to match partial URLs
const frame1 = await page.frame({ url: /frame1.html/ });
await frame1.fill('[name="mytext1"]', 'Hello');
Approach 2: Using frameLocator()
Use this when you want to locate a frame by its CSS selector or XPath.
Example: Locate input inside a frame and fill
const inputBox = page
.frameLocator('iframe[src="frame1.html"]')
.locator('[name="mytext1"]');
frameLocator(...)
identifies the frame using a selector..locator(...)
finds the target element inside the frame.
Summary
Use Case | Method | Key Input |
---|---|---|
Frame with known URL | page.frame() | { url: /.../ } |
Frame with name | page.frame() | { name: '...' } |
Frame via selector | frameLocator() | 'iframe[src="..."]' |
Always await
frame methods. Never interact with elements inside a frame without switching context first.