Rayrun

What methods can I use to access and manipulate local storage, session storage, and cookies in Playwright tests?

Answer

Accessing Storage and Cookies in Playwright Tests

Playwright provides APIs to access local storage, session storage, and cookies in your tests.

Session Storage

To retrieve session storage data, use page.evaluate(). This method executes JavaScript code in the page context. Here's how to save session storage as an environment variable:

const sessionStorage = await page.evaluate(() => JSON.stringify(sessionStorage));
fs.writeFileSync('playwright/.auth/session.json', JSON.stringify(sessionStorage), 'utf-8');

To set session storage in a new context, parse and load it from a file using fs.readFileSync(). Then, use context.addInitScript() to set the session storage based on specific conditions:

const sessionStorage = JSON.parse(fs.readFileSync('playwright/.auth/session.json', 'utf-8'));
await context.addInitScript(storage => {
  if (window.location.hostname === 'ray.run') {
    for (const [key, value] of Object.entries(storage)) {
      window.sessionStorage.setItem(key, value);
    }
  }
}, sessionStorage);

Local Storage and Cookies

For local storage or cookies, use Playwright's built-in methods like context.storageState() and context.cookies().

After performing login actions on your application page, save the state of local storage by calling page.context().storageState({ path: STORAGE_STATE }). This saves all relevant local storage data into a specified file path.

To reuse this authenticated state, load this stored state by passing it as an argument to browser.newContext() using the storageState option:

const browserContext2 = await browser.newContext({ storageState });

This lets you continue generating tests from the logged-in state without needing to authenticate again.

Remember to handle sensitive information securely. Only use the storage file locally and consider adding it to your .gitignore or deleting it once you're done with your tests.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.