All challenges · Expert & Verification

Challenge 27 of 29 · Expert authoring · Verification

Test localStorage State

Write values to the browser’s local storage and read them back, after first giving the page a real origin to store them under.

Skills you will practise

  • localStorage
  • page.evaluate
  • browser origins

The concept

localStorage is a small key-value store the browser keeps per origin, meaning scheme, host and port. Apps use it for themes, drafts, feature flags and sometimes auth tokens. Tests often need to seed it or check it.

Your test reaches it through page.evaluate(), because storage lives in the browser. There is one trap: a brand-new page is on about:blank, which has no real origin, and accessing localStorage there throws a SecurityError. Navigate to the site first, then read or write.

If you set values and want the app to pick them up, reload after writing. For seeding many tests at once, Playwright's storageState or context.addInitScript() are the usual tools.

The fragile version

Fragile
await page.evaluate(() => localStorage.setItem('currency', 'GBP'));
await page.goto('/');

Why it breaks: The evaluate runs on about:blank, which has no origin, so it throws before the test even loads the site.

A robust Playwright version

Robust
await page.goto('/');
await page.evaluate(() => localStorage.setItem('currency', 'GBP'));
await page.reload();
expect(await page.evaluate(() => localStorage.getItem('currency'))).toBe('GBP');
await expect(page.getByText('Prices in GBP')).toBeVisible();

It gives the page a real origin first, writes, reloads so the app reads the value, and checks both storage and UI.

This is a general example on a made-up page, not the challenge’s reference solution.

Common mistakes

  • Touching storage before navigating to the site.
  • Writing on one origin and reading on another (for example www. versus bare domain).
  • Forgetting to reload when the app only reads storage on start-up.

FAQ

Why does localStorage throw SecurityError in Playwright?

The page is on about:blank with no origin. Navigate first.

How do I clear localStorage between tests?

Each Playwright test gets a fresh context by default; otherwise localStorage.clear() via evaluate.

Can I pre-load storage before the page runs?

Yes, with storageState or context.addInitScript().

Try it

Practise this in Challenge 27. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.

Practise this challenge free