First Playwright Script in Java


























How to Write Your First Playwright Script in Java

Automation testing has become an essential skill for modern QA engineers. With Java, we can automate browser actions such as opening a website, clicking buttons, filling forms, submitting data, and validating results.

Playwright is a powerful automation framework developed by Microsoft that allows us to control modern web browsers programmatically. It supports multiple browsers including:

  • Chromium (Chrome, Edge)

  • Firefox

  • WebKit (Safari)

In this guide, we will create our first Playwright script using Java.


Important Things to Know Before Starting

Before writing your first script, you should understand a few basic concepts:

  • Playwright was originally built on Node.js, but it provides official support for Java.

  • It allows interaction with web elements like buttons, text fields, dropdowns, and links.

  • It is widely used for UI testing and end-to-end automation.

  • It supports cross-browser testing with the same code base.

If you are familiar with Selenium, you will find Playwright easier in terms of auto-waiting and browser management.


Steps to Create Your First Playwright Script in Java

Playwright automation follows five simple steps.


Step 1: Set Up the Environment

Before writing any code:

  • Install Java (JDK 11 or above)

  • Install Maven or Gradle

  • Create a new Java project

  • Add Playwright dependency

Playwright will automatically download the required browser binaries when you run the project for the first time.


Maven Dependency

Add the following dependency in your pom.xml file:

<dependencies> <dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.45.0</version> </dependency> </dependencies>

Make sure you use the latest stable version available.


Step 2: Launch the Browser

The first thing in automation is launching a browser instance.

Playwright allows you to:

  • Run in headless mode (faster, no browser UI)

  • Run in headed mode (browser UI visible)

For learning purposes, headed mode is recommended.


Step 3: Create a Browser Context

A BrowserContext works like an incognito window.

Each context:

  • Has separate cookies

  • Has separate local storage

  • Is completely isolated

This helps in running multiple tests independently.


Step 4: Create a Page and Navigate

A Page represents a single browser tab.

Once the page is created, you can navigate to any website and begin interacting with it.


Step 5: Interact with Web Elements

Playwright supports multiple selector strategies such as:

  • ID

  • CSS

  • Text

  • XPath

You can perform actions like:

  • click()

  • fill()

  • selectOption()

  • take screenshots

  • hover

  • wait for elements


Step 6: Close the Browser

After completing your test steps, always close the browser.

This ensures proper cleanup of resources and prevents memory leaks.


First Playwright Script in Java

Below is a simple example. This script:

import com.microsoft.playwright.*; public class FirstPlaywrightTest { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { // Launch Chromium browser in headed mode Browser browser = playwright.chromium().launch( new BrowserType.LaunchOptions().setHeadless(false) ); // Create a new browser context BrowserContext context = browser.newContext(); // Open a new page Page page = context.newPage(); // Navigate to website page.navigate("https://example.com"); // Get page title String title = page.title(); System.out.println("Page title is: " + title); // Close browser browser.close(); } } }


Code Explanation

LineExplanation
Playwright.create()Initializes the Playwright engine
playwright.chromium().launch()Launches Chromium browser
browser.newContext()Creates isolated browser session
context.newPage()Opens new browser tab
page.navigate()Loads the website
page.title()Returns the page title
browser.close()Closes browser instance


How to Run in Eclipse

  1. Right-click on the Java class

  2. Select Run As

  3. Click Java Application

The browser will open, navigate to the website, and print the title in the console.


Best Practices for Beginners

  • Always use try-with-resources for Playwright

  • Avoid using Thread.sleep()

  • Use Playwright’s built-in waiting mechanism

  • Keep headless mode enabled in CI/CD environments

  • Always close browser after execution


Conclusion

Writing your first Playwright script in Java is straightforward once you understand the flow:

  1. Initialize Playwright

  2. Launch browser

  3. Create context

  4. Open page

  5. Perform actions

  6. Close browser

These basic steps form the foundation of any advanced Playwright automation framework.

Once you are comfortable with this structure, you can move forward to handling alerts, dropdowns, iframes, and building a complete automation framework.


Playwright Architecture

 

Playwright Architecture Explained in Detail (2026 Guide with Real Examples)

Playwright is a modern end-to-end test automation framework developed by Microsoft. It enables reliable cross-browser testing across:

  • Chromium (Chrome, Edge)

  • Firefox

  • WebKit (Safari)

Unlike traditional automation tools, Playwright is designed with a client-server architecture, high reliability, and built-in auto-waiting mechanisms that reduce flaky tests significantly.

In this guide, we will deeply understand:

  • Playwright architecture

  • How it communicates with browsers

  • Core components

  • Advanced architectural features

  • Real-world practical examples


Playwright Architecture Overview

Playwright follows a Client–Server Architecture.

When you execute a test:

  1. Your test script sends commands.

  2. Playwright converts them into protocol messages.

  3. Commands are sent over a WebSocket connection.

  4. The browser executes the action.

  5. Response is returned via the same connection.


Why WebSocket?

Playwright maintains a single persistent WebSocket connection during test execution.

Benefits:

  • Faster communication

  • Fewer connection failures

  • Reduced latency

  • Reliable command execution









Core Components of Playwright Architecture

1. Test Script / Test Runner

Your test code (written in Java, JavaScript, Python, etc.) interacts with the Playwright API.

In Java, you typically use:

  • JUnit
  • TestNG
Java Example:

import com.microsoft.playwright.*;

public class SimpleTest {
    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();

            page.navigate("https://example.com");
            page.click("text=More information");

            browser.close();
        }
    }
}

This script:

  • Launches Chromium

  • Creates a browser context

  • Opens a page

  • Performs click action

2.  Playwright Client Library

The Client Library provides high-level APIs like:

  • page.navigate()

  • page.click()

  • page.fill()

Internally, it communicates with:

  • Chrome DevTools Protocol (CDP) for Chromium

  • WebKit Remote Debugging Protocol

  • Firefox Remote Protocol

This abstraction allows you to write one test that runs on multiple browsers.

    
3. Browser Layer

Playwright downloads and manages browser binaries automatically.

You can run:

  • Headed mode (UI visible)

  • Headless mode (no UI)

Each test runs inside a Browser Context, which ensures isolation.


How Playwright Interacts With Browser

Execution Flow:

  • Test script calls Playwright API

  • API converts action into protocol message

  • Browser executes action

  • Response is returned

Example:

page.click("#loginButton");

This internally:

  • Waits for element

  • Verifies visibility

  • Sends click command

  • Confirms action success


Key Architectural Features


1) Auto-Waiting Mechanism

Unlike Selenium, Playwright automatically waits for:

  • Elements to be visible

  • Elements to be enabled

  • Network calls to complete

  • Navigation to finish


Example:
page.navigate("https://example.com");
page.waitForSelector("#username");
page.fill("#username", "admin");

This reduces flaky tests significantly.

Why Auto-Wait is Important

  • Prevents race conditions

  • Reduces manual wait usage

  • Improves reliability

  • Synchronizes with dynamic UI



Browser Contexts (Isolation)

A Browser Context works like an incognito session.

Each context has:

  • Separate cookies

  • Separate local storage

  • Separate session storage

Example (Multiple Users)

BrowserContext user1 = browser.newContext(); BrowserContext user2 = browser.newContext(); Page page1 = user1.newPage(); Page page2 = user2.newPage();

This is useful for testing multi-user scenarios.


Tracing (Debugging Power)

Playwright tracing records:

  • Screenshots

  • DOM snapshots

  • Network logs

  • Console logs

Enable Tracing (Java)

context.tracing().start( new Tracing.StartOptions().setScreenshots(true).setSnapshots(true) ); // Run test steps context.tracing().stop( new Tracing.StopOptions().setPath(Paths.get("trace.zip")) );

This is extremely helpful in CI/CD debugging.


Network Interception

You can monitor or mock API calls.

Example (Java)

page.route("**/api/login", route -> { route.fulfill(new Route.FulfillOptions() .setStatus(200) .setBody("{\"status\":\"success\"}")); });

Use cases:

  • Mock backend APIs

  • Simulate failures

  • Test error handling

  • Block unwanted resources


Multiple Browser Support

Run the same test across:

  • Chromium

  • Firefox

  • WebKit

Example:

Browser browser = playwright.firefox().launch();

This ensures cross-browser compatibility.


Parallel Execution

Playwright supports parallel execution using workers.

Each worker:

  • Runs isolated tests

  • Uses separate contexts

  • Does not share state

Parallel execution improves CI pipeline speed significantly.


Security & Isolation

Each test runs in a fresh context.

You can control:

  • Permissions

  • Geolocation

  • Device emulation

  • Viewport

  • Network conditions

Example:

BrowserContext context = browser.newContext( new Browser.NewContextOptions() .setGeolocation(28.6139, 77.2090) .setPermissions(Arrays.asList("geolocation")) );

Why Playwright is Better for Modern Applications

Playwright is:

  • Cross-browser

  • Fast

  • Reliable

  • Built for SPAs

  • CI/CD friendly

  • Designed for modern JavaScript-heavy apps

Because of its architecture, it handles:

  • Lazy loading

  • Animations

  • Dynamic rendering

  • API-heavy frontends


Conclusion

Playwright’s client-server architecture, WebSocket communication model, browser isolation, and built-in auto-waiting make it one of the most powerful UI automation tools available today.

For automation engineers working on modern web applications, Playwright provides:

  • Stability

  • Performance

  • Cross-browser reliability

  • Advanced debugging capabilities

This makes it an excellent choice for enterprise-grade automation frameworks.


Suggested Posts:

1. Handle Alerts in Playwright
2. BrowserContext in Playwright
3. Handle Dropdowns in Playwright
4. Handle IFrames in Playwright
5. Thread Local in Playwright