I have some elements in my page which are sometimes in iFrame, sometimes don't. They have the same id to identify them in both cases.
What is the best and quickly way to find them in page or iFrame ?
I currently use this code which works when elements are in the iFrame, but which doesn't work if the element are simply in the page. I thought the mainFrame would be the "currentPage" outside the iFrame, but it seems the code search only in iFrames, not outside.
async function recursiveFindInFrames(inputFrame, selector) {
const frames = inputFrame.childFrames();
const results = await Promise.all(
frames.map(async frame => {
const el = await frame.$(selector);
if (el) return el;
if (frame.childFrames().length > 0) {
return await recursiveFindInFrames(frame, selector);
}
return null;
})
);
return results.find(Boolean);
}
async function findInFrames(page, selector) {
const result = await recursiveFindInFrames(page.mainFrame(), selector);
if (!result) {
console.log('The selector ',selector,' could not be found in any child frames.')
}
return result;
}
...
//Element that could be in an iFrame, or not
const element = await findInFrames(page2, 'input[name="myField"]');
await element.click();
...
from Puppeter find element in current page OR iFrame
No comments:
Post a Comment