How to switch between tabs with Puppeteer?

我是研究僧i 提交于 2019-12-01 04:09:38

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"]');

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!