How to handle frames in Puppeteer?


We can handle frames in Puppeteer. The frames in an html code are represented by the frames/iframe tag. Puppeteer can handle frames by switching from the main page to the frame. To work with elements inside a frame, first, we have to identify the frame with the help of locators. The method contentFrame is used to access the elements inside the frame.

Syntax

const f = await page.$("frame[name='frame-bottom']")
const m = await f.contentFrame()

Let us see the html code of an element inside a frame and obtain the text - BOTTOM inside it.

The tagname highlighted in the above image is frame and the value of its name attribute is frame-bottom.

Example

Code Implementation

//Puppeteer library
const pt= require('puppeteer')
async function frameHandle(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://the-internet.herokuapp.com/nested_frames')
   //identify frame
   const f = await page.$("frame[name='frame-bottom']")
   //move to frame
   const x = await f.contentFrame();
   //identify element inside frame
   const n = await x.$("body")
   //get text
   const v = await (await n.getProperty("textContent")).jsonValue()
   console.log(v)
}
frameHandle()

Output

Updated on: 19-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements