Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch between tabs with Puppeteer?

Tags:

puppeteer

Here is my use case:

I have a link which on clicking opens a new tab and loads the content.

What I am looking for:

Is there a way to switch the reference of the page while new tab opens or create a reference for the new tab?

like image 506
Kaushik Avatar asked Sep 24 '17 12:09

Kaushik


People also ask

How do you close a tab puppeteer?

We can close the tab opened using the close() function present in puppeteer.

Can you run puppeteer in the browser?

Puppeteer lets you automate the testing of your web applications. With it, you can run tests in the browser and then see the results in real-time on your terminal. Puppeteer uses the WebDriver protocol to connect with the browser and simulate user interaction with HTML elements or pages.

How do you right click on a puppeteer?

click() with the button option set to 'right' to right-click an element: const example = await page. $('#example'); await example. click({ button: 'right', });


3 Answers

To get the page that was opened after a link is clicked, you can listen on the popup event. It is emitted when the page opens a new tab or window.

Code sample (from the docs linked above)

const [newPage] = await Promise.all([
    new Promise(resolve => page.once('popup', resolve)),
    page.click('a[target=_blank]'),
]);

This will click on the link while waiting for a window to be opened by the current page. newPage will be the opened page.


Alternative approach: To get a list of all open pages, you can use browser.pages:

const pages = await browser.pages();

pages will be an array with all open pages.

like image 77
Thomas Dondorf Avatar answered Oct 20 '22 11:10

Thomas Dondorf


Use next function:

let clickAndWaitForTarget = async (clickSelector, page, browser) => {
  const pageTarget = page.target(); //save this to know that this was the opener
  await page.click(clickSelector); //click on a link
  const newTarget = await browser.waitForTarget(target => target.opener() === pageTarget); //check that you opened this page, rather than just checking the url
  const newPage = await newTarget.page(); //get the page object
  // await newPage.once("load",()=>{}); //this doesn't work; wait till page is loaded
  await newPage.waitForSelector("body"); //wait for page to be loaded

  return newPage;
};

and use it:

await page.waitForSelector('a[href="/admin"]');
page = await clickAndWaitForTarget('a[href="/admin"]', page, browser);

// Admin page
//console.log(JSON.stringify(page.target()));
await page.waitForSelector('a[href="/users"]');
like image 45
G. I. Joe Avatar answered Oct 20 '22 10:10

G. I. Joe


Currently, you can follow this issue https://github.com/GoogleChrome/puppeteer/pull/554 to know when the ability is added to puppeteer. Or you can use repo where JoelEinbinder folked

like image 21
Anh Thang Bui Avatar answered Oct 20 '22 10:10

Anh Thang Bui