Search code examples
javascriptnode.jsgoogle-chromechromiumpuppeteer

With Puppeteer: How can I get an iframe from its parent element selector?


I want to get an iframe as frame and click an element in the frame, but the iframe does not have a name and the website has many frames (page.frames() returns 14).

And I don't have permission to edit html. I can only edit the JavaScript.

I think the best way to identify the iframe in this case is from its parent element.

How can I do this with puppeteer?

<div id="foo">
  <iframe>
    #document
  </iframe>
</div>

Solution

  • You can use the elementHandle.contentFrame() function to return a frame from an element handle.

    Quote from the docs:

    Resolves to the content frame for element handles referencing iframe nodes, or null otherwise

    Example:

    const elementHandle = await page.$('div#foo iframe');
    const frame = await elementHandle.contentFrame();