如何使用 Puppeteer 在选项卡之间切换? [英] How to switch between tabs with Puppeteer?
问题描述
这是我的用例:
我有一个链接,点击它会打开一个新标签并加载内容.
I have a link which on clicking opens a new tab and loads the content.
我在找什么:
有没有办法在新标签打开时切换页面的引用或为新标签创建引用?
Is there a way to switch the reference of the page while new tab opens or create a reference for the new tab?
推荐答案
要获取点击链接后打开的页面,可以在 popup
事件.当页面打开新选项卡或窗口时发出.
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]'),
]);
这将在等待当前页面打开一个窗口时点击链接.newPage
将是打开的页面.
This will click on the link while waiting for a window to be opened by the current page. newPage
will be the opened page.
替代方法:要获取所有打开页面的列表,您可以使用 browser.pages
:
Alternative approach: To get a list of all open pages, you can use browser.pages
:
const pages = await browser.pages();
pages
将是一个包含所有打开页面的数组.
pages
will be an array with all open pages.
这篇关于如何使用 Puppeteer 在选项卡之间切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!