TL;DR
- Use the opener page's
popupevent when a known action creates a child tab or window. - Use the browser context's
pageevent when the creator is unknown or you intentionally monitor all new pages in that context. - Register the event promise before clicking and bound how long the client will wait.
- Verify the destination and a task-specific marker before interacting with the new page.
- Use a navigation wait for the same-tab path and a dialog handler for JavaScript dialogs.
- Close only the pages the task owns, then verify managed session cleanup through the controller.
How do you handle a popup or new tab in Playwright?
Handle a popup by waiting for the event from the page that will open it, then treating the returned page as a separate automation target. Check its actual destination and expected application state before issuing another action. Nstdata provides managed browsers to which a supported Playwright client can attach and manage more than one page.
Consider a staging review queue with a link that opens a release preview. An unrelated status tab is also open. Selecting the most recent element in context.pages() assumes that no other worker or page created a tab. The safer design waits for the event from the known opener and verifies that the returned page shows the correct release. For cases where someone opens a page manually first, see the operator handoff workflow.
Which event matches the behavior of your application?
Choose the event that corresponds to what the page actually creates. A new DOM modal keeps the same Playwright page and needs ordinary locators. A dialog raised by JavaScript is a separate event. A new tab is represented by another page, and a same-tab navigation changes the URL of the original page.
| Browser behavior | Wait or check | How to identify success |
|---|---|---|
| Known opener creates child page | page.waitForEvent('popup') | Correct child URL, expected marker and opener when applicable |
| Context gets a page from an unknown source | context.waitForEvent('page') | Allowed destination, task identity, and page ownership |
| Same-tab navigation | page.waitForURL() | Expected final route and visible target |
| DOM modal on original page | Locate the modal or dialog rendered by the app | Correct accessible region and intended controls |
| JavaScript dialog | page.on('dialog', ...) when handling is needed | Authorized handling and expected app effect |
The Playwright documentation on multiple pages describes the relationship between the context-level event and the opener-level popup event. The Playwright dialogs guide covers a different surface. Determine which behavior the owned app uses before selecting an event.
How do you capture the intended release preview?
Capture the popup from the known review page and require an exact fixture URL and release identifier. The example uses a local staging fixture and an extra tab to catch a common mistake. It runs on Node.js 22 and playwright-core@1.65.1. Use the companion fixture.mjs and install local Chromium with npx playwright-core install chromium for the standalone path.
Step 1. Prepare the opener and the expected child
Start node fixture.mjs. The approved opener is /opener and the expected child is /child. The child shows the heading Release preview and a marker for fixture-42. The script also creates a decoy tab for /status. In a real application, derive the approved destination and marker from the authorized work item before initiating the click.
Step 2. Connect a worker to the correct browser
Save the shared modules and choose a local run or the loopback CDP verification path. If you are using a managed browser, use an owned ready session and a corresponding approved target that is reachable from that environment. Configure NSTDATA_API_KEY, NSTDATA_SESSION_ID, and optional workspace selection. The workflow was exercised on local Chromium and loopback CDP. It needs an authorized workspace to test the managed branch. Nstdata browser automation guide.
const root = 'https://api.nstdata.io/api/v1/cloud-browser'; export async function api(method, path, body) { const key = process.env.NSTDATA_API_KEY; if (!key) throw new Error('Set NSTDATA_API_KEY'); const headers = { 'x-api-key': key }; if (process.env.NSTDATA_TEAM_ID) headers['x-team-id'] = process.env.NSTDATA_TEAM_ID; if (body) headers['content-type'] = 'application/json'; let response; try { response = await fetch(root + path, { method, headers, redirect: 'error', body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(20_000), }); } catch { throw Object.assign(new Error('API transport failed; reconcile the original operation'), { retryable: true }); } const retryable = response.status === 429 || response.status >= 500; let result; try { result = await response.json(); } catch { throw Object.assign(new Error('Invalid API JSON'), { retryable }); } if (!response.ok || result.err === true || result.success === false) { throw Object.assign(new Error(`Cloud Browser API HTTP ${response.status}`), { retryable }); } if (!result.data) throw new Error('Missing API data'); return result.data; } export async function connection(id) { if (!id) throw new Error('Set NSTDATA_SESSION_ID'); const path = `/sessions/${encodeURIComponent(id)}`; const session = await api('GET', path); if (session.state !== 'ready') throw new Error(`Session is ${session.state}, not ready`); const c = await api('POST', path + '/automation-credentials'); if (c.sessionId !== id || !c.headerName || !c.accessToken || !(Date.parse(c.expiresAt) > Date.now()) || new URL(c.cdpUrl).protocol !== 'wss:') { throw new Error('Invalid or expired CDP credentials'); } return { endpoint: c.cdpUrl, headers: { [c.headerName]: c.headerName.toLowerCase() === 'authorization' ? `Bearer ${c.accessToken}` : c.accessToken }, }; } export async function endpoint() { // An isolated local CDP endpoint can test the client without managed credentials. if (process.env.LOCAL_CDP_URL) { const url = new URL(process.env.LOCAL_CDP_URL); if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)) { throw new Error('LOCAL_CDP_URL must use loopback'); } return { endpoint: url.href, headers: {} }; } return connection(process.env.NSTDATA_SESSION_ID); }
import { chromium } from 'playwright-core'; import { endpoint } from './cloud-api.mjs'; export async function withPage(task) { const origin = new URL(process.env.APP_ORIGIN ?? 'http://127.0.0.1:4173'); const remote = Boolean(process.env.LOCAL_CDP_URL || process.env.NSTDATA_SESSION_ID); if (!remote && origin.hostname !== '127.0.0.1') throw Error('Use the local fixture for local runs'); const connection = remote ? await endpoint() : null; const browser = connection ? await chromium.connectOverCDP(connection.endpoint, { headers: connection.headers, timeout: 15_000 }) : await chromium.launch({ args: ['--no-proxy-server'] }); let page; try { const context = remote ? browser.contexts()[0] : await browser.newContext(); if (!context) throw Error('Expected a browser context'); page = await context.newPage(); page.setDefaultTimeout(8_000); page.setDefaultNavigationTimeout(10_000); return await task(page, origin); } finally { try { await page?.close(); } finally { await browser.close(); } } }
Step 3. Register the event and click
Save the example as popup.mjs, then run node popup.mjs. The event promise is registered before the link click. The returned popup is kept in a dedicated variable. The script verifies its route and that its content refers to the expected test revision. It also proves that the opener did not navigate away and that the popup belongs to that page. The Playwright Page API reference documents popup and opener semantics.
import assert from 'node:assert/strict'; import { withPage } from './browser.mjs'; await withPage(async (page, origin) => { const decoy = await page.context().newPage(); let popup; try { await decoy.goto(new URL('/status', origin).href); const entry = new URL('/opener', origin).href; assert((await page.goto(entry, { waitUntil: 'domcontentloaded' }))?.ok()); assert.equal(page.url(), entry); [popup] = await Promise.all([ page.waitForEvent('popup', { timeout: 8_000 }), page.getByRole('link', { name: 'Open preview', exact: true }).click(), ]); await popup.waitForURL(new URL('/child', origin).href, { timeout: 8_000 }); await popup.getByRole('heading', { name: 'Release preview', exact: true }).waitFor(); assert.equal((await popup.locator('output[data-release="fixture-42"]').textContent()).trim(), 'ready'); assert.equal(await popup.opener(), page); console.log(JSON.stringify({ parentPreserved: page.url() === entry, release: 'fixture-42', ready: true })); } finally { try { await popup?.close(); } finally { await decoy.close(); } } });
Step 4. End the child workflow under known ownership
Close the child and decoy created by the example. If another job owns tabs in that runtime, leave those tabs alone. Record which page the outcome came from. Stop the managed session only when the controller verifies that all authorized work on it is complete. The browser session management guide shows where shutdown belongs.
[Screenshot: Show the staging review page and the verified child preview with synthetic release ID. Keep other tabs and signed addresses outside the screenshot.]
Why does the popup wait time out or target the wrong tab?
A popup wait usually fails because the listener is late, the opener is wrong, the app navigated in the same tab, or the expected content never arrived. Find which milestone occurred. Check the button's documented behavior and subscribe on the appropriate page. A tab may appear before its final URL or content is ready, so verify both independently.
| Symptom | Likely explanation | How to recover |
|---|---|---|
| Event times out but URL changed | The original page navigated | Wait for the known same-tab destination, then verify content |
| Context event picked an unrelated tab | Another page created it | Scope the wait to the opener or correlate the returned page before acting |
| New tab opens with a blank page | Target navigation is pending or failed | Wait for the approved route and result with a bounded timeout |
| Popup closes before the next step | The app finished or rejected the workflow | Read the parent or server receipt before retrying |
| Unexpected destination or extra tab | The workflow differs from the approved fixture | Stop that action and investigate with a safe page identifier |
If the new page is part of a sensitive workflow, keep its full URL out of logs and avoid recording private tabs by default. The console and network debugging guide helps identify which page and route actually produced the failure.
How do you handle a workflow that sometimes stays in the same tab?
Handle optional navigation by defining two expected outcomes and adding a bounded observation for each. An application might open a preview in a new tab only for certain account roles. Instrument the actual behavior in the approved test environment and keep the contract visible in your cases. A configuration that always uses a popup should still fail if it silently falls back to the parent instead.
For genuine alternatives, begin the appropriate waits before clicking and keep any listeners scoped to that action. When one outcome is established, cancel or retire the unused observation cleanly so it does not affect the next step. Verify the target separately from the type of transition. Match the expected origin and intended revision on both paths and keep evidence that shows which path passed.
How does Nstdata Cloud Browser support multi-page workflows?
Nstdata Cloud Browser provides managed cloud browsers for browser automation and AI agents. Use CDP to attach to the selected session and derive page ownership from the application and client. Live View gives an authorized operator a way to review the active page when a flow behaves differently from the fixture. The worker still verifies the new page and coordinates its lifetime with the controller.
- Page-aware automation. Lease one job's page objects and validate the exact opener or approved destination.
- Operator review. Use documented diagnostics or Live View if a multi-page flow needs supervised investigation.
- Predictable cleanup. Close only pages created by the workflow and verify managed shutdown through its separate lifecycle.
What should a multitab regression test establish?
A multitab regression test should establish that the expected user action created exactly the intended target page and preserved or changed the opener as designed. Run a test with another page present, compare the application marker, and trigger a controlled failure where the popup does not show the expected revision. Log the selected outcome instead of a general count of tabs.
For a capture workflow, add verified remote screenshots only after you can identify the intended child page and its stable content.
FAQ
Q: What is the difference between the popup and page events?
The popup event belongs to a known opener. The page event on a browser context can observe new pages created within that context more broadly.
Q: Does Playwright need the new tab to be visually focused?
Playwright actions target the page object you use. Verify that the returned object represents the intended page.
Q: Can you assume context.pages().at(-1) is the new page?
Avoid relying on page order for ownership. Capture the corresponding event and check the target or task marker.
Q: What if the link stays in the same tab?
Wait for the original page's expected URL and verify the resulting content. A same-tab navigation does not emit an opener popup event.
Q: Should closing a popup close the managed browser?
Close the popup you own without ending unrelated browser work. Stop the managed session through the owning controller when its job is done.





