Ai Driven TestingBeginner

Browser Contexts and Pages in Playwright

Learn about browser contexts and pages for test isolation and multi-tab testing

ObserveOne Team
3 min read

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 instance
const browser = await chromium.launch();
// Create two independent browser contexts
const adminContext = await browser.newContext();
const userContext = await browser.newContext();
// Each context can have different settings
const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();
// Perform isolated actions in each context
await 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 context
const loginPage = await context.newPage();
const dashboardPage = await context.newPage();
const profilePage = await context.newPage();
// Navigate independently
await 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"],
});

Advanced Isolation Techniques#

Handling Authentication#

async function authenticatedContexts() {
const browser = await chromium.launch();
// Create a context with pre-authenticated session
const context = await browser.newContext();
const page = await context.newPage();
// Perform login once
await page.goto("https://example.com/login");
await page.fill("#username", "testuser");
await page.fill("#password", "securepassword");
await page.click('button[type="submit"]');
// Store authentication state
await context.storageState({ path: "auth.json" });
}

Troubleshooting#

Problem
Context not resetting between tests
Solution
Always create a fresh context for each test and close it after use. Use beforeEach and afterEach hooks in your test framework.
Problem
Performance issues with multiple contexts
Solution
Limit concurrent contexts, close unused pages/contexts, and use context.close() to free resources.
Problem
Inconsistent page behavior across contexts
Solution
Ensure you're not sharing browser instances and reset context configurations between tests.

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

Related comparisons

Weighing the tools you just read about? Here's how they stack up side by side.

See alternatives to your stack

Looking to swap one of these out? Here's where to start.

Ready for AI-Powered Testing?

ObserveOne monitors your selectors 24/7 and automatically heals them when websites change. Never deal with broken tests again.

Start Free Trial