Playwright 19 ๐ญ Multiple Tabs and Windows โ context.newPage() and popups
Modern web applications routinely open new tabs and popup windows: external links with target="_blank", OAuth login flows that detour through a provider’s consent screen, invoice previews that open in a separate window, and chat widgets that launch a support panel. Playwright treats every tab and every popup as a Page object inside the same BrowserContext, which means a test can drive multiple windows simultaneously with the same locator-based API it uses for a single page. The challenge is not interactionโit is timing. A new page is an event that fires when it is created, and a test must be listening before the action that triggers it.
This chapter covers the two ways to obtain a new page: creating one programmatically with context.newPage(), and capturing one that the application opens with page.waitForEvent('popup') or context.waitForEvent('page'). It explains the difference between a page and a context, how tabs within a context share cookies and storage, how to list and switch between open tabs with context.pages(), and how to avoid the race condition that causes popup tests to hang. It also covers popups that trigger downloads and the scoping distinction between the page-level popup event and the context-level page event. By the end, you will be able to test any multi-window flow without flakiness.
Key point: A new tab or popup is an event, not a polling target. Register page.waitForEvent('popup') or context.waitForEvent('page') before the click that opens it, then await both together. Clicking first and waiting afterward is a race condition that produces intermittent timeouts.
Why multi-page handling exists
The event-timing problem. When a click opens a new tab, the browser creates the Page object almost instantly. If the test clicks first and then calls waitForEvent, the event has already fired, and the wait never resolves. This is the single most common cause of flaky popup tests. Playwright exposes the event specifically so tests can subscribe before triggering the action, but the ordering is the test author’s responsibility.
The session-sharing problem. A new tab opened from an existing page shares the same BrowserContext, which means it inherits cookies, localStorage, and authentication state . This is usually desirable: a test that logs in once and then opens a second tab should find the user already authenticated in the new tab. The alternativeโa separate browser.newContext()โcreates an isolated session with no shared state, which is the correct choice when testing two different users, but the wrong choice for a single user opening a second window .
The scoping problem. Playwright provides two events for new pages. The popup event fires on the originating page and is scoped to that page’s children, making it the precise choice when one specific link or button triggers the new window . The page event fires on the BrowserContext and catches every new page, including those opened by scripts or unrelated frames, making it the fallback when the trigger is unknown or when multiple new pages may appear .
a. Creating tabs programmatically with context.newPage()
The context.newPage() method opens a fresh tab in the existing browser context and returns a Page object. The tab starts blank; the test navigates it explicitly. This is the correct approach when the test itself decides to open a second tab, rather than reacting to an application action.
import { test, expect } from '@playwright/test';
test('opening a second tab to compare data', async ({ context, page }) => {
// Navigate the original tab to the product list
await page.goto('/products');
// Open a second tab in the same context (shares cookies and session)
const secondPage = await context.newPage();
// Navigate the new tab to the cart
await secondPage.goto('/cart');
// Add an item in the first tab
await page.getByRole('button', { name: 'Add to cart' }).first().click();
// The second tab reflects the updated cart via shared session state
await expect(secondPage.getByTestId('cart-count')).toHaveText('1');
// Close the second tab when finished
await secondPage.close();
});
Every tab in a context behaves as a focused, active page; bringing it to the front is not required for interaction . The context.pages() method returns an array of all open pages in the context, in the order they were created, which allows a test to iterate over every tab or assert on the total count . Note that the first pageโthe one provided by the test fixtureโis included in that array, so a context with one manually created tab reports a length of two.
b. Capturing popups with waitForEvent
When the application opens the new window, the test cannot call newPage(). It must wait for the event. The standard pattern creates the promise before the click, then awaits both concurrently, typically with Promise.all to make the ordering structurally correct .
test('capturing a popup opened by a link', async ({ page }) => {
await page.goto('/dashboard');
// Start waiting for the popup BEFORE the click; note no await here
const popupPromise = page.waitForEvent('popup');
// Trigger the popup with a click
await page.getByRole('link', { name: 'Open invoice' }).click();
// Await the event; this resolves with the new Page object
const popup = await popupPromise;
// Wait for the popup's DOM to be ready before asserting
await popup.waitForLoadState();
// Interact with the popup using the same API as any page
await expect(popup.getByRole('heading')).toHaveText('Invoice #42');
// Close the popup; the original page remains open
await popup.close();
});
The popup event resolves as soon as the new page exists, which may be before its content has loaded . Calling popup.waitForLoadState() before asserting prevents flakiness when the title or heading is set late in the page’s lifecycle. For cases where the action that opens the new page is unknownโa timer, a WebSocket message, a third-party scriptโthe context-level page event with context.on('page', ...) catches every new page without requiring a preceding action . This is a listener rather than a one-shot wait, so it fires for every subsequent page creation in that context.
c. Choosing between popup and page events
The two events differ in scope, and the choice affects both reliability and precision. The popup event fires only on the page that opened the new window, while the page event fires on the context and catches every new page regardless of origin . When a single link triggers the popup, page.waitForEvent('popup') ties the wait to the exact opener and fails loudly if a different element opens the window . When the trigger is ambiguous or when the test expects multiple new tabs, context.waitForEvent('page') is the appropriate listener.
test('using Promise.all to eliminate the race condition', async ({ page, context }) => {
await page.goto('/reports');
// Promise.all starts the wait and the click together
const [newPage] = await Promise.all([
context.waitForEvent('page'), // catches any new page in the context
page.getByRole('link', { name: 'Export PDF' }).click(), // triggers the popup
]);
await newPage.waitForLoadState();
expect(newPage.url()).toContain('/reports/export');
});
The Promise.all shape is the recommended default because it makes the subscribe-before-click ordering impossible to get wrong . Both operations begin simultaneously: the listener is armed, and the click triggers the event. If the popup is blocked by the browserโcommon with window.open calls not initiated by a user gestureโwaitForEvent will time out, and the test should handle that rejection to verify the application’s fallback behavior rather than hanging indefinitely .
Complete Example Session
// ============================================
// PART 1: IMPORT AND TEST SETUP
// ============================================
import { test, expect } from '@playwright/test';
// ============================================
// PART 2: CREATING A TAB PROGRAMMATICALLY
// ============================================
test('multi-window workflow', async ({ context, page }) => {
await page.goto('/products');
// Open a second tab in the same context; session is shared
const cartTab = await context.newPage();
await cartTab.goto('/cart');
// ============================================
// PART 3: VERIFYING SHARED STATE ACROSS TABS
// ============================================
await page.getByRole('button', { name: 'Add to cart' }).first().click();
await expect(cartTab.getByTestId('cart-count')).toHaveText('1');
// ============================================
// PART 4: LISTING ALL OPEN PAGES
// ============================================
const allPages = context.pages();
expect(allPages).toHaveLength(2); // original page + cart tab
// ============================================
// PART 5: CAPTURING A POPUP VIA THE PAGE EVENT
// ============================================
await page.goto('/orders');
const popupPromise = page.waitForEvent('popup');
await page.getByRole('link', { name: 'View receipt' }).click();
const receipt = await popupPromise;
// ============================================
// PART 6: WAITING FOR POPUP CONTENT
// ============================================
await receipt.waitForLoadState();
await expect(receipt.getByRole('heading')).toContainText('Receipt');
// ============================================
// PART 7: USING PROMISE.ALL FOR RACE-FREE CAPTURE
// ============================================
const [helpWindow] = await Promise.all([
context.waitForEvent('page'), // context-level catch
page.getByRole('button', { name: 'Help' }).click(),
]);
await helpWindow.waitForLoadState();
// ============================================
// PART 8: INTERACTING ACROSS MULTIPLE TABS
// ============================================
await cartTab.bringToFront();
await cartTab.getByRole('button', { name: 'Checkout' }).click();
// ============================================
// PART 9: CLOSING TABS WITHOUT AFFECTING OTHERS
// ============================================
await receipt.close();
await helpWindow.close();
expect(context.pages()).toHaveLength(2); // original + cart remain
// ============================================
// PART 10: CLEANUP
// ============================================
await cartTab.close();
expect(context.pages()).toHaveLength(1);
});
The ten parts above demonstrate the full range: programmatic tab creation, cross-tab state verification, listing pages, popup capture via both events, race-free Promise.all, interaction across tabs, and independent closing. The two tabs created by newPage() and the two captured via events all belong to the same context, so the session remains consistent throughout.
Quick Reference
Page Creation and Capture
| Method | Scope | Use When |
|---|---|---|
context.newPage() | Context | Test decides to open a tab |
page.waitForEvent('popup') | Page | A specific element opens the window |
context.waitForEvent('page') | Context | Trigger unknown; any new page |
context.pages() | Context | List all open tabs |
context.on('page', ...) | Context | Listen for every new page |
Popup Event vs Page Event
| Aspect | popup (page) | page (context) |
|---|---|---|
| Fires on | Originating page | Browser context |
| Scope | Popups from that page | All new pages |
| Precision | High (tied to opener) | Broad (catches everything) |
| Multiple tabs | One wait per popup | One listener for all |
Best Practices for Timing
| Practice | Why |
|---|---|
| Create promise before click | Event fires immediately; late wait hangs |
Use Promise.all | Structurally enforces ordering |
Call waitForLoadState() | Popup resolves before DOM ready |
Prefer popup when possible | Scoped to the opener |
| Handle blocked popups | waitForEvent rejects if never fires |
Context vs New Context
| Need | Approach |
|---|---|
| Same user, second tab | context.newPage() or popup event |
| Different user, isolated session | browser.newContext() |
| Shared cookies required | Same context |
| Separate cookies required | New context |
Best Practices
โ Do This:
// Start the wait before the click, then await both together
const popupPromise = page.waitForEvent('popup'); // โ
await page.getByRole('link', { name: 'Open' }).click();
const popup = await popupPromise;
// Use Promise.all for race-free capture
const [tab] = await Promise.all([
page.waitForEvent('popup'), // โ
page.getByRole('button', { name: 'Share' }).click(),
]);
// Wait for the popup's DOM before asserting
await popup.waitForLoadState(); // โ
await expect(popup.getByRole('heading')).toHaveText('Report');
// Prefer the page-scoped popup event when one element triggers it
page.waitForEvent('popup'); // โ
scoped to opener
// Use context.newPage() when the test opens the tab itself
const secondTab = await context.newPage(); // โ
// Close tabs individually when done
await popup.close(); // โ
โ Don’t Do This:
// Don't click first, then wait; the event may have already fired
await page.getByRole('link', { name: 'Open' }).click(); // โ race
const popup = await page.waitForEvent('popup');
// Don't assert immediately after the event without waiting for load
const popup = await popupPromise; // โ DOM may be empty
await expect(popup.getByRole('heading')).toHaveText('Report');
// Don't use waitForTimeout to "wait for the popup"
await page.waitForTimeout(2000); // โ slow and still flaky
// Don't create a new context when you need shared cookies
const isolated = await browser.newContext(); // โ different session
// Don't forget to handle a blocked popup
const popup = await page.waitForEvent('popup'); // โ hangs if blocked
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Popup wait times out | Wait registered after the click | Start promise before the action |
| Popup found but empty | Event fires before DOM loads | Call waitForLoadState() first |
| Wrong tab captured | Multiple popups, broad page listener | Use popup with specific opener |
| Auth not shared | New context created instead of new page | Use context.newPage() in same context |
| Test hangs on blocked popup | waitForEvent never rejects by default | Add timeout or .catch() handler |
| Tab count off by one | Forgot the original page in context.pages() | Length includes all pages in context |
Real-World Examples
1. Opening a second tab to compare prices
const compareTab = await context.newPage();
await compareTab.goto('/products/compare');
await expect(compareTab.getByText('Product A')).toBeVisible();
2. Capturing a target="_blank" documentation link
const popupPromise = page.waitForEvent('popup');
await page.getByRole('link', { name: 'Documentation' }).click();
const docs = await popupPromise;
await expect(docs).toHaveURL(/docs\.example\.com/);
3. Using Promise.all for an OAuth popup
const [authPopup] = await Promise.all([
page.waitForEvent('popup'),
page.getByRole('button', { name: 'Sign in with Google' }).click(),
]);
await authPopup.getByLabel('Email').fill('user@example.com');
4. Listing all tabs and asserting the count
const tabs = context.pages();
expect(tabs).toHaveLength(3); // original + 2 opened
5. Switching focus between tabs
const [tabA, tabB] = context.pages();
await tabB.bringToFront();
await tabB.getByRole('button', { name: 'Submit' }).click();
6. Capturing a popup via the context-level page event
const [newTab] = await Promise.all([
context.waitForEvent('page'),
page.getByText('Open support').click(),
]);
7. Closing a popup and verifying the original remains
await popup.close();
await expect(page.getByRole('heading')).toHaveText('Dashboard');
8. Handling a popup that triggers a download
const popupPromise = page.waitForEvent('popup');
await page.getByRole('link', { name: 'Download invoice' }).click();
const popup = await popupPromise;
const download = await popup.waitForEvent('download');
await download.saveAs('./invoices/latest.pdf');
9. Opening a new tab programmatically for a fresh session view
const freshTab = await context.newPage();
await freshTab.goto('/account');
await expect(freshTab.getByText('Logged in')).toBeVisible();
10. Listening for all new pages in a context
const pages: Page[] = [];
context.on('page', (p) => pages.push(p));
await page.getByRole('button', { name: 'Open all' }).click();
expect(pages.length).toBeGreaterThan(0);
Visual
The Popup Race Condition
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WHY ORDER MATTERS โ
โ โ
โ โ WRONG ORDER (click first, wait second) โ
โ โ
โ t=0 click "Open" โ
โ t=1 browser creates Page object โ
โ t=2 popup event fires โโโบ NO LISTENER โ
โ t=3 test calls waitForEvent('popup') โ
โ t=4 event already happened โโโบ hangs until timeoutโ
โ โ
โ โ
CORRECT ORDER (wait first, click second) โ
โ โ
โ t=0 test calls waitForEvent('popup') โ
โ t=1 listener armed โ
โ t=2 click "Open" โ
โ t=3 browser creates Page object โ
โ t=4 popup event fires โโโบ listener catches it โ
โ t=5 promise resolves with the new Page โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Popup Event vs Page Event Scope
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SCOPE OF EACH EVENT โ
โ โ
โ BrowserContext โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ โ
โ โ Page A (opener) โ โ
โ โ โ โ โ
โ โ โโโ popup event fires here โโโบ Page B โ โ
โ โ โ โ โ
โ โ โโโ popup event fires here โโโบ Page C โ โ
โ โ โ โ
โ โ page event fires here for B and C โโโบ Page D โ โ
โ โ (context level, catches all new pages) โ โ
โ โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ page.waitForEvent('popup') โ scoped to opener โ
โ context.waitForEvent('page') โ catches everything โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Same Context vs New Context
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SHARED SESSION OR ISOLATED SESSION โ
โ โ
โ SAME CONTEXT (second tab, same user) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ context.newPage() โ โ
โ โ or popup event โ โ
โ โ โ โ
โ โ Tab 1 โโโ โ โ
โ โ โโโ shared cookies, localStorage โ โ
โ โ Tab 2 โโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ NEW CONTEXT (different user, isolated) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ browser.newContext() โ โ
โ โ โ โ
โ โ Context 1: Tab A โโ cookies A โ โ
โ โ Context 2: Tab B โโ cookies B (separate) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Create a tab | context.newPage() |
| Capture a popup | page.waitForEvent('popup') |
| Capture any new page | context.waitForEvent('page') |
| List all tabs | context.pages() |
| Listen for all new pages | context.on('page', handler) |
| Race-free pattern | Promise.all([waitForEvent, click]) |
| Wait for popup DOM | popup.waitForLoadState() |
| Close a tab | page.close() |
| Shared session | Same context |
| Isolated session | browser.newContext() |
Key takeaways:
- The event fires before you think it does. A new page is created almost instantly after the click. Waiting after the action is a race condition that produces intermittent hangs. The promise must exist before the trigger.
Promise.allis the safest shape. Combining the wait and the click in a singlePromise.allcall makes the correct ordering structural rather than a matter of discipline. It is the pattern to reach for by default.- The popup event is scoped; the page event is broad. Use
page.waitForEvent('popup')when one element opens the window. Usecontext.waitForEvent('page')when the trigger is unknown or multiple pages may open. - A tab belongs to a context, not a page. Tabs in the same context share cookies and storage. This is usually what a test wants for a single user; use a new context only when testing independent sessions.
- The event resolves before the DOM is ready. Always call
waitForLoadState()on the captured page before asserting on its content, or the assertion may run against an empty document. context.pages()includes the original page. A test that opens one additional tab will see a length of two, not one. Account for the fixture page when asserting on tab counts.- Blocked popups need handling. If the browser blocks the popup,
waitForEventwill time out rather than reject immediately. Attach a timeout or a.catch()handler when testing applications that might be blocked.
Remember: Multi-window testing in Playwright is fundamentally an exercise in event timing. The browser does not ask the test whether it is ready before opening a tab; it fires the event and moves on. The test’s job is to be listening before the trigger, to await the event and the action together, and to wait for the new page’s content before asserting. Once the page is captured, it is just another Page objectโsame locators, same assertions, same interactions. The complexity is entirely in the capture, and the Promise.all pattern reduces that complexity to a single, reliable shape.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!