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.
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.
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:
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With