8

这是我的用例:

我有一个链接,单击它会打开一个新选项卡并加载内容。

我在找什么:

有没有办法在新标签打开时切换页面的引用或为新标签创建引用?

4

3 回答 3

4

要获取单击链接后打开的页面,您可以监听该popup事件。当页面打开新选项卡或窗口时发出。

代码示例(来自上面链接的文档)

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

这将在等待当前页面打开一个窗口时单击该链接。newPage将是打开的页面。


替代方法:要获取所有打开页面的列表,您可以使用browser.pages

const pages = await browser.pages();

pages将是一个包含所有打开页面的数组。

于 2019-05-07T19:09:14.950 回答
3

使用下一个功能:

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;
};

并使用它:

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"]');
于 2019-03-30T01:14:21.980 回答
1

目前,您可以关注此问题https://github.com/GoogleChrome/puppeteer/pull/554以了解该能力何时添加到puppeteer. 或者你可以使用 JoelEinbinder 的 repo

于 2017-09-25T16:15:19.653 回答