Interacting with iframes

Puppeteer and Playwright enable us to access and interact with iframes.

Locate an iframe and its elements

To access iframe elements, locate the iframe and query the DOM elements as if you’re in the page context.

const { chromium } = require('playwright')

;(async () => {
  const browser = await chromium.launch()
  const context = await browser.newContext()
  const page = await context.newPage()

  await page.goto('')

  const header = await page.frameLocator('iframe').locator('h1')
  console.log(await header.innerText())

  await browser.close()

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('')

  const iframeHandle = await page.$('iframe')
  const iframe = await iframeHandle.contentFrame()
  const heading = await iframe.$('h1')

  console.log(await heading.evaluate((el) => el.innerText))

  await browser.close()

Further reading

  1. Playwright’s “Frames documentation”

Last updated on May 3, 2024. You can contribute to this documentation by editing this page on Github