How to click elements within pop-up/new tab windows in Puppeteer

Viewed 2929

I have used the following example to target a pop-up window/newtab, but the methods available to me after the fact are limited. I can only really do things like capture the URL and close the tab (among other things).

What I am trying to do is interact with a google/twitter sign in pop-up, but puppeteer doesn't seem to have a solution for multiple window handles, at least when trying to interact as in click elements.

const newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page()));
await page.click('my-link'); //Opens pop-up window
const newPage = await newPagePromise;

I'm looking to have something like this (in addition to the code written above):

const element = await newPage.$(selector);
await element.click();

This does not work. Has anyone else had this need?

1 Answers

Take this with a grain of salt. I'm working with puppeteer in a way that the api documentation doesn't recommend, so I had to translate some of what you see below.

I'm happy to answer any additional questions.

All in all, this solution permits you to open a new tab/pop-up, and interact with that tab/pop-up. I was even able to close the pop-up and switch back to the originating page, which is not mentioned below.

const newPagePromise = getNewPageWhenLoaded()
await page.click('my-link'); //Opens pop-up window
const newPage = await newPagePromise;
newPage = newPage.mainFrame();
const element = await newPage.waitForSelector('img');
newPage.click(element);

function getNewPageWhenLoaded() {
    return new Promise((x) => browser.once('targetcreated', async (target) => {
        const newPage = await target.page();
        const newPagePromise = new Promise(() => newPage.once('domcontentloaded', () => x(newPage)));
        const isPageLoaded = await newPage.evaluate(() => document.readyState);
        return isPageLoaded.match('complete|interactive') ? x(newPage) : newPagePromise;
    }));
}
Related