Frames and Files

Frame Locator in Playwright

Frame Locator in Playwright: definition, iframe usage, scoped examples, common mistakes, interview notes, and practice.

Definition and Brief Explanation

Definition: A frame locator targets elements inside an iframe by first identifying the frame and then locating content inside it.

Explanation: Iframes have their own document context, so normal page locators cannot always reach their internal elements directly. frameLocator keeps the test readable by clearly saying: first enter this frame, then find this element inside it.

Why It Matters

  • It allows tests to work with iframe content that lives in a separate document.
  • It keeps frame interactions readable and scoped.
  • It avoids brittle JavaScript workarounds for embedded payment, chat, analytics, or widget flows.
  • It helps when the same element names exist both outside and inside the frame.

How It Works

  1. Find the iframe using frameLocator.
  2. Chain a locator inside that frame.
  3. Perform the action or assertion inside the frame context.
  4. Assert an outcome inside the frame or on the parent page.

Syntax and Examples

Example 1: Frame locator

const frame = page.frameLocator('#payment-frame');
await frame.getByLabel('Card number').fill('4111111111111111');

Explanation: Targets elements inside an iframe without manual context switching.

Common Mistakes

  • Using page.locator for content that is inside an iframe.
  • Targeting the iframe by fragile position instead of a stable selector.
  • Forgetting that cross-origin frames can behave differently.
  • Mixing popup handling and frame handling as if they are the same thing.

Interview Notes

  1. What is frameLocator used for?
  2. How is an iframe different from a normal page element?
  3. How do you click a button inside an iframe?
  4. What makes iframe tests flaky?

Practice Task

Create a page with an iframe, locate a button inside it with frameLocator, click it, and assert the result inside the frame.