πͺ Client-Side Persistence & Storage Architecture
Modern web applications rely on two distinct mechanisms to preserve user state across sessions: HTTP Cookies (managed at the network protocol and browser context level) and Web Storage (comprising HTML5 localStorage and sessionStorage, scoped strictly to domain origins in the DOM window). While Selenium WebDriver requires tedious loop iterations or messy JavaScript executors to inspect and clear client storage, Playwright with Python provides direct, first-class storage primitives. Through context.cookies(), context.add_cookies(), context.clear_cookies(), and targeted JavaScript evaluation via page.evaluate(), engineers can seed shopping carts, set feature flags, verify cookie security flags (Secure, HttpOnly, SameSite), and test session expiration workflows with surgical precision.
CLIENT-SIDE STORAGE TOPOLOGY IN PLAYWRIGHT:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1. HTTP COOKIES (Network & Context Scope: context.cookies(), add_cookies) β
β * Transmitted automatically with every outgoing HTTP header β
β * Security flags: HttpOnly (inaccessible to JS), Secure, SameSite β
β * Domain and Path scoping (e.g. domain=".nikita-infotech.com") β
β * Direct Playwright API: context.cookies(), context.clear_cookies() β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 2. WEB STORAGE (DOM Origin Scope: window.localStorage / sessionStorage) β
β * LocalStorage: Persists indefinitely across browser restarts β
β * SessionStorage: Scoped strictly to single active tab lifecycle β
β * Inaccessible over HTTP headers; read strictly via browser JavaScript β
β * Playwright Access: page.evaluate("() => localStorage.getItem(...)") β
β * Pre-seed Access : page.add_init_script(...) before document mounts β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# Pre-populate cookies across multiple domains
context.add_cookies([
{
"name": "session_id",
"value": "SESS_AUTH_99482",
"domain": "httpbin.org",
"path": "/",
"httpOnly": True,
"secure": True,
"sameSite": "Lax"
},
{
"name": "theme_preference",
"value": "dark",
"domain": "example.com",
"path": "/"
}
])
# 1. Fetch all cookies in the context
all_cookies = context.cookies()
print(f"Total Cookies in Context: {len(all_cookies)}")
# 2. Filter cookies strictly for a target URL
target_cookies = context.cookies("https://httpbin.org")
print(f"Cookies scoped to httpbin.org: {len(target_cookies)}")
for cookie in target_cookies:
print(" Cookie Name :", cookie["name"])
print(" Cookie Value :", cookie["value"])
print(" HttpOnly Flag :", cookie["httpOnly"])
print(" Secure Flag :", cookie["secure"])
print(" SameSite Policy :", cookie["sameSite"])
assert target_cookies[0]["value"] == "SESS_AUTH_99482"
assert target_cookies[0]["httpOnly"] is True
context.close()
browser.close()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# Pre-inject GDPR cookie consent and currency preference
context.add_cookies([
{
"name": "cookie_consent_accepted",
"value": "true",
"domain": "httpbin.org",
"path": "/"
},
{
"name": "selected_currency",
"value": "INR",
"domain": "httpbin.org",
"path": "/"
}
])
page = context.new_page()
page.goto("https://httpbin.org/cookies")
cookies_rendered = page.inner_text("pre")
print("Injected Cookies Read by Remote Server:")
print(cookies_rendered.strip())
assert "cookie_consent_accepted" in cookies_rendered
assert "INR" in cookies_rendered
print("Verified remote server received both pre-injected cookies!")
context.close()
browser.close()
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# Set initial authentication cookies
context.add_cookies([
{"name": "auth_token", "value": "TOKEN_XYZ", "domain": "httpbin.org", "path": "/"},
{"name": "user_role", "value": "admin", "domain": "httpbin.org", "path": "/"}
])
print(f"Cookie count before clearing: {len(context.cookies())}")
assert len(context.cookies()) == 2
# Clear all cookies across the context
context.clear_cookies()
print(f"Cookie count after context.clear_cookies(): {len(context.cookies())}")
assert len(context.cookies()) == 0
# Verify remote server receives empty cookie dictionary
page = context.new_page()
page.goto("https://httpbin.org/cookies")
page_text = page.inner_text("pre")
print(f"Server verified cookie payload:\n{page_text.strip()}")
assert '"cookies": {}' in page_text
context.close()
browser.close()
window.localStorage using page.evaluate(): set items, retrieve structured JSON entries, inspect storage lengths, and assert persisted keys.
import json
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com")
# 1. WRITE to LocalStorage via evaluate()
user_payload = {"user_id": 1042, "name": "Pooja Patil", "role": "Architect"}
page.evaluate(f"item => localStorage.setItem('user_profile', JSON.stringify(item))", user_payload)
page.evaluate("() => localStorage.setItem('app_theme', 'dark')")
# 2. READ from LocalStorage
theme = page.evaluate("() => localStorage.getItem('app_theme')")
profile_str = page.evaluate("() => localStorage.getItem('user_profile')")
parsed_profile = json.loads(profile_str)
storage_length = page.evaluate("() => localStorage.length")
print("LocalStorage Read Verification:")
print(f" Storage Items Count : {storage_length}")
print(f" App Theme Setting : '{theme}'")
print(f" Profile Name : '{parsed_profile['name']}'")
print(f" Profile Role : '{parsed_profile['role']}'")
assert theme == "dark"
assert parsed_profile["name"] == "Pooja Patil"
# 3. DELETE specific key & verify
page.evaluate("() => localStorage.removeItem('app_theme')")
assert page.evaluate("() => localStorage.getItem('app_theme')") is None
print("Successfully removed 'app_theme' key from LocalStorage.")
browser.close()
localStorage synchronously on bootstrap before rendering components. Pre-populate storage before DOM parsing with add_init_script().
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Pre-seed LocalStorage BEFORE navigating to target origin
page.add_init_script("""() => {
window.localStorage.setItem('cart_items', JSON.stringify([
{ id: 'SKU-OPTIC-1', name: 'Optic Sensor Relay', qty: 2 },
{ id: 'SKU-IOT-09', name: 'Industrial Gateway', qty: 1 }
]));
window.localStorage.setItem('discount_code', 'DIWALI2026');
}""")
# Simulated e-commerce cart that reads localStorage on initial mount
page.set_content("""
Checkout Summary
Loading cart...
None
""")
cart_label = page.locator("#cart-display")
coupon_label = page.locator("#coupon-display")
expect(cart_label).to_have_text("Items in Cart: 2")
expect(coupon_label).to_have_text("Applied: DIWALI2026")
print(f"Verified UI Cart State : '{cart_label.inner_text()}'")
print(f"Verified Coupon State : '{coupon_label.inner_text()}'")
browser.close()
window.sessionStorage, which isolates data strictly to a single browser tab and clears automatically when that tab is closed.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
tab1 = context.new_page()
tab1.goto("https://example.com")
# 1. Write to sessionStorage on Tab 1
tab1.evaluate("() => sessionStorage.setItem('wizard_step', 'STEP_3_CONFIRMATION')")
val_tab1 = tab1.evaluate("() => sessionStorage.getItem('wizard_step')")
print(f"Tab 1 SessionStorage Value : '{val_tab1}'")
# 2. Open Tab 2 to the same URL - SessionStorage is completely isolated!
tab2 = context.new_page()
tab2.goto("https://example.com")
val_tab2 = tab2.evaluate("() => sessionStorage.getItem('wizard_step')")
print(f"Tab 2 SessionStorage Value : {val_tab2} (Isolated per tab)")
assert val_tab1 == "STEP_3_CONFIRMATION"
assert val_tab2 is None
print("SessionStorage tab-level isolation verified successfully!")
context.close()
browser.close()
localStorage into a native Python dictionary in a single execution call for comprehensive assertions or debug logging.
from playwright.sync_api import sync_playwright
def get_all_local_storage(page) -> dict:
"""Extracts all localStorage keys and values as a Python dictionary."""
return page.evaluate("""() => {
let items = {};
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
items[key] = localStorage.getItem(key);
}
return items;
}""")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com")
# Populate multiple keys
page.evaluate("""() => {
localStorage.setItem('auth_token', 'TOKEN_ABC');
localStorage.setItem('user_locale', 'en-IN');
localStorage.setItem('sidebar_collapsed', 'false');
}""")
# Dump all localStorage keys in one call
storage_dump = get_all_local_storage(page)
print("Complete LocalStorage Dump Extracted:")
for key, value in storage_dump.items():
print(f" {key:18s} -> {value}")
assert storage_dump["auth_token"] == "TOKEN_ABC"
assert storage_dump["user_locale"] == "en-IN"
assert len(storage_dump) == 3
browser.close()
page instance to test functions.
# content of conftest.py
import pytest
from playwright.sync_api import Browser, Page
@pytest.fixture
def preseeded_page(browser: Browser) -> Page:
"""Fixture providing a page pre-populated with cookies and LocalStorage tokens."""
context = browser.new_context()
# 1. Inject Cookies
context.add_cookies([{
"name": "session_auth",
"value": "VALID_AUTH_COOKIE_2026",
"domain": "example.com",
"path": "/"
}])
# 2. Inject LocalStorage via init script
context.add_init_script("""() => {
window.localStorage.setItem('user_role', 'ENTERPRISE_ADMIN');
window.localStorage.setItem('telemetry_optin', 'false');
}""")
page = context.new_page()
yield page
context.close()
# content of test_storage_suite.py
def test_dashboard_with_preseeded_storage(preseeded_page: Page):
preseeded_page.goto("https://example.com")
role = preseeded_page.evaluate("() => localStorage.getItem('user_role')")
cookies = preseeded_page.context.cookies("https://example.com")
assert role == "ENTERPRISE_ADMIN"
assert any(c["name"] == "session_auth" for c in cookies)
print("Pytest test executed with pre-seeded cookies and LocalStorage!")
COOKIES & WEB STORAGE REFERENCE MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Method / Expression β Target Layer / Scope β Description / Primary Use Case β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β context.cookies(urls) β BrowserContext (Cookies) β Retrieves all cookies or filtered by URL list. β
β context.add_cookies(cookies) β BrowserContext (Cookies) β Injects list of cookie dicts (name, value, domain...). β
β context.clear_cookies() β BrowserContext (Cookies) β Clears all active cookies across the context. β
β page.evaluate(localStorage) β Page DOM (localStorage) β Executes localStorage getItem, setItem, removeItem. β
β page.add_init_script(...) β Page / Context Initializationβ Pre-populates localStorage before scripts run. β
β page.evaluate(sessionStorage)β Page DOM (sessionStorage) β Manages tab-isolated sessionStorage entries. β
β context.storage_state() β Full Session Snapshot β Dumps all cookies + localStorage origins to dict/JSON. β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β COOKIE DICTIONARY REQUIRED / OPTIONAL KEYS: β
β * "name" : str (Required) βββΊ The cookie identifier name. β
β * "value" : str (Required) βββΊ The cookie string value. β
β * "domain" : str (Required*) βββΊ Target domain (e.g. "example.com" or ".example.com"). Either domain or url req. β
β * "path" : str (Required*) βββΊ URL path (typically "/"). β
β * "url" : str (Optional) βββΊ Alternative to supplying domain and path explicitly. β
β * "httpOnly" : bool (Optional) βββΊ Restricts client JavaScript access (security best practice). β
β * "secure" : bool (Optional) βββΊ Enforces HTTPS-only transmission. β
β * "sameSite" : "Strict"|"Lax" βββΊ Cross-site request policy enforcement. β
β * "expires" : float (Optional)βββΊ Unix epoch timestamp in seconds indicating expiration. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ