Thursday, April 24, 2025

Multiple Windows in playwright

 In this example, we will explore how to manage multiple pages in Playwright, including practical examples and best practices. Working with multiple windows (or tabs) in Playwright is actually pretty smooth. Playwright handles browser contexts and page events really well, so switching between windows or monitoring popups is straightforward.

Multiple Windows in playwright

Here’s a breakdown of how you can manage multiple windows (tabs or popups) in Playwright:


 Syntax

const [newPage] = await Promise.all([
  context.waitForEvent('page'), // Listen for the new window
  page.click('a[target="_blank"]') // Trigger that opens the new tab/window
]);

await newPage.waitForLoadState();
await newPage.locator('h1').click(); // Interact with new tab

Explanation:

  1. context.waitForEvent('page'): Listens for any new page (tab or popup).
  2. Promise.all(): Ensures you don’t miss the event (because Playwright is async).
  3. newPage: Is your handle to the new tab or window.


 Switching Between Windows

You can interact with both windows/pages by holding references to them.

await page.bringToFront(); // Focus original tab
await newPage.bringToFront(); // Switch to new tab


Pages

Each BrowserContext can have multiple pages. A Page refers to a single tab or a popup window within a browser context. It should be used to navigate to URLs and interact with the page content.

// Create a page.
const page = await context.newPage();

// Navigate explicitly, similar to entering a URL in the browser.
await page.goto('http://example.com');
// Fill an input.
await page.locator('#search').fill('query');

// Navigate implicitly by clicking a link.
await page.locator('#submit').click();
// Expect a new url.
console.log(page.url());

Multiple pages

Each browser context can host multiple pages (tabs).

  1. Each page behaves like a focused, active page. Bringing the page to front is not required.
  2. Pages inside a context respect context-level emulation, like viewport sizes, custom network routes or browser locale.

// Create two pages
const pageOne = await context.newPage();
const pageTwo = await context.newPage();

// Get pages of a browser context
const allPages = context.pages();

expect(pages.length).toBe(2);

const originalPage = pages[0];
const popupPage = pages[1];


Handling new pages

The page event on browser contexts can be used to get new pages that are created in the context. This can be used to handle new pages opened by target="_blank" links.

// Start waiting for new page before clicking. Note no await.
const pagePromise = context.waitForEvent('page');
await page.getByText('open new tab').click();
const newPage = await pagePromise;
// Interact with the new page normally.
await newPage.getByRole('button').click();
console.log(await newPage.title());

If the action that triggers the new page is unknown, the following pattern can be used.

// Get all new pages (including popups) in the context
context.on('page', async page => {
  await page.waitForLoadState();
  console.log(await page.title());
});

Handling popups

If the page opens a pop-up (e.g. pages opened by target="_blank" links), you can get a reference to it by listening to the popup event on the page.

This event is emitted in addition to the browserContext.on('page') event, but only for popups relevant to this page.

// Start waiting for popup before clicking. Note no await.
const popupPromise = page.waitForEvent('popup');
await page.getByText('open the popup').click();
const popup = await popupPromise;
// Interact with the new popup normally.
await popup.getByRole('button').click();
console.log(await popup.title());
If the action that triggers the popup is unknown, the following pattern can be used.
// Get all popups when they open
page.on('popup', async popup => {
  await popup.waitForLoadState();
  console.log(await popup.title());
});

To handle multiple pages or windows in Playwright, you can use the newContext method to create a new browser context and then open multiple pages within that context. Here's a basic example:


Handling new tab or new window in playwright

Here is the simple example to handle multiple window in playwright.

// @ts-check
import { test, expect } from '@playwright/test';

test("Handle window in playwright", async({ browser }) => {

    const context = await browser.newContext();
    const page = await context.newPage();

    await page.goto("https://demoqa.com/browser-windows");

    // Start waiting for new page before clicking. Note no await.
    const pagePromise = context.waitForEvent('page');
    await page.locator('#tabButton').click();
    const newPage = await pagePromise;

    // Interact with the new page normally.
    // Verify the new page h1 tag text
    await expect(newPage.locator('//h1')).toHaveText("This is a sample page");
    console.log(await newPage.title());

});


Handling new tab or new window in playwright using promise

Here is the simple example to handle multiple window in playwright using promise.
// @ts-check
import { test, expect } from '@playwright/test';

test("Handle window in playwright using promise", async({ browser }) => {

    const context = await browser.newContext();
    const page = await context.newPage();

    await page.goto("https://demoqa.com/browser-windows");

    // Start waiting for new page before clicking. Note no await.
    // Click on a link that opens a new page
    const [newPage] = await Promise.all([
        context.waitForEvent("page"), // Wait for the new page to open
        await page.locator('#tabButton').click(),
    ]);

    // Interact with the new page normally.
    // Verify the new page h1 tag text
    await expect(newPage.locator('//h1')).toHaveText("This is a sample page");
    console.log(await newPage.title());

});


Handling multiple windows and tabs in Playwright is straightforward once you understand how browser contexts work. By utilizing the features provided by Playwright, such as event handling and isolated contexts, you can create robust and efficient test scripts that simulate real user interactions across multiple pages.



No comments:

Post a Comment