Browser contexts and pages are fundamental concepts in Playwright that enable powerful, isolated testing strategies. In this guide, you'll learn how to leverage these features to create robust, scalable web automation and testing solutions.
Prerequisites#
- Node.js (v16+ recommended)
- npm or yarn package manager
- Basic TypeScript knowledge
- Playwright installed (v1.30+)
- Code editor (VS Code recommended)
- Estimated setup time: 15-20 minutes
Understanding Browser Contexts in Playwright#
Browser contexts are lightweight, isolated environments within a browser instance. Think of them as private browsing windows that don't share cookies, cache, or state. This isolation is crucial for creating independent test scenarios.
Why Browser Contexts Matter#
Browser contexts allow you to simulate multiple user sessions simultaneously without complex configuration. Each context acts like a separate browser profile.
import { chromium } from "playwright";async function createMultipleContexts() {// Create a browser instanceconst browser = await chromium.launch();// Create two independent browser contextsconst adminContext = await browser.newContext();const userContext = await browser.newContext();// Each context can have different settingsconst adminPage = await adminContext.newPage();const userPage = await userContext.newPage();// Perform isolated actions in each contextawait adminPage.goto("https://admin.example.com");await userPage.goto("https://user.example.com");}
import { chromium } from "playwright";async function createMultipleContexts() {// Create a browser instanceconst browser = await chromium.launch();// Create two independent browser contextsconst adminContext = await browser.newContext();const userContext = await browser.newContext();// Each context can have different settingsconst adminPage = await adminContext.newPage();const userPage = await userContext.newPage();// Perform isolated actions in each contextawait adminPage.goto("https://admin.example.com");await userPage.goto("https://user.example.com");}
Page Management and Isolation#
Pages represent individual browser tabs or windows within a context. Each page can have its own unique configuration, navigation history, and state.
Creating and Managing Pages#
async function multiPageTesting() {const browser = await chromium.launch();const context = await browser.newContext();// Open multiple pages in the same contextconst loginPage = await context.newPage();const dashboardPage = await context.newPage();const profilePage = await context.newPage();// Navigate independentlyawait loginPage.goto("https://app.example.com/login");await dashboardPage.goto("https://app.example.com/dashboard");}
async function multiPageTesting() {const browser = await chromium.launch();const context = await browser.newContext();// Open multiple pages in the same contextconst loginPage = await context.newPage();const dashboardPage = await context.newPage();const profilePage = await context.newPage();// Navigate independentlyawait loginPage.goto("https://app.example.com/login");await dashboardPage.goto("https://app.example.com/dashboard");}
Context Configuration Options#
Be cautious when configuring contexts. Some settings can impact test reproducibility if not managed carefully.
const context = await browser.newContext({viewport: { width: 1280, height: 720 },geolocation: { latitude: 41.8781, longitude: -87.6298 },permissions: ["geolocation"],});
const context = await browser.newContext({viewport: { width: 1280, height: 720 },geolocation: { latitude: 41.8781, longitude: -87.6298 },permissions: ["geolocation"],});
Advanced Isolation Techniques#
Handling Authentication#
async function authenticatedContexts() {const browser = await chromium.launch();// Create a context with pre-authenticated sessionconst context = await browser.newContext();const page = await context.newPage();// Perform login onceawait page.goto("https://example.com/login");await page.fill("#username", "testuser");await page.fill("#password", "securepassword");await page.click('button[type="submit"]');// Store authentication stateawait context.storageState({ path: "auth.json" });}
async function authenticatedContexts() {const browser = await chromium.launch();// Create a context with pre-authenticated sessionconst context = await browser.newContext();const page = await context.newPage();// Perform login onceawait page.goto("https://example.com/login");await page.fill("#username", "testuser");await page.fill("#password", "securepassword");await page.click('button[type="submit"]');// Store authentication stateawait context.storageState({ path: "auth.json" });}
Troubleshooting#
Best Practices#
- Always create a new context for each test scenario
- Use
context.close()to release browser resources - Configure contexts with specific requirements
- Store and reuse authentication states
- Monitor memory usage when creating multiple contexts
- Use viewport settings for consistent rendering
- Implement proper error handling in async context methods
Next Steps#
- Explore Playwright's network interception capabilities
- Learn about browser emulation techniques
- Investigate cross-browser testing strategies
- Study advanced page object model implementations
- Dive into parallel test execution with contexts