Multi-Tab Testing in Playwright
Multi-Tab Testing in Playwright
Playwright is a powerful testing framework that supports automating multiple browser tabs or pages simultaneously. Testing scenarios involving multiple tabs are common in real-world web applications, such as workflows that open new tabs for authentication, payment, or external links.
π Key Concepts
Each browser tab or window is represented by a Page object in Playwright.
You can create, switch between, and control multiple pages (tabs) in a single browser context.
Playwright provides events and APIs to listen for new pages (tabs) and interact with them.
π How to Handle Multiple Tabs
1. Open a New Tab
You can open a new tab explicitly:
javascript
Copy
Edit
const newPage = await context.newPage();
await newPage.goto('https://example.com');
Or, open a link that opens in a new tab, then listen for that event:
javascript
Copy
Edit
const [newPage] = await Promise.all([
context.waitForEvent('page'), // Wait for new tab
page.click('a[target="_blank"]'), // Action that opens new tab
]);
await newPage.waitForLoadState();
console.log(await newPage.title());
2. Switching Between Tabs
You can keep references to multiple pages (tabs) and switch by calling actions on them:
javascript
Copy
Edit
await page.bringToFront(); // Switch focus to original tab
await newPage.bringToFront(); // Switch focus to new tab
3. Example: Multi-Tab Test Scenario
javascript
Copy
Edit
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
// Open the first tab
const page = await context.newPage();
await page.goto('https://example.com');
// Click a link that opens a new tab
const [newPage] = await Promise.all([
context.waitForEvent('page'), // Wait for new tab to open
page.click('a[target="_blank"]'),
]);
// Interact with new tab
await newPage.waitForLoadState();
console.log('New tab title:', await newPage.title());
// Switch back to first tab
await page.bringToFront();
await browser.close();
})();
π Tips for Multi-Tab Testing
Use context.waitForEvent('page') to reliably catch new tabs or popups.
Remember each tab is independent; handle navigation, selectors, and waits separately.
Use bringToFront() to focus a specific tab before interacting with it.
Clean up by closing tabs or the browser context after tests.
✅ Summary
Multi-tab testing in Playwright lets you automate complex flows involving multiple browser tabs or windows easily. By listening for new page events and managing multiple Page objects, you can write reliable and maintainable tests for multi-tab scenarios.
Learn Playwright Training Course in Hyderabad
Read More
Testing Shadow DOM Elements with Playwright
Writing Custom Reporters in Playwright
Using Playwright for Mobile Web Testing
Custom Helpers and Utilities in Playwright
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment