Multi-Page and Cross-Origin Testing
Relevant source files
The following files were used as context for generating this wiki page:
Playwright is designed to handle the complexity of modern web applications, which often involve multiple pages, tabs, popups, and interactions across different origins. Its architecture, which runs tests out-of-process, aligns with modern browsers and removes the limitations of typical in-process runners. This enables robust testing of scenarios that span multiple tabs, origins, and even user sessions within a single test.
The core of this capability lies in the BrowserContext, which provides a sandboxed environment for pages, ensuring full test isolation with minimal overhead. This allows for the creation of complex test scenarios that accurately reflect real-world user interactions.
Sources: README.md
Core Concepts
BrowserContext for Isolation and Page Management
A BrowserContext is equivalent to a brand-new browser profile. It provides a self-contained session with its own cookies, local storage, and cache, ensuring that tests are fully isolated from one another. Creating a new context is a lightweight operation, taking only milliseconds.
Key functionalities provided by BrowserContext:
- Creating new pages:
browserContext.newPage()opens a new tab within the context. - Listing existing pages:
browserContext.pages()returns an array of allPageobjects currently active in the context.
This model is fundamental for managing multiple pages in a structured and isolated manner.
Sources: README.md, tests/library/browsercontext-pages.spec.ts:13-20
The following diagram illustrates the relationship between the core components.
This diagram shows how a single Browser instance can manage multiple, isolated BrowserContexts, each with its own set of pages.
Sources: README.md, tests/library/browsercontext-pages.spec.ts
Handling Multiple Pages
Playwright provides event-driven APIs to handle new pages that are opened as a result of user interactions, such as clicking a link that opens a new tab or a popup window.
Popups and New Tabs
The most common way to handle a new page is by waiting for the popup event on the originating page or the page event on the browser context. These events are emitted when a new page is created, for example, through window.open or a link with target="_blank".
The standard pattern involves waiting for the event concurrently with the action that triggers it.
// From tests/library/popup.spec.ts
test('should work', async ({ page, server }) => {
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('a[target=_blank]'),
]);
expect(popup).toBeTruthy();
});
Sources: tests/library/popup.spec.ts:14-20
The following sequence diagram illustrates the flow of handling a popup.
This diagram shows how a test script registers a listener for the popup event before triggering the action, ensuring the new page is captured reliably.
Sources: tests/library/popup.spec.ts
Cross-Origin Testing
Playwright seamlessly handles tests that navigate across different origins. This is a critical feature for testing applications that integrate with third-party services or have micro-frontend architectures.
Cross-Origin Navigation
Navigating to a different origin is as simple as using page.goto(). Playwright's architecture ensures that the test script maintains control over the page regardless of its origin.
Persisting Scripts Across Navigations with addInitScript
A powerful tool for cross-origin testing is page.addInitScript(). This method injects a script that is guaranteed to execute in the page's context before any other scripts, and it persists across all navigations, including cross-origin ones. This is useful for mocking APIs, setting up state, or instrumenting the page.
The following test demonstrates that an init script added on one origin runs correctly after navigating to a different one.
// From tests/page/page-add-init-script.spec.ts
it('should work after a cross origin navigation', async ({ page, server }) => {
await page.goto(server.CROSS_PROCESS_PREFIX);
await page.addInitScript(function() {
window['injected'] = 123;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window['result'])).toBe(123);
});
Sources: tests/page/page-add-init-script.spec.ts:77-85
The init script is also applied to iframes loaded within the page, ensuring consistent behavior across the entire page structure.
Sources: tests/page/page-add-init-script.spec.ts:87-97
Debugging and Tooling
Playwright's tooling is designed to provide deep insights into complex multi-page and cross-origin test executions.
Trace Viewer
The Trace Viewer is an indispensable tool for debugging. It captures a complete, time-traveling record of the test execution, including:
- DOM snapshots for every action.
- Network requests and responses.
- Console logs.
- Source code with execution markers.
This is particularly valuable in multi-page scenarios. For instance, the trace viewer can handle and display parallel API requests made to different origins from different contexts within the same test, preventing hangs and providing a clear picture of all concurrent activities.
Sources: tests/playwright-test/reporter-html.spec.ts:602-621
Test Server for Advanced Scenarios
Playwright's internal test suite uses a TestServerConnection to facilitate communication with the test runner process. This allows for advanced scenarios like intercepting stdio and finding related test files based on dependencies, which is crucial for features like --only-changed. This demonstrates the underlying capability to manage complex, cross-process test orchestration.
Sources: tests/playwright-test/test-server.spec.ts
Key API Reference
The following table summarizes the key API methods for multi-page and cross-origin testing.
| Method/Event | Description | Source File |
|---|---|---|
browserContext.newPage() | Creates a new page (tab) in the browser context. | tests/library/browsercontext-pages.spec.ts:13-20 |
browserContext.pages() | Returns an array of all pages in the context. | tests/library/browsercontext-pages.spec.ts:22-29 |
page.waitForEvent('popup') | Waits for a popup Page to be opened by the current page. | tests/library/popup.spec.ts:14-20 |
context.waitForEvent('page') | Waits for a new Page to be created in the browser context. | tests/library/browsercontext-pages.spec.ts:31-38 |
page.addInitScript() | Adds a script which is executed at the beginning of the document, persisting across navigations. | tests/page/page-add-init-script.spec.ts:18-24 |
page.goto() | Navigates the page to a URL, which can be cross-origin. | tests/page/page-add-init-script.spec.ts:77-85 |
Sources: tests/library/popup.spec.ts, tests/library/browsercontext-pages.spec.ts, tests/page/page-add-init-script.spec.ts