Session Storare in Playwright



Session Storare in Playwright

In Playwright, Session Storage is maintained per page (tab) within a browser context. Unlike Local Storage, there is no direct API like context.storageState() for Session Storage. You typically use page.evaluate() to set or retrieve it.


1. Set Session Storage

import { test } from '@playwright/test';
test('Set Session Storage', async ({ page }) => {
    await page.goto('https://example.com');
    await page.evaluate(() => {
        sessionStorage.setItem('username', 'Anand');
        sessionStorage.setItem('role', 'Admin');
    });
});

2. Get Session Storage Value

import { test } from '@playwright/test';
test('Get Session Storage', async ({ page }) => {
    await page.goto('https://example.com');
    const username = await page.evaluate(() => {
        return sessionStorage.getItem('username');
    });
    console.log(username);
});
Output
Anand

3. Get All Session Storage Values

const sessionData = await page.evaluate(() => {
    const data: Record<string, string> = {};
    for (let i = 0; i < sessionStorage.length; i++) {
        const key = sessionStorage.key(i)!;
        data[key] = sessionStorage.getItem(key)!;
    }

    return data;
});

console.log(sessionData);
Output
{
   username: 'Anand',
   role: 'Admin'
}

4. Remove One Item

await page.evaluate(() => {
    sessionStorage.removeItem('username');
});

5. Clear Session Storage

await page.evaluate(() => {
    sessionStorage.clear();
});

6. Check if a Key Exists

const exists = await page.evaluate(() => {
    return sessionStorage.getItem('username') !== null;
});
console.log(exists);
Output
true

7. Save Session Storage Before Opening the Application

If the application checks Session Storage during page load, use addInitScript():

import { chromium } from '@playwright/test';
const browser = await chromium.launch();
const context = await browser.newContext();
await context.addInitScript(() => {
    sessionStorage.setItem('token', 'ABC123');
    sessionStorage.setItem('user', 'Anand');
});

const page = await context.newPage();
await page.goto('https://example.com');
This ensures the values are present before any application JavaScript runs.

8. Verify Session Storage

await expect(
    page.evaluate(() => sessionStorage.getItem('role'))
).resolves.toBe('Admin');

Session Storage vs Local Storage

Feature Session Storage Local Storage
Scope Per tab/page Shared across pages in the same origin
Lifetime Until the tab is closed Persists until explicitly cleared
Shared with another page in same context? ❌ No ✅ Yes
Shared across browser contexts? ❌ No ❌ No
Access in Playwright page.evaluate() page.evaluate() or storageState() (cookies only; local storage can be initialized with scripts or managed through page evaluation)

Interview Question

Q: How do you handle Session Storage in Playwright?

Answer:

Playwright does not provide a dedicated Session Storage API. Instead, we use page.evaluate() to execute JavaScript in the browser context and call sessionStorage.setItem(), getItem(), removeItem(), or clear(). If Session Storage must exist before the application loads, we use context.addInitScript() to populate it before navigating to the page.

Tags: ,
Leave a comment

Your email address will not be published. Required fields are marked *

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!