GyaaniGuy

- self made 💻 😎

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 using name or url.

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 CaseMethodKey Input
Frame with known URLpage.frame(){ url: /.../ }
Frame with namepage.frame(){ name: '...' }
Frame via selectorframeLocator()'iframe[src="..."]'

Always await frame methods. Never interact with elements inside a frame without switching context first.


dated April 2025