How to Get and Use Cookies in Playwright: A Step-by-Step Guide for Beginners

armanabbasi
3 min readNov 13, 2023

--

Overview

Playwright is a powerful framework designed for web testing and automation. It is built to enable reliable and fast cross-browser web automation. Additionally, Playwright can save the authentication state of the context and reuse it in all the tests.
In this article, we will explore how to capture and use cookies in Playwright.

1- Getting Started

It is necessary to install Node.js and Playwright.

npm init playwright@latest

3- Start Test:

This test involves three parts:
3.1 Define preconditions, such as libraries and constants.
3.2 Write a scenario that you can access cookies in a try-catch block
3.3 How to capture and return cookies.

You can see the complete code, and next, we will review each part.

import { test } from '@playwright/test';
import { chromium } from 'playwright';

test('captureAndSetCookies', async () => {
let cookies = [];
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
try {
const page = await context.newPage();
await page.goto(BASE_URL);

// ... Login codes ...

// Get cookies from the current context
cookies = await context.cookies();
console.log('Cookies after logging in:', cookies);

} catch (err) {
await chrome.close();
throw new Error(err.message);
}

return cookies;
});

Let’s break down the first part of the code:

3.1 Define preconditions, such as libraries and constants.

import { test } from '@playwright/test';
import { chromium } from 'playwright';
  • The ‘test’ function from the Playwright test library is used to define a test case in Playwright tests. The ‘chromium’ object is then used to launch a Chromium browser instance in your test.
test('captureAndSetCookies', async () => {...})
  • The ‘test’ function is the starting point for defining a test case, it is an asynchronous function that can take an object as a parameter.
let cookies = [];
  • This line initializes an empty array to store cookie information
const browser = await chromium.launch({ headless: false })
  • To launch a specific browser instance(such as chromium) using the browserType methods.
const context = await browser.newContext();
  • BrowserContexts provide a way to operate multiple independent browser sessions, similar to an new incognito browser context.
  • If you want to use user sessions or to isolate the actions performed on different pages, use the ‘newContext’ method.
  • In this case, we want to capture cookies when opening a page, and then transfer them to another framework.

3.2 Write a scenario that you can access cookies in a try-catch block

try {

// ... Login codes ...

} catch (err) {
await chrome.close();
throw new Error(err.message);
}
  • We use a ‘try’ block to write login codes because it helps handle any exceptions or errors that may occur during the cookie-capturing process, such as network issues or browser problems.

Catch Block:

  • The ‘catch’ block is executed, when an exception occurs in the “try” block.
  • After handling the error, it is essential to close the browser, because it might remain open in the background and could eventually impact the system’s stability. so using await chrome.close() is a necessary step.
  • The throw new Error(err.message), is used to create a new error object with the same message as the original error, providing consistency in error handling.

3.3 How to capture and return cookies.

try {
// ... Login codes ...

// Get cookies from the current context
cookies = await context.cookies();
console.log('Cookies after logging in:', cookies);
}
// ... more code about error handling

return cookies;
  • In the final line of the ‘try’ block, store the cookie values in a variable (‘cookies’). Using 'console.log', display all cookies in the terminal after logging in.
  • The ‘return’ statement allows for the use of the captured cookies outside the ‘try’ block

5- Conclusion

In this article, we’ve covered the process of capturing and returning cookies using Playwright. This technique proves valuable for handling cookies in complex scenarios, such as logging in with SSO pages (single sign-on) or using them with other frameworks like ‘Cypress’, which may have limitations in performing certain actions.

You can check out the repository related to this article:
https://github.com/armanabbassii/Playwright

☕️ Happy automating! ☕️

--

--

armanabbasi

A person who loves facing new challenges, learning new things, and sharing knowledge with others.