Search code examples
playwright

how to capture and access session storage of the browser after login in playwright


I am using the following function to capture and store the state of the browser after login. i can see that this function captures the local storage in to a json file just fine. However, the token i am after (bearer/ access token) is only available in the session storage and not in local storage. any ideas on how to capture and access the session storage is greatly appreciated.

async function globalSetup() {
  const browser: Browser = await chromium.launch();
  const context = await browser.newContext();
  const page: Page = await context.newPage();
  const loginPage = new LoginPage(page);
  await page.goto("url")
  await loginPage.login("userName", "password");
  await page.context().storageState({ path: "./utils/storageState.json" })
}

Solution

  • Playwright has docs on how to use sessionStorage with auth, but copying over the relevant portions here.

    You'll need to use page.evaluate() to grab the sessionStorage.

    const sessionStorage = page.evaluate(() => window.sessionStorage);
    

    And then write that to file. I've had success just adding the sessionStorage to the JSON generated by storageState

    import fs from 'fs';
    ...
    const storageState = JSON.parse(fs.readFileSync("./utils/storageState.json", "utf-8"));
    storageState.sessionStorage = JSON.parse(sessionStorage); // variable name re-used from above
    fs.writeFileSync("./utils/storageState.json", JSON.stringify(storageState), "utf-8");
    

    After storing the sessionStorage, when I need to set it on the browser, I converted the function in their doc to a utility function that I can call when needed.

    export const setSessionStorage = async (page: Page, user: string) => {
      const sessionStorage = JSON.parse(readFileSync(user, 'utf-8'));
      await page.addInitScript(storage => {
        for (const [key, value] of Object.entries(storage.sessionStorage)) window.sessionStorage.setItem(key, value);
      }, sessionStorage);
    };
    

    Which makes it easy to call during a test / beforeEach

    test.describe('My Tests', () => {
      test('My test', ({ page }) => {
        await setSessionStorage(page, "./utils/storageState.json");
        // rest of setup
      });
    });