How can you leverage Playwright's capabilities to directly manipulate browser storage (Local Storage, Session Storage, Cookies) for efficient test setup and state verification?
Description and use
Playwright enables direct manipulation of localStorage and sessionStorage via page.evaluate(), speeding up test setup and eliminating UI interactions.
Problem
Building robust end-to-end tests often involves cumbersome UI interactions just to get an application into a specific state. Waiting for login flows, setting preferences, or pre-filling forms via the UI can be slow, brittle, and significantly extend test execution times. This impacts feedback loops and CI/CD efficiency.
Outcome
Direct manipulation of browser storage via Playwright’s page.evaluate() speeds up test setup, reduces UI dependency, and ensures state persistence across page reloads.
Workflow
- Navigate to target URL with page.goto()
- Use page.evaluate() to set localStorage.setItem('user_preference','dark_mode')
- Use page.evaluate() to set sessionStorage.setItem('temp_session_data','user_id_123')
- Verify localStorage item with page.evaluate() and expect()
- Verify sessionStorage item with page.evaluate() and expect()
- Reload the page with page.reload()
- Verify localStorage persistence after reload
Evidence
Playwright's page.evaluate() provides direct access to the browser's JavaScript context, enabling powerful manipulation of localStorage and sessionStorage.
page.evaluate() executes JavaScript within the page's context.
Use localStorage.setItem() and sessionStorage.setItem() directly.
- Record date: 2026-10-09T14:11:00.266Z