What is a browser context in Playwright?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 25: Frames, Tabs, Files and Login State.
- Working with Iframes & Shadow DOM
- Multiple Tabs, Windows & Popups
- File Uploads, Downloads & Screenshots
- Authentication & Storage State
- Practice and interview questions: Advanced Playwright Techniques
Playwright's docs describe contexts as "equivalent to incognito-like profiles" and say they "are fast and cheap to create and are completely isolated, even when running in a single browser." Launching a browser is slow; a context is quick, which is why Playwright can give every test a new one.
Most of the time you never create one yourself. The page fixture already belongs to a fresh context the runner made for that test. You reach for browser.newContext() when one test needs two separate people, such as a manager and a customer, or an admin and a user.
In the example, the test opens two contexts. The manager's page uses ?autologin=1, so it is signed in and sees the grinder's price, ₹11,900. The visitor's page has no sign-in and sees Sign in for pricing on the same card. Sign-in on this app is kept in local storage, and the two contexts do not share it, so each sees its own version of the page. The test closes both contexts at the end, because it created them.
import { test, expect } from '@playwright/test';
test('a signed-in and a signed-out visitor at the same time', async ({ browser }) => {
const managerContext = await browser.newContext();
const visitorContext = await browser.newContext();
const manager = await managerContext.newPage();
const visitor = await visitorContext.newPage();
await manager.goto('/catalog.html?mock=static&seed=42&autologin=1');
await visitor.goto('/catalog.html?mock=static&seed=42');
const price = (page) =>
page.locator('article[data-sku="MRD-1003"]').getByTestId('product-price');
await expect(price(manager)).toHaveText('₹11,900');
await expect(price(visitor)).toHaveText('Sign in for pricing');
await managerContext.close();
await visitorContext.close();
});1 passed (2.5s)
Practised in the full course: the drill Auth: Signed Out.
See the chapterRelated questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free