πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 53 of 100
Interactions
Intermediate

How does Playwright handle multiple tabs within a single test?

The Answer

Each browser tab is a `Page` object. When an action opens a new tab, you listen for the `page` event on the context. You can then interact with both pages simultaneously.

Deep Dive Explanation

The `Promise.all()` pattern is critical β€” it registers the event listener BEFORE triggering the click, ensuring the new tab event is never missed. Starting the wait after the click would create a race condition.

example.spec.ts
test('multiple tabs', async ({ context, page }) => {
  await page.goto('https://app.com');

  // Wait for new tab to open when clicking a link
  const [newTab] = await Promise.all([
    context.waitForEvent('page'),
    page.getByRole('link', { name: 'Open Preview' }).click()
  ]);

  await newTab.waitForLoadState('networkidle');
  await expect(newTab).toHaveTitle('Preview Mode');

  // Both tabs are accessible
  await expect(page).toHaveURL('https://app.com'); // Original still works
  await newTab.close();
});