Last active
January 11, 2022 22:25
-
-
Save victoralvesf/4bb00222f7fd41802d7c5505355b2b7e to your computer and use it in GitHub Desktop.
[PUPPETEER] - Dealing with new tabs after click in a target _blank anchor.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const puppeteer = require("puppeteer"); | |
| async function waitFor(time) { | |
| return new Promise((r) => setTimeout(r, Number(time))); | |
| } | |
| (async () => { | |
| const browser = await puppeteer.launch({ | |
| headless: false, | |
| }); | |
| // First page | |
| const page1 = await browser.newPage(); | |
| await page1.goto("https://www.npmjs.com/package/puppeteer"); | |
| await page1.waitForSelector("a[aria-labelledby=repository]"); | |
| const link = await page1.$("a[aria-labelledby=repository]"); | |
| // First method | |
| const newPagePromise = new Promise((x) => { | |
| return browser.on("targetcreated", (target) => x(target.page())); | |
| }); | |
| await link.click(); | |
| // Second page | |
| const page2 = await newPagePromise; | |
| await page2.bringToFront(); | |
| await waitFor(3000); | |
| await page2.waitForSelector(".Layout-sidebar span a.text-bold"); | |
| const link2 = await page2.$(".Layout-sidebar span a.text-bold"); | |
| // Newer/best method | |
| const [page3] = await Promise.all([ | |
| new Promise((resolve) => page2.once("popup", resolve)), | |
| link2.click(), | |
| ]); | |
| // Bringing the third page to front | |
| await page3.bringToFront(); | |
| await waitFor(3000); | |
| // Getting opened tabs [] | |
| let pages = await browser.pages(); | |
| // Going back to first page | |
| await pages[1].bringToFront(); | |
| await waitFor(3000); | |
| // Closing the second and third pages. | |
| await Promise.all([pages[2].close(), pages[3].close()]); | |
| await waitFor(3000); | |
| await browser.close(); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment