Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer detect when the new tab is opened and get page object

My web app opens a new tab under some conditions. But when I try to get all tabs (await browser.pages()) I get only one back, the initial page.

How can I get the new page's object in my code?

This happens when you don't create new tab with puppeteer with await browser.newPage(), but when you do something like this:

await (await browser.pages())[0].evaluate(() => {
    window.open('http://www.example.com', '_blank');
});

The page won't be available in the browser.pages() response.

like image 630
Konstantin Bodnia Avatar asked Mar 01 '18 12:03

Konstantin Bodnia


People also ask

How do I access an already opened page on puppeteer?

When launching a browser on Puppeteer, it launches with an open tab. To access the already opened page: It's important to use proxies while scraping at scale. When you try to scrape a website and visit over a certain number of pages, the rate-limiting defense mechanism will block your visits.

How to catch new tabs and popups in puppeteer?

Starting with puppeteer version 1.12, a special ‘popup’ event has been added to the page, which allows you to catch new tabs and popups. We use it by rewriting the first example:

Why does puppeteer stop when I focus on a new window?

But in any case, at this point, focusing on a new window occurs or if it is not properly processed, puppeteer will not continue executing the code, but will wait until you close in puppeteer popup window or switch to the old tab. So let’s do it! You can read how to open the link in a new tab in this note. First, let’s talk a little about tabs.

Why does puppeteer keep closing my tabs?

If you make a mistake in the code, puppeteer will constantly close absolutely all tabs. Or perform with them some other operations that are not worth doing. Starting with puppeteer version 1.12, a special ‘popup’ event has been added to the page, which allows you to catch new tabs and popups.


1 Answers

This code will catch the new page in a new tab if it was opened by clicking a link in the original page.

//save target of original page to know that this was the opener:     
const pageTarget = page.target();
//execute click on first tab that triggers opening of new tab:
await page.click('#selector');
//check that the first page opened this new page:
const newTarget = await browser.waitForTarget(target => target.opener() === pageTarget);
//get the new page object:
const newPage = await newTarget.page();
like image 114
Robert Hillen Avatar answered Sep 19 '22 12:09

Robert Hillen