TESTEVERYTHING

Saturday, 17 May 2025

How to handle new tab using playwright

 

Scenario:

You click a link or button that opens a new tab, and you want to switch to that tab and perform actions.



  const [newPage] = await Promise.all([

    context.waitForEvent('page'),         // Waits for a new tab to be opened

    page.click('a[target="_blank"]'),     // Simulates clicking the link that opens a new tab

  ]);


  // Wait for the new tab to load

  await newPage.waitForLoadState();


  // Do something in the new tab

  console.log('New tab title:', await newPage.title());


  // Example: take screenshot of the new tab

  await newPage.screenshot({ path: 'new-tab.png' });


  await browser.close();

})();


Key Concepts:

  • context.waitForEvent('page'): Waits for a new tab or popup.

  • The Promise.all() ensures that the event and click happen together.

  • newPage.waitForLoadState(): Ensures the new tab is fully loaded before interaction.


Which one is right ?

Translate







Tweet