How to capture dynamic content from element inside an iFrame?

1.6k Views Asked by At

When I try to capture text from an element inside an iFrame where the element content changes every second, I get "undefined". What might I be doing wrong?

Code:

const { firefox } = require('playwright');
const fs = require('fs');
var url = 'http://jsfiddle.net/6vnam1jr/1/show';
var section_path = 'xpath=/html/body/div/div/div/section';
var iframe_path = 'xpath=/html/body/div/iframe';
var text_path = 'xpath=//html/body/div[2]/div[2]';
async function getElementText(browser,page){
  await page.goto(url);
  await page.click(section_path);
  
  const frame = await page.$(iframe_path);
  const contentFrame = await frame.contentFrame();
  await sleep(1000);
  let handle = await contentFrame.$eval(text_path);
  console.log(handle)
  
  // try again
  await sleep(1000);
  handle = await contentFrame.$eval(text_path);
  console.log(handle)
  
  closeBrowser(browser);
}
async function closeBrowser(browser){
  await browser.close();
}
function sleep(ms) {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
}
(async () => {
  const browser = await firefox.launch({ headless: false });
  const page = await browser.newPage();
  getElementText(browser,page);
})();```
1

There are 1 best solutions below

0
On BEST ANSWER

Thanks for the repro. frame.$eval is an API to run a JS function in the browser which takes the element as an argument.

I believe what you are looking for is an ElementHandle to this element. You can use frame.waitForSelector or frame.$ for this purpose. I have verified that they are not undefined.

// ...
let handle = await contentFrame.waitForSelector(text_path);