How can I manage multiple tabs or pages opened by a link in Playwright?


Handling Multiple Tabs in Playwright

When a link opens multiple new tabs, Playwright has got you covered. Each browser context in Playwright can host multiple pages, acting like focused, active pages.

Here's how you can handle this:

// 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());

In this example, we first start waiting for a new page to be created. Then we click on the link that opens the new tab. Finally, we wait for the newly opened page to finish loading and retrieve its title.

If you're unsure which action triggers the opening of a new tab, Playwright provides another pattern. You can listen for all pages that are created in the context:

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

This sets up an event listener that triggers whenever a new page is created within the browser context. Inside this function, you can perform actions or retrieve information from each newly created page.

As for setting up different contexts based on URL, you can create multiple browser contexts in Playwright. Each context can have its own set of pages and can be configured with different settings. However, there's no specific details on how to set up a page context based on URL.

In summary, Playwright provides mechanisms to handle situations where a link opens multiple new tabs. However, there's no explicit information available on setting up page contexts based on URLs.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.