I noticed that many people encounter difficulties if they need to work in several tabs. So I decided to write a short note on how to in puppeteer open link in new tab. The list of methods is not exhaustive, but all of them are easy to use.
New tab to go to famous url
If the link that we want to go to is known, then in this case it’s enough to create a new tab and open the link in it:
const puppeteer = require('puppeteer'); // puppeteer
const browser = await puppeteer.launch(); // run browser
const page1 = await browser.newPage(); // open new tab
await page1.goto('https://google.com'); // go to google.com
const page2 = await browser.newPage(); // open new tab
await page2.goto('https://github.com'); // go to github.com
await page2.bringToFront(); // make the tab active
...
await browser.close(); // close browser
In this example, we opened two pages (tabs): page1 and page2. On the first tab, we switched to https://google.com, on the second – to https://github.com. For further work, we indicate the required page and perform the necessary actions with it. If it is necessary to bring the tab to the foreground (activate the tab) – use the bringToFront () function.
Puppeteer open link in new tab
If the link is not known in advance or the transition must be carried out on a specific interactive object (element, button, etc.), then we need a selector. How to get it, we told earlier in this article.
const puppeteer = require('puppeteer'); // puppeteer
const browser = await puppeteer.launch(); // run browser
const page1 = await browser.newPage(); // open new tab
await page1.goto('https://google.com'); // go to google.com
await page1.waitForSelector('#fsl > a:nth-child(4)'); // wait load object
const link = await page1.$('#fsl > a:nth-child(4)'); // declare object
const newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page()))); // declare promise
await link.click({button: 'middle'}); // click middle button, link open in a new tab
const page2 = await newPagePromise; // declare new tab, now you can work with it
await page2.bringToFront(); // make the tab active
...
await browser.close(); // close browser
As in the previous example, we create a tab / page page1 and go to https://google.com. Next, we want to click on How Search Works and to open the page in a new tab. We recognize the selector of this object (in this case it is ‘fsl> a: nth-child (4)’) and press the middle mouse button.
This concludes the discussion on how to in puppeteer open link in new tab. And in more detail about working with multiple tabs, blocking pop-ups (popup ads) can be found in this article.
estava há literalmente 5 horas tentando referenciar uma pagina com target _blank, salvou muito