'How do I open a new window page from a button in Puppeteer?

I'm trying to open a new window page from a button in Puppeteer.

An example given: I'm logging to a website and the moment I click the button for the login a new fresh window page will pop-up, redirecting to the site the button is meant to be going. How can I do it?



Solution 1:[1]

You can do that by simply pressing Shift button while doing page.click And to catch the newly opened window you can use waitForTarget.

const puppeteer = require('puppeteer')

;(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
    })
    const context = browser.defaultBrowserContext()
    const page = (await context.pages())[0]
    await page.goto('https://www.amazon.com/gp/product/B093GQSVPX/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1', {waitUntil: 'load'})
    await page.waitForSelector('a[title="Add to List"]', {visible: true})
    await page.keyboard.down('Shift')
    await page.click('a[title="Add to List"]')
    await page.keyboard.up('Shift')
    const popup = await browser.waitForTarget(
        (target) => target.url().includes('www.amazon.com/ap/signin')
    )

    const popupPage = await popup.page()
    await popupPage.waitForSelector('a.a-link-expander[role="button"]')
    await popupPage.click('a.a-link-expander[role="button"]')
    await popupPage.click('input#continue[type="submit"]')
    await browser.close()
})()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1