How to Handle Multiple Tabs in Playwright

Profile picture for user arilio666

In Playwright, we can handle multiple tabs or pages using page instances created using browser context. A Page refers to a single tab or a popup window within a browser context. Switching or bringing the page to the front is not required in Playwright like Selenium because each page behaves like a focused or active page when referred to using its page instance. Also, Pages created using context respect context-level emulation, like viewport sizes, custom network routes, or browser locale.

Table of Content

  1. Demo Website
  2. Example
  3. Video Tutorial

1. Demo Website

how to open multiple tabs in playwright

For the demo, we will click on the By iVagus Services Pvt. Ltd. link in the copyright footer section of the programsbuzz website. After the click, a new tab will open with a different website, and we will get the title of the new and existing website using page instances.

2. Example

test.only('verify multiple tabs', async({context})=>{
    const page = await context.newPage();
    await page.goto("")

    const [newPage] = await Promise.all([
        // This action triggers the new tab
        page.locator('text=By iVagus Services Pvt. Ltd.').click() 
      // Wait for Page Load
      await newPage.waitForLoadState();          
      // title of new tab page
      console.log(await newPage.title());
      // title of existing page
      console.log(await page.title());
  • context: context is a fixture or an isolated browser context instance created for each test.
  • Promise.all(): Promise represents the completion of asynchronous operations. All is a method used to create a promise which is resolved when all of the provided promises resolve, and the promise is rejected when any promise is rejected. All method resolve with an array of results and prevents a race condition between clicking and waiting for the request.
  • waitForEvent('page'): It is essential to call waitForEvent first to wait for the creation of a child tab. The event is emitted when a new Page is created in the BrowserContext.
  • waitForLoadState(): This resolves when the page reaches a required load state, load by default. Other values are domcontentloaded and networkidle.
  • page and newpage: page is an instance of the current page, and the newpage is an instance of the page opened in a new tab after clicking on an element.

Video Tutorial: Playwright Multiple Tabs