最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to focus current tab puppeteer - Stack Overflow

programmeradmin2浏览0评论

How do I focus on the newly opened tab in puppeteer? I click an element on the page that opens up a new tab and then puppeteer stays focused on the page that was just left for some reason. How can I focus on the newly opened tab? I'm using google chrome browser

How do I focus on the newly opened tab in puppeteer? I click an element on the page that opens up a new tab and then puppeteer stays focused on the page that was just left for some reason. How can I focus on the newly opened tab? I'm using google chrome browser

Share Improve this question asked Aug 3, 2020 at 20:48 Roboman RoboRoboman Robo 6892 gold badges8 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You can use the bringToFront function.

await page.bringToFront();

Handling Multiple Pages(tabs) in Playwright:

Each browser context can host multiple pages (tabs).

Each page behaves like a focused, active page. Bringing the page to front is not required. Pages inside a context respect context-level emulation, like viewport sizes, custom network routes or browser locale.

// Create two pages
const pageOne = await context.newPage();
const pageTwo = await context.newPage();

// Get pages of a browser context
const allPages = context.pages();

Handling new pages

The page event on browser contexts can be used to get new pages that are created in the context. This can be used to handle new pages opened by target="_blank" links.

// Start waiting for new page before clicking. Note no await.
const pagePromise = context.waitForEvent('page');
await page.getByText('open new tab').click();
const newPage = await pagePromise;
await newPage.waitForLoadState();
console.log(await newPage.title());

If the action that triggers the new page is unknown, the following pattern can be used.

// Get all new pages (including popups) in the context context.on('page', async page => { await page.waitForLoadState(); console.log(await page.title()); });

Handling popups

If the page opens a pop-up (e.g. pages opened by target="_blank" links), you can get a reference to it by listening to the popup event on the page.

This event is emitted in addition to the browserContext.on('page') event, but only for popups relevant to this page.

// Start waiting for popup before clicking. Note no await.
const popupPromise = page.waitForEvent('popup');
await page.getByText('open the popup').click();
const popup = await popupPromise;
// Wait for the popup to load.
await popup.waitForLoadState();
console.log(await popup.title());

Reference: https://playwright.dev/docs/pages#multiple-pages

发布评论

评论列表(0)

  1. 暂无评论