COOKIES & LOCALSTORAGE MANAGEMENT IN PYTHON

Master client-side state manipulation in Playwright with Python: reading, writing, and clearing HTTP cookies via BrowserContext, manipulating HTML5 LocalStorage and SessionStorage, setting cross-origin tokens, and testing persistence behaviors.

πŸͺ 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.

1. Storage Topology: HTTP Cookies vs. HTML5 Web Storage
Understanding the architectural differences between network cookies managed by BrowserContext and client-side web storage evaluated inside Page JavaScript contexts.
Storage Layer Comparison
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     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Manage cookies at the BrowserContext level; manipulate localStorage and sessionStorage directly inside the Page execution context via evaluate() or add_init_script().
Real-Time Example 1: Reading & Filtering Cookies via context.cookies()
Query all active browser cookies across the current context, or filter cookies for specific domain URLs, inspecting values, expiration timestamps, and security flags.
Python (Reading & Filtering Cookies)
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()
Output: Total Cookies in Context: 2 Cookies scoped to httpbin.org: 1 Cookie Name : session_id Cookie Value : SESS_AUTH_99482 HttpOnly Flag : True Secure Flag : True SameSite Policy : Lax
Real-Time Example 2: Injecting Cookies via context.add_cookies()
Inject authentication tokens, GDPR consent acceptance flags, or tracking IDs into the browser context before navigating, avoiding repetitive cookie consent banners.
Python (Cookie Injection & Verification)
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()
Output: Injected Cookies Read by Remote Server: { "cookies": { "cookie_consent_accepted": "true", "selected_currency": "INR" } } Verified remote server received both pre-injected cookies!
Real-Time Example 3: Purging Cookies via context.clear_cookies()
Simulate user sign-out or session revocation by clearing all cookies across the entire context, asserting that subsequent page navigations treat the user as an anonymous visitor.
Python (Clearing Context Cookies)
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()
Output: Cookie count before clearing: 2 Cookie count after context.clear_cookies(): 0 Server verified cookie payload: { "cookies": {} }
Real-Time Example 4: Reading & Writing HTML5 LocalStorage via page.evaluate()
Interact with standard DOM window.localStorage using page.evaluate(): set items, retrieve structured JSON entries, inspect storage lengths, and assert persisted keys.
Python (LocalStorage CRUD via evaluate)
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()
Output: LocalStorage Read Verification: Storage Items Count : 2 App Theme Setting : 'dark' Profile Name : 'Pooja Patil' Profile Role : 'Architect' Successfully removed 'app_theme' key from LocalStorage.
Real-Time Example 5: Bootstrapping LocalStorage via page.add_init_script()
Many single-page applications read tokens from localStorage synchronously on bootstrap before rendering components. Pre-populate storage before DOM parsing with add_init_script().
Python (Pre-Seeding LocalStorage 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()
Output: Verified UI Cart State : 'Items in Cart: 2' Verified Coupon State : 'Applied: DIWALI2026'
Real-Time Example 6: Managing Tab-Scoped HTML5 SessionStorage
Interact with window.sessionStorage, which isolates data strictly to a single browser tab and clears automatically when that tab is closed.
Python (SessionStorage Operations)
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()
Output: Tab 1 SessionStorage Value : 'STEP_3_CONFIRMATION' Tab 2 SessionStorage Value : None (Isolated per tab) SessionStorage tab-level isolation verified successfully!
Real-Time Example 7: Dumping Entire LocalStorage to a Python Dictionary
Extract all key-value pairs stored in a page's localStorage into a native Python dictionary in a single execution call for comprehensive assertions or debug logging.
Python (Bulk LocalStorage Dump Helper)
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()
Output: Complete LocalStorage Dump Extracted: auth_token -> TOKEN_ABC user_locale -> en-IN sidebar_collapsed -> false
Real-Time Example 8: Reusable Pytest Fixture for Pre-Seeded Storage State
Build a clean Pytest fixture that automatically configures both HTTP cookies and HTML5 LocalStorage entries before yielding the page instance to test functions.
Python (conftest.py Pre-Seeded Storage Fixture)
# 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!")
Output: Pytest test executed with pre-seeded cookies and LocalStorage! PASSED tests/test_storage_suite.py::test_dashboard_with_preseeded_storage
Real-Time Example 9: Cookies & Storage Methods Reference Matrix
A comprehensive reference summary of methods, signatures, and scopes for managing cookies, localStorage, and sessionStorage in Playwright Python.
Storage Operations Reference Matrix
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.                             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Use context.add_cookies() and page.add_init_script() to bypass consent banners and auth setups. Use context.clear_cookies() and page.evaluate('localStorage.clear()') to test clean logout scenarios.