π‘οΈ What is a BrowserContext in Playwright?
A BrowserContext is an isolated, incognito-equivalent profile running inside an active browser engine instance. While traditional frameworks force test runners to spawn an entire new browser operating system process (consuming several hundred megabytes of RAM and taking seconds to start), Playwright initializes a completely clean BrowserContext in under 15 milliseconds. Each context maintains its own independent storage, cookies, cache, local/session storage, proxy configuration, viewport geometry, permissions, and network routing rules without any cross-test contamination.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BROWSER INSTANCE (Single OS Process) β
β β
β ββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββ β
β β BrowserContext 1 (Admin) β β BrowserContext 2 (Buyer) β β
β β ββ Cookies: session_id=ADMIN_9901 β β ββ Cookies: session_id=BUYER_42β β
β β ββ LocalStorage: role="sysadmin" β β ββ LocalStorage: role="shopper"β β
β β ββ Permissions: ["notifications"] β β ββ Geolocation: Pune (18.5204) β β
β β ββ Pages: [ Page A ] β β ββ Pages: [ Page B, Page C ] β β
β ββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# 1. Spawn isolated context for Admin User
admin_context = browser.new_context()
admin_page = admin_context.new_page()
admin_page.goto("https://demo.playwright.dev/todomvc/")
admin_input = admin_page.get_by_placeholder("What needs to be done?")
admin_input.fill("Inventory Item #801 - In Stock")
admin_input.press("Enter")
print("Admin Action: Item created in Admin context.")
# 2. Spawn completely separate context for Customer User (Zero shared cookies/storage)
customer_context = browser.new_context()
customer_page = customer_context.new_page()
customer_page.goto("https://demo.playwright.dev/todomvc/")
# Customer context starts with a pristine, empty local storage
customer_items = customer_page.locator(".todo-list li").count()
print(f"Customer View: Visible items in fresh buyer context = {customer_items}")
# Clean teardown of both contexts
admin_context.close()
customer_context.close()
browser.close()
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# 1. Load exact mobile device profile from registry
iphone_13 = p.devices["iPhone 13"]
mobile_context = browser.new_context(**iphone_13)
mobile_page = mobile_context.new_page()
mobile_page.goto("https://example.com")
viewport = mobile_page.viewport_size
user_agent = mobile_page.evaluate("navigator.userAgent")
print("Mobile Emulation Profile (iPhone 13):")
print(f" Viewport Resolution: {viewport['width']}x{viewport['height']}")
print(f" Emulated User Agent: {user_agent[:45]}...")
mobile_context.close()
# 2. Custom Responsive Tablet Profile
tablet_context = browser.new_context(
viewport={"width": 820, "height": 1180},
device_scale_factor=2,
is_mobile=True,
has_touch=True
)
tablet_page = tablet_context.new_page()
tablet_page.goto("https://example.com")
print(f"Tablet Context Initialized: 820x1180 with touch enabled.")
tablet_context.close()
browser.close()
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# Configure context with coordinates for Pune, Maharashtra (18.5204Β° N, 73.8567Β° E)
context = browser.new_context(
permissions=["geolocation"],
geolocation={"latitude": 18.5204, "longitude": 73.8567, "accuracy": 10}
)
page = context.new_page()
# Verify browser navigator API returns mock GPS position
page.goto("https://example.com")
geo_data = page.evaluate("""() => new Promise(resolve => {
navigator.geolocation.getCurrentPosition(pos => {
resolve({
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
});
});
})""")
print("Emulated Browser Geolocation Readout:")
print(f" Latitude : {geo_data['latitude']}Β° N")
print(f" Longitude : {geo_data['longitude']}Β° E")
print("Status: Verified target coordinates delivered to client script.")
context.close()
browser.close()
locale, timezone_id, and color_scheme directly at the context boundary.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# Configure regional Indian locale, IST timezone, and dark mode theme
context = browser.new_context(
locale="en-IN",
timezone_id="Asia/Kolkata",
color_scheme="dark"
)
page = context.new_page()
page.goto("https://example.com")
# Read client formatting evaluated by the browser JavaScript engine
client_eval = page.evaluate("""() => ({
formattedDate: new Intl.DateTimeFormat().format(new Date()),
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
prefersDark: window.matchMedia('(prefers-color-scheme: dark)').matches
})""")
print("Context Regional Configuration Audit:")
print(f" Intl Date Format : {client_eval['formattedDate']}")
print(f" Browser TimeZone : {client_eval['timeZone']}")
print(f" Dark Theme Active: {client_eval['prefersDark']}")
context.close()
browser.close()
BrowserContext before navigating to target pages.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# Pre-inject session and consent cookies
cookies_to_add = [
{
"name": "auth_token",
"value": "SECURE_JWT_TOKEN_9921",
"domain": ".example.com",
"path": "/",
"httpOnly": True,
"secure": True
},
{
"name": "cookie_consent",
"value": "accepted_all",
"domain": ".example.com",
"path": "/"
}
]
context.add_cookies(cookies_to_add)
# Read back registered cookies across the context
active_cookies = context.cookies("https://example.com")
print(f"Successfully Pre-loaded {len(active_cookies)} Cookies into Context:")
for c in active_cookies:
print(f" Cookie: '{c['name']}' = '{c['value']}' (HttpOnly: {c['httpOnly']})")
# Clear cookies dynamically during test execution
context.clear_cookies()
print(f"Cookies after clearing: {len(context.cookies())}")
context.close()
browser.close()
launch_persistent_context() to preserve profile state across test runs on disk or load unpacked browser extensions for custom internal tools testing.
import os
import tempfile
from playwright.sync_api import sync_playwright
profile_dir = os.path.join(tempfile.gettempdir(), "test_user_profile_dir")
with sync_playwright() as p:
# Launches a persistent context bound directly to a disk folder
persistent_context = p.chromium.launch_persistent_context(
user_data_dir=profile_dir,
headless=True,
args=["--disable-blink-features=AutomationControlled"]
)
page = persistent_context.pages[0] if persistent_context.pages else persistent_context.new_page()
page.goto("https://demo.playwright.dev/todomvc/")
# Store custom data
page.evaluate("() => localStorage.setItem('profile_owner', 'Nikita Infotech')")
retrieved = page.evaluate("() => localStorage.getItem('profile_owner')")
print(f"Persistent Storage Path: {profile_dir}")
print(f"Persisted Value Verified: '{retrieved}'")
persistent_context.close()
context.route() applies network rules across every single tab and popup opened within that profile, blocking analytics scripts and heavyweight imagery globally.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
aborted_requests = []
# Global context-level interception handler
def block_unwanted_resources(route):
res_type = route.request.resource_type
if res_type in ["image", "media", "font"]:
aborted_requests.append(route.request.url)
route.abort()
else:
route.continue_()
# Bind route pattern across all current and future pages in this context
context.route("**/*", block_unwanted_resources)
page = context.new_page()
page.goto("https://quotes.toscrape.com/")
print(f"Page Title: '{page.title()}'")
print(f"Total Blocked Media Requests: {len(aborted_requests)}")
print(f"Sample Blocked Resource URL: {aborted_requests[0] if aborted_requests else 'None'}")
context.close()
browser.close()
X-Test-Execution-ID) on every outbound request.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# Supply HTTP Basic Auth credentials and global custom headers
context = browser.new_context(
http_credentials={"username": "testuser", "password": "securepassword123"},
extra_http_headers={
"X-Automation-Suite": "Playwright-Enterprise",
"X-Client-Version": "2.4.0"
}
)
page = context.new_page()
# Verify custom headers on an echo server
page.goto("https://httpbin.org/headers")
headers_text = page.inner_text("pre")
print("Outbound Request Headers Transmitted by Context:")
for line in headers_text.splitlines():
if "X-Automation-Suite" in line or "X-Client-Version" in line:
print(" ", line.strip())
context.close()
browser.close()
browser.new_context() for enterprise Python automation frameworks.
BROWSER CONTEXT CONFIGURATION PARAMETERS MATRIX:
ββββββββββββββββββββββββ¬βββββββββββββββββ¬βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Parameter β Type β Default β Description / Use Case β
ββββββββββββββββββββββββΌβββββββββββββββββΌβββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β viewport β Dict[int, int] β {"width": 1280, ...} β Default page width and height dimensions in pixels. β
β is_mobile β bool β False β Emulates mobile viewport behavior and meta-viewport tagβ
β has_touch β bool β False β Enables touch event dispatch on the DOM. β
β user_agent β str β Default Engine UA β Overrides client User-Agent header string. β
β locale β str β Host System Locale β Overrides browser language (e.g., "en-IN", "fr-FR"). β
β timezone_id β str β Host System Timezone β Overrides browser clock timezone (e.g., "Asia/Kolkata").β
β permissions β List[str] β [] β Grants browser API rights ("geolocation", "clipboard"). β
β geolocation β Dict[float] β None β Sets mock GPS coordinates (latitude, longitude, acc). β
β color_scheme β str β "no-preference" β Toggles CSS media queries: "light", "dark", or "no-...".β
β extra_http_headers β Dict[str, str] β {} β Custom HTTP headers sent on all requests in context. β
β http_credentials β Dict[str, str] β None β Automatically answers HTTP Basic authentication prompts.β
β storage_state β str / dict β None β Pre-populates cookies and localStorage from file/dict. β
β record_video_dir β str β None β Records all page interactions into video files on disk. β
β ignore_https_errors β bool β False β Ignores self-signed SSL certificate security warnings. β
ββββββββββββββββββββββββ΄βββββββββββββββββ΄βββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ