How to Handle Multiple Tabs in Playwright

In Playwright, we can handle multiple tabs or pages using page instances created using 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("https://www.programsbuzz.com/")

    const [newPage] = await Promise.all([
        context.waitForEvent('page'),
        // This action triggers the new tab
        page.locator('text=By iVagus Services Pvt. Ltd.').click() 
      ])
           
      // 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.
  • 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.
Mon, 09/05/2022 - 18:01

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

Video Tutorial: Playwright Handle Multiple Browser Tabs

Tags