# Safari Private Browsing Storage Isolation Test

Canonical: https://figment.so/blog/mac-safari-private-browsing-storage-test

Use a fresh Playwright WebKit BrowserContext as a stand-in for a Private Browsing tab. Write localStorage and IndexedDB, close the context, then assert a new context sees nothing. Storage-only checks run on any Mac plan.

**Run Playwright's WebKit project on a Mac, write known values to `localStorage`, `IndexedDB` and `sessionStorage` in a fresh `BrowserContext`, close it, and assert that a new context sees nothing.** A Playwright context is an incognito-like stand-in for a Safari Private Browsing tab, not Safari's Private Browsing itself.

The suite below is small on purpose. It writes the values, confirms the writes land, closes the context, and opens a new context to assert nothing leaked across the boundary.

## What does Safari Private Browsing isolate?

WebKit documents Safari's Private Browsing as a per-tab ephemeral session: "Safari's Private Browsing Mode uses a new ephemeral session for each tab the user opens to isolate tabs from each other" ([webkit.org/tracking-prevention](https://webkit.org/tracking-prevention/)). Cookies, `localStorage`, `sessionStorage`, `IndexedDB` and cache for that session go away when the tab closes.

Two consequences matter for tests:

- A Private Browsing tab does not see data written in a previous normal-browsing session, so any first-paint code that assumes a prior `localStorage` key is wrong in Private Browsing.
- Two Private Browsing tabs in Safari do not share storage with each other, which differs from Chromium's Incognito, where all Incognito tabs in one window share a profile.

| Behaviour | WebKit Private Browsing | Chromium Incognito |
|---|---|---|
| Storage persists after tab/context close | No | No |
| Two private tabs share storage in one session | No | Yes |
| `localStorage` / `IndexedDB` writes succeed during the session | Yes | Yes |

Playwright models each `BrowserContext` as an independent incognito-like profile with its own cookies, `localStorage`, `IndexedDB`, cache and service workers ([playwright.dev BrowserContext](https://playwright.dev/docs/api/class-browsercontext)). That makes it the right primitive for simulating a Private Browsing tab.

## How do I write localStorage and IndexedDB in a WebKit context?

Pin the test to the `webkit` project so results reflect the same engine Safari ships. These helpers write and read both stores from the page runtime.

```typescript
// storage-isolation.spec.ts
import { test, expect, BrowserContext, Page } from '@playwright/test';

const TEST_ORIGIN = process.env.BASE_URL ?? 'http://localhost:3000';
const LS_KEY = 'privacyTest_ls';
const LS_VALUE = 'isolation-check-value';
const IDB_DB = 'privacyTestDB';
const IDB_STORE = 'entries';
const IDB_KEY = 'privacyTest_idb';
const IDB_VALUE = 'idb-isolation-check';

async function writeStorage(page: Page): Promise<void> {
  await page.evaluate(
    ({ lsKey, lsVal, dbName, storeName, idbKey, idbVal }) => {
      localStorage.setItem(lsKey, lsVal);
      return new Promise<void>((resolve, reject) => {
        const req = indexedDB.open(dbName, 1);
        req.onupgradeneeded = () => {
          req.result.createObjectStore(storeName);
        };
        req.onsuccess = () => {
          const tx = req.result.transaction(storeName, 'readwrite');
          tx.objectStore(storeName).put(idbVal, idbKey);
          tx.oncomplete = () => resolve();
          tx.onerror = () => reject(tx.error);
        };
        req.onerror = () => reject(req.error);
      });
    },
    { lsKey: LS_KEY, lsVal: LS_VALUE,
      dbName: IDB_DB, storeName: IDB_STORE,
      idbKey: IDB_KEY, idbVal: IDB_VALUE }
  );
}

async function readLocalStorage(page: Page, key: string): Promise<string | null> {
  return page.evaluate((k) => localStorage.getItem(k), key);
}

async function readIndexedDB(page: Page): Promise<unknown> {
  return page.evaluate(
    ({ dbName, storeName, idbKey }) =>
      new Promise((resolve) => {
        const req = indexedDB.open(dbName);
        req.onsuccess = () => {
          const db = req.result;
          if (!db.objectStoreNames.contains(storeName)) {
            resolve(null);
            return;
          }
          const tx = db.transaction(storeName, 'readonly');
          const getReq = tx.objectStore(storeName).get(idbKey);
          getReq.onsuccess = () => resolve(getReq.result ?? null);
          getReq.onerror = () => resolve(null);
        };
        req.onerror = () => resolve(null);
      }),
    { dbName: IDB_DB, storeName: IDB_STORE, idbKey: IDB_KEY }
  );
}
```

## How do I assert that nothing remains after the context closes?

Open a write context, confirm the writes land in that same context, close it, then open a fresh context for each assertion. A non-null read from the fresh context indicates a genuine cross-context leak.

```typescript
test.describe('Safari Private Browsing storage isolation', () => {
  let writeContext: BrowserContext;

  test.beforeAll(async ({ browser }) => {
    writeContext = await browser.newContext();
    const page = await writeContext.newPage();
    await page.goto(TEST_ORIGIN);

    await writeStorage(page);

    const lsValue = await readLocalStorage(page, LS_KEY);
    const idbValue = await readIndexedDB(page);
    expect(lsValue).toBe(LS_VALUE);
    expect(idbValue).toBe(IDB_VALUE);

    const state = await writeContext.storageState({ indexedDB: true });
    await test.info().attach('storage-state-before-close.json', {
      body: Buffer.from(JSON.stringify(state, null, 2)),
      contentType: 'application/json',
    });

    await writeContext.close();
  });

  test('localStorage is empty after context disposal', async ({ browser }) => {
    const freshContext = await browser.newContext();
    const page = await freshContext.newPage();
    await page.goto(TEST_ORIGIN);
    expect(await readLocalStorage(page, LS_KEY)).toBeNull();
    await freshContext.close();
  });

  test('IndexedDB has no residual entries after context disposal', async ({ browser }) => {
    const freshContext = await browser.newContext();
    const page = await freshContext.newPage();
    await page.goto(TEST_ORIGIN);
    expect(await readIndexedDB(page)).toBeNull();
    await freshContext.close();
  });

  test('sessionStorage is not accessible from a new context', async ({ browser }) => {
    const writeCtx = await browser.newContext();
    const writePage = await writeCtx.newPage();
    await writePage.goto(TEST_ORIGIN);
    await writePage.evaluate(() =>
      sessionStorage.setItem('privacyTest_ss', 'ss-isolation-value')
    );
    await writeCtx.close();

    const readCtx = await browser.newContext();
    const readPage = await readCtx.newPage();
    await readPage.goto(TEST_ORIGIN);
    const residual = await readPage.evaluate(() =>
      sessionStorage.getItem('privacyTest_ss')
    );
    expect(residual).toBeNull();
    await readCtx.close();
  });
});
```

`storageState()` serializes cookies and `localStorage` by default. Pass `{ indexedDB: true }` to include IndexedDB in the JSON snapshot, per the Playwright API reference linked above. `sessionStorage` is per-tab and intentionally excluded from `storageState()`, so the dedicated test above exercises that path directly.

## How do I pin the run to WebKit on macOS?

Lock the project list so results reflect the macOS WebKit build, and keep a Chromium project alongside for parity evidence:

```typescript
// playwright.config.ts (excerpt)
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    { name: 'webkit',   use: { ...devices['Desktop Safari'] } },
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
  ],
});
```

Playwright's own browser documentation notes that media codec availability "varies substantially between Linux, macOS and Windows" and that "for the closest-to-Safari experience you should run WebKit on mac" ([playwright.dev/docs/browsers](https://playwright.dev/docs/browsers)). For storage-only assertions, Linux WebKit is usually adequate. For anything that touches media or layout surfaces that differ by platform, run on macOS.

## Is the Intel Mac VM enough for a WebKit storage suite?

The Intel Mac VM ($25 a month, $2 a day) runs macOS Sequoia and is enough for a single-project WebKit storage suite. The Apple Silicon Mac VM ($39 a month, $6 a day, 4GB RAM) fits if you also want Apple-silicon-native tooling or Xcode 26.4 or later in the same job. We have not measured this suite on either plan, and the test is storage logic only, so it does not need a camera, microphone or other hardware. See the [Mac hosting plans](/mac-hosting) for the macOS version shown before purchase.

**Related guides:**

- [Full disk access automation test](/blog/mac-full-disk-access-automation-test)
- [Safari WebAuthn passkey test](/blog/mac-safari-webauthn-passkey-test)
- [GitHub Actions self-hosted runner on a Mac](/blog/mac-github-actions-self-hosted-runner)
