Playwright Tabs and Windows
A traveler steps out of one train carriage and into a completely new one while the journey continues. A new browser tab works the same way for a test, opening a fresh, independent space that Playwright must consciously step into to keep interacting with the page.
A New Tab Opening
Original Tab (Product Page)
|
v
Click "View Full Terms" Link
|
v
New Tab Opens (Terms Page)
|
v
Playwright Captures and Controls It
Capturing a New Tab
const [newTab] = await Promise.all([
context.waitForEvent('page'),
page.getByRole('link', { name: 'View Full Terms' }).click(),
]);
await newTab.waitForLoadState();This code waits for a new tab to open at the exact moment the link gets clicked, then stores that new tab under the name newTab for later use.
Working Inside the New Tab
await expect(newTab.getByRole('heading', { name: 'Terms and Conditions' })).toBeVisible();
await newTab.close();Once captured, the new tab behaves exactly like the original page object, supporting the same locators, actions, and assertions. Closing it when finished keeps the browser session tidy.
Switching Back to the Original Tab
The original page variable still points to the first tab and remains fully usable throughout the test. A test simply chooses which variable name to act on, depending on which tab needs attention at that moment.
A Real-World Example: A Support Article
A help center article includes a link labeled "Watch Video Tutorial" that opens a video hosting site in a new tab. A test confirms the new tab loads correctly and shows the expected video title, then closes it and continues checking the rest of the original help article page.
Handling Multiple New Tabs
const allPages = context.pages();
console.log(`Currently open tabs: ${allPages.length}`);This lists every currently open tab within the browser context, useful when a page opens several new tabs at once and a test needs to identify the correct one among them.
Waiting for a Specific Tab by Its Title
const [newTab] = await Promise.all([
context.waitForEvent('page'),
page.getByRole('link', { name: 'Live Chat' }).click(),
]);
await expect(newTab).toHaveTitle(/Support Chat/);Checking the title confirms the correct tab actually opened, especially useful on pages that might open different tabs depending on which link a user clicks.
Quick Practice Task
Find a link on any website that opens content in a new tab. Write a test that clicks it, confirms the new tab's title, and closes it afterward.
Key Takeaways
- New tabs need explicit capturing using waitForEvent before use.
- A captured tab works exactly like a normal page object.
- The original tab stays active and available throughout the test.
- Checking a new tab's title confirms the correct one actually opened.
