How to switch between tabs with Puppeteer?

后端 未结 3 1712
孤独总比滥情好
孤独总比滥情好 2021-01-12 04:27

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 refe

3条回答
  •  无人及你
    2021-01-12 04:44

    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.

提交回复
热议问题