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
- Find the iframe using frameLocator.
- Chain a locator inside that frame.
- Perform the action or assertion inside the frame context.
- 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
- What is frameLocator used for?
- How is an iframe different from a normal page element?
- How do you click a button inside an iframe?
- 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.