Overview of Playwright Framework

 

What is Playwright?

Playwright is an open-source end-to-end (E2E) automation testing framework developed by Microsoft. It is used to automate modern web applications across multiple browsers and platforms. Playwright provides APIs for automating Chromium (Chrome, Edge), Firefox, and WebKit (Safari) browsers using a single codebase.
























Key Features of Playwright


FeatureDescription
Cross-browser testingSupports Chromium, Firefox, and WebKit with a unified API.
Cross-platformRuns on Windows, Linux, and macOS.
Auto-waitAutomatically waits for elements to be ready before performing actions.
Headless & Headful modesCan run in the background (headless) or visible mode (headful).
Multiple language supportOfficial support for JavaScript/TypeScript, Python, Java, and .NET.
Built-in test runnerIncludes its own Playwright Test runner for powerful parallel execution, retries, and test reporting.
Browser contextsIsolates test environments within the same browser instance to simulate multiple users.
Network & Geolocation mockingAllows simulation of network conditions and geolocation.
Visual comparisonsSupports screenshot and video capturing for visual regression testing.


Supported Browsers

  • Chromium (Google Chrome, Microsoft Edge)
  • Firefox
  • WebKit (Safari)

These are bundled with Playwright, so no need to install them manually.


Advanced Features

  • API Testing: Playwright can make HTTP requests and validate responses.
  • Mobile Emulation: Emulates mobile devices like iPhone, Pixel.
  • Component Testing: React, Angular, Vue component testing support.
  • CI/CD Integration: Jenkins, GitHub Actions, GitLab, Azure DevOps, etc.


Comparison: Playwright vs Selenium

FeaturePlaywrightSelenium
Modern web supportExcellentLimited in modern web features
SpeedFasterSlower
Auto-waitYesManual wait often required
Browser supportChromium, Firefox, WebKitAll major browsers
API TestingBuilt-inNeeds external tools
Built-in test runnerYesNo



Playwright generally used for:

  • Cross-browser UI Testing
  • Visual Regression Testing
  • API Testing
  • CI/CD pipeline automation
  • Mobile and geolocation testing
  • Real-time network condition simulation

You can go official website for more detail: 
https://playwright.dev/java/






Suggested Posts:

1. Handle Alerts in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Token Based Authentication in Playwright
5. Basic Authentication in Playwright

How to Test Cookie based Authentication in API by Playwright


What are Cookies?

  • Cookies are small pieces of data stored by a web browser on the client side.
  • They are usually sent by the server in the HTTP response headers and stored by the browser.
  • On subsequent requests, the browser automatically attaches these cookies back to the server.
  • Cookies are used for:

        - Session management (login sessions, user preferences, shopping carts).

        - Personalization (themes, recommendations).

        - Tracking (analytics, advertising)


What is Cookie-Based Authentication?

  • Cookie-based authentication is a mechanism where the server authenticates a user and creates a session.
  • After successful login, the server generates a session ID and stores it in the server-side session storage.
  • This session ID is sent back to the client as a cookie.
  • For every subsequent request, the browser automatically sends this cookie back, allowing the server to recognize the authenticated user.

Steps in Cookie-Based Authentication:
  • User provides login credentials (username/password).
  • Server verifies credentials and creates a session on the backend.
  • Server sends a Set-Cookie header with a unique session ID to the client.
  • Browser stores the cookie.
  • For each new request, the browser includes the cookie in the Cookie header.
  • Server checks the cookie, validates the session, and grants access.


Handling Cookie-Based Authentication in Playwright (Java)

In Playwright automation, cookie-based authentication can be handled in two ways:

1. Manual Login Once & Reuse Cookies
  • Automate login once by filling in username/password and submitting.
  • After login, extract cookies from the browser context.
  • Save these cookies into a file (e.g., JSON format).
  • In subsequent tests, load these cookies into the browser context so you don’t need to log in again.
  • This makes tests faster and avoids hitting the login page repeatedly.
2. Programmatic Cookie Injection
  • If you already have valid cookies (from API calls or manual login), you can directly inject them into the browser context in Playwright.
  • This bypasses the UI login flow.
  • Once cookies are added, Playwright will automatically attach them to all requests, and the session will be authenticated.

Why This is Useful in Automation?
  • Efficiency: Skips repetitive login steps in test cases.
  • Stability: Reduces flakiness by avoiding multiple login UI interactions.
  • Scalability: Multiple test cases can reuse the same authenticated session.

To test cookie-based authentication in API using Playwright in Java, you need to simulate the process of login, capture the authentication cookies, reuse them for subsequent requests, and validate access to protected resources.

















Concept: Cookie-Based Authentication

  • The user sends credentials via a login API (usually POST).
  • Server responds with a Set-Cookie header (usually a session or JWT cookie).
  • The browser stores this cookie and sends it with every subsequent request.
  • You can use Playwright to extract, reuse, and assert using these cookies.


Steps in Playwright Java

  • Launch browser.
  • Navigate to login API or page and perform login.
  • Extract cookies using context.cookies().
  • Store or reuse those cookies for a new context/page to access protected resources.

Example: Cookie-Based Login Simulation

Let’s use https://www.saucedemo.com/ for login.

You can use any backend which sets cookies, or mock a cookie manually for demonstration.













Java Code: Simulate Cookie Auth in Playwright

import com.microsoft.playwright.*;

import java.util.*;

public class CookieAuthTest {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Step 1: Navigate to website and simulate login
            page.navigate("https://www.saucedemo.com/");

            //Save cookies + localStorage/sessionStorage
            context.storageState(new BrowserContext.StorageStateOptions().setPath(Paths.get(storageStatePath)));
             

            // Simulate login (replace with actual selectors)
            page.locator("[name='user-name']").fill("standard_user");
            page.locator("[name='password']").fill("secret_sauce");
            page.locator("[name='login-button']").click();

            // Wait for navigation or successful login indication
            page.waitForURL("**/inventory.html");

            // Step 2: Extract cookies after login
            List<BrowserContext.Cookie> cookies = context.cookies();
            System.out.println("Extracted Cookies:");
            for (BrowserContext.Cookie cookie : cookies) {
                System.out.println(cookie.name + " = " + cookie.value);
            }

            // Step 3: Create new context with saved cookies (simulate another session)
            BrowserContext authContext = browser.newContext(new Browser.NewContextOptions().setStorageStatePath(Paths.get(storageStatePath)));
            authContext.addCookies(cookies);

            Page authPage = authContext.newPage();
            authPage.navigate("https://www.saucedemo.com/inventory.html"); // Protected resource

            // Step 4: Verify protected content is accessible
            if (authPage.locator(".header_label>div").isVisible()) {
                System.out.println("Authentication successful using cookie!");
            } else {
                System.out.println("Authentication failed.");
            }

            browser.close();
        }
    }
}


Code Steps:

(a) Create Playwright, Browser, BrowserContext and Page object
(b) Save cookies + localStorage/sessionStorage
(c) Navigate to website and simulate login
(d) Simulate login (replace with actual selectors)
(e) Wait for navigation or successful login indication
(f) Extract cookies after login
(g) Create new context with saved cookies (simulate another session)
(h) Verify protected content is accessible



Explanation:

  • page.locator().fill() – Simulates user entering credentials.
  • context.cookies() – Gets all cookies after login.
  • authContext.addCookies(cookies) – Applies saved cookies to new context.
  • authPage.navigate() – Navigates to protected resource using cookie-based session.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Token Based Authentication in Playwright
5. Basic Authentication in Playwright