Playwright Multiple Tabs and Windows Explained: A Practical Guide


Playwright handles multiple tabs and popup windows using the Page object. A browser context can contain multiple pages, and you can capture a newly opened page by waiting for the appropriate event before performing the action that opens it.

This is useful when testing websites that open product details, payment providers, reports, or external links in new tabs.

In this tutorial, you will learn how to open new tabs, handle popups, verify page details, and avoid common timing problems.

1. What Are Multiple Tabs and Windows in Playwright?

Consider an online shopping website.

You open a product page and click a link to view its specifications in a new tab. You may also open a payment provider in a popup window.

A person can switch between these pages manually. An automation test needs to identify the correct page and interact with it.

Playwright represents a tab or popup using a Page object.

According to the official Playwright pages documentation, one browser context can contain multiple pages.

2. Understand Browser, Context, and Page

Before writing code, understand these three concepts.

  • Browser: The browser instance controlled by Playwright.

  • Browser context: An isolated browser session.

  • Page: A tab or popup within a browser context.

For example:

const context = await browser.newContext();


const pageOne = await context.newPage();

const pageTwo = await context.newPage();


Both pages belong to the same context.

They can display different websites while sharing context-level session state.

A page created inside a different context belongs to a separate browser session.

This distinction matters when testing multiple tabs for one user versus separate sessions for different users.

3. How to Open a New Tab in Playwright

You can create a new page directly using context.newPage().

const { test, expect } = require('@playwright/test');


test('open two pages', async ({ context }) => {

  const firstPage = await context.newPage();


  await firstPage.goto('https://example.com');


  const secondPage = await context.newPage();


  await secondPage.goto('https://playwright.dev');


  await expect(firstPage).toHaveTitle(/Example Domain/);


  await expect(secondPage).toHaveURL(/playwright\.dev/);

});


This example creates two pages in the same context.

You do not need to close the first page before interacting with the second. Playwright can interact with both pages using their respective objects.

4. How to Handle a New Tab Opened by Clicking a Link

A common scenario occurs when clicking a link opens another tab.

For example, a website might contain:

<a href="https://example.com" target="_blank">

  Open Example

</a>


Your test needs to capture the new page.

Use context.waitForEvent('page'):

const { test, expect } = require('@playwright/test');


test('handle a newly opened tab', async ({ page, context }) => {

  await page.goto('https://your-test-site.example');


  const newPagePromise = context.waitForEvent('page');


  await page.getByRole('link', {

    name: 'Open Example'

  }).click();


  const newPage = await newPagePromise;


  await newPage.waitForLoadState('domcontentloaded');


  await expect(newPage).toHaveURL(/example\.com/);

});


Replace the example website with your actual test application.

The important sequence is:

  1. Start waiting for the new page.

  2. Perform the click.

  3. Await the new page.

  4. Verify the destination.

Why must the listener come first?

The click may open the page immediately.

If you wait for the page only after clicking, the event may already have occurred, leaving the test waiting until it times out.

Creating the promise before the click avoids this race condition.

5. How to Handle Popup Windows

Use page.waitForEvent('popup') when the popup is opened by a particular page.

test('handle a popup window', async ({ page }) => {

  await page.goto('https://your-test-site.example');


  const popupPromise = page.waitForEvent('popup');


  await page.getByRole('button', {

    name: 'Open Report'

  }).click();


  const popup = await popupPromise;


  await popup.waitForLoadState('domcontentloaded');


  console.log('Popup URL:', popup.url());

});


The popup event is associated with the page that opened the popup.

The browser context's page event can capture new pages across the context, including popups.

Use the page-specific event when you know which page triggers the popup. Use the context-level event when you need to capture a new page created anywhere in the context.

6. How to Verify the New Tab's Title and URL

After capturing the new page, you can verify its destination and content.

const { expect } = require('@playwright/test');


await expect(newPage).toHaveURL(/example\.com/);


await expect(newPage).toHaveTitle(/Example Domain/);


These assertions help confirm that the application opened the correct destination.

You can also inspect the title directly:

const title = await newPage.title();


console.log('New page title:', title);


Prefer assertions when writing automated tests because they make expected behavior explicit.

7. How to Switch Between Tabs

Playwright does not require you to switch browser focus manually before interacting with a page.

You can keep references to different pages and use the appropriate object.

const pages = context.pages();


console.log('Open page count:', pages.length);


const firstPage = pages[0];

const secondPage = pages[1];


console.log('First URL:', firstPage.url());

console.log('Second URL:', secondPage.url());


The context.pages() method returns the pages currently open in that context.

However, do not assume a specific array position will always identify a particular business page if your test opens several pages dynamically.

Capture the page from the event that created it whenever possible.

8. How to Close a Tab and Continue Testing

Use page.close() to close a particular page.

await secondPage.close();


await expect(firstPage).toHaveTitle(/Example Domain/);


Closing the second page does not automatically close the first page.

This is useful when testing workflows where users open a report, inspect its content, close the report, and continue working on the original page.

Remember that closing the entire browser context is different from closing one page.

9. Testing Login, Payment, and External Links

Multiple-page automation is particularly useful for business workflows.

Login workflows

If authentication opens a new page, capture it and verify the resulting URL or content.

Do not assume that every login flow opens a new tab. Many applications navigate within the existing page.

Payment workflows

A payment integration might open a payment provider in another page.

Test the expected transition and use a suitable test environment. Avoid running automated payment tests against real financial transactions unless the testing arrangement explicitly supports them.

External links

A website may open documentation, a help center, or a partner website in a new tab.

Verify that the link points to the intended destination.

For complex page interactions, see the Playwright locator guide.

10. Common Multiple-Tab Errors

Error 1: Waiting for the event after clicking

Problem: The new page opens before the listener is registered.

Solution: Create the event promise before clicking.

Error 2: Using the original page to test the popup

Problem: The test continues interacting with the original page even though the target content is in the popup.

Solution: Use the returned popup or new-page object.

Error 3: Using arbitrary fixed delays

Problem: A test calls waitForTimeout(3000) and assumes the new page will be ready after three seconds.

The page may load sooner or later.

Solution: Wait for the page event, then wait for a relevant state, navigation, or assertion.

For example:

await expect(newPage.getByRole('heading', {

  name: 'Report'

})).toBeVisible();


This waits for the expected heading instead of relying on a guessed delay.

Error 4: Confusing a new page with a new context

Problem: The test expects a new tab to have independent cookies from the original page.

Solution: Remember that pages within one context share context-level session state. Create a new context when a separate browser session is required.

Error 5: Waiting for the wrong event

Problem: The test waits for a popup from the wrong page.

Solution: Use page.waitForEvent('popup') for a popup opened by a specific page, or context.waitForEvent('page') to capture a page created within the context.

11. Best Practices for Stable Multi-Page Tests

Follow these practices:

  • Register event listeners before triggering actions.

  • Keep clear references to the original page and new pages.

  • Verify URLs and page content with assertions.

  • Avoid arbitrary delays as a synchronization strategy.

  • Do not depend on page-array positions when an event can identify the target.

  • Use separate contexts when different users require isolated sessions.

  • Close pages you create manually when they are no longer needed.

  • Use descriptive locators and web-first assertions.

You can explore reusable setup patterns in the Playwright fixtures guide and improve your validation with the Playwright assertions guide.

For more complex automation suites, the Page Object Model guide can help organize page-specific behavior.

If a popup test fails intermittently, use the Playwright debugging guide to investigate the failure.

Frequently Asked Questions

How do I handle multiple tabs in Playwright?

Use context.newPage() to create a page directly, or wait for the page event when an action opens a new tab.

What is the difference between page and popup events?

The context's page event captures new pages within the context. The page's popup event captures popups opened by that particular page.

Can Playwright interact with multiple tabs simultaneously?

Yes. Keep references to the individual Page objects and use the appropriate object for each action.

Do multiple tabs share cookies?

Pages in the same context share context-level cookies. Pages in separate contexts use independent browser-session state.

Why does my new-tab test time out?

Possible causes include a click that does not open a page, an incorrect locator, a popup blocked by application behavior, or an event listener registered too late.

Do I need to switch tabs manually?

No. Playwright can interact with a page through its Page object without requiring you to manually change browser focus.

How can I learn more about Playwright automation?

Visit the PlaywrightMasters for practical automation tutorials and related learning resources.

Conclusion

Playwright makes multiple-tab automation manageable by representing tabs and popups as Page objects.

Use context.waitForEvent('page') to capture a newly created page in a browser context and page.waitForEvent('popup') when a specific page opens a popup.

Register listeners before the triggering action, verify the resulting page, and wait for meaningful application states rather than arbitrary delays.

For more Playwright automation guidance, explore the tutorials and technical learning resources available on PlaywrightMasters.in.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright