When a frame is nested inside another iframe (aka a child frame), you’ll need to access the parent frame first, then drill down into the children.
How Child Frames Work in Playwright
Every Frame object in Playwright has a method called .childFrames() that returns an array of its direct child frames. You can use this to navigate deeper.
Example
Let’s say you have a structure like this:
<iframe name="parentFrame"> <!-- Inside parentFrame --> <iframe name="childFrame"></iframe> </iframe>
Here is the below example to handle child object in playwright.
const parent = await page.frame({ name: 'parentFrame' }); // Get all child frames const children = parent.childFrames(); // Optionally, find one by name const child = children.find(frame => frame.name() === 'childFrame'); // Interact with the child frame await child.click('#someButton');
OR
const parent = await page.frame({ name: 'parentFrame' }); // Get all child frames const children = parent.childFrames(); // Interact with the child frame await child[0].click('#someButton');
✅ Recursively Navigating Nested Frames
If the nesting is deeper, you can recurse through .childFrames() like this:
function findFrameByName(frame, name) { if (frame.name() === name) return frame; for (const child of frame.childFrames()) { const found = findFrameByName(child, name); if (found) return found; } return null; } const rootFrames = page.frames(); const desiredFrame = rootFrames.map(f => findFrameByName(f, 'childFrame')).find(Boolean); await desiredFrame.click('#deepButton');
✅ Alternative via elementHandle
If you're not sure about the frame names, another approach is to get the <iframe> element itself and access the frame:
const iframeHandle = await page.waitForSelector('iframe#parentFrame'); const parentFrame = await iframeHandle.contentFrame(); const childHandle = await parentFrame.waitForSelector('iframe#childFrame'); const childFrame = await childHandle.contentFrame(); await childFrame.click('button#doSomething');
No comments:
Post a Comment