First Playwright Script in Java

  

We can use java programming language to automate actions on a web browser. It can perform tasks like opening a webpage, clicking buttons, filling forms, and verifying content. Playwright provides APIs to interact with different browsers (Chromium, Firefox, WebKit) programmatically.


Before writing our first script in Playwright Java, We should aware of following points:

  • Playwright is a Node.js library for automating web browsers.
  • It allows you to interact with web pages: click buttons, fill forms, navigate pages, and run tests.
  • It supports multiple browsers: Chromium (Chrome), Firefox, WebKit (Safari).
  • It’s mainly used for UI testing and web automation.


Steps to Create a First Playwright Script in Java

Before writing code, we should have clear that playwright has four main steps:

Step 1: Set Up the Environment

  • Install Java (JDK 11 or above) and a build tool like Maven or Gradle.
  • Add Playwright as a dependency in your project.
  • Playwright automatically downloads the necessary browser binaries.

Step 2: Launch a Browser

  • You start by creating a browser instance.
  • Playwright supports different browser types like Chromium, Firefox, Webkit, etc.
  • We can choose to launch in headless mode (no GUI, faster) or headed mode (browser GUI visible).
Step 3: Create a Page and Navigate

  • A page represents a single browser tab.
  • Just open a page and navigate it to a URL you want to test.
  • This allows your script to interact with the web application.

Step 4: Interact with Web Elements
  • You can locate elements on the page (buttons, input fields, links) using selectors like ID, class, text, or XPath.
  • It performs actions such as click, type text, select dropdowns, take screenshots, etc.

Step 5: Close the Browser
  • After the test, the script closes the page and the browser instance.
  • This ensures resources are released properly.


























Step 1: Maven Dependency


<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.45.0</version> <!-- Use the latest available version -->
    </dependency>
</dependencies>


Step 2: Basic Playwright Script in Java

Below is the first playwright script written in java and this script is launching a website: https://www.example.com, fetching the title of website and displaying on console.


import com.microsoft.playwright.*;

public class FirstPlaywrightTest {
    public static void main(String[] args) {
        // 1. Launch Playwright
        try (Playwright playwright = Playwright.create()) {

            // 2. Launch a browser (Chromium in this case)
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // 3. Open a new browser context (like a clean browser profile)
            BrowserContext context = browser.newContext();

            // 4. Create a new page/tab in the browser
            Page page = context.newPage();

            // 5. Navigate to the desired URL
            page.navigate("https://example.com");

            // 6. Fetch the page title
            String title = page.title();
            System.out.println("Page title is: " + title);

            // 7. Close the browser
            browser.close();
        }
    }
}



Code Explanation

LineCodeExplanation
1import com.microsoft.playwright.*;Imports all Playwright Java classes.
5Playwright.create()Initializes Playwright engine. Must be closed after use.
8playwright.chromium().launch(...)Launches Chromium browser (similar to Chrome). You can also use .firefox() or .webkit().
11browser.newContext()Creates an isolated browser context (like incognito). Useful for running multiple tests.
14context.newPage()Opens a new tab (page) in the browser.
17page.navigate(...)Loads the given URL in the browser.
20page.title()Returns the page’s title.
23browser.close()Gracefully shuts down the browser.


How to run in Eclipse:
Right Click > Run As > Java Application

Playwright Architecture

 

Playwright is a powerful end-to-end testing and automation framework developed by Microsoft that enables testing of modern web applications across multiple browsers. It supports Chromium (Chrome, Edge), WebKit (Safari), and Firefox.


Playwright Architecture Overview


Playwright works on Web socket connection protocol, it means once you will trigger the test, the code will be converted into JSON format and will be sent to the server using Web socket protocol. It communicates all requests through a single Web socket connection, which stays in place until test execution is completed. This reduces the points of failure and allows commands to be sent quickly on a single connection.

The architecture of Playwright is client-server based, designed to abstract browser internals and provide a fast, reliable, and cross-browser API for automation.









Core Components of Playwright

Below are the core components of playwright which are used in playwright architecture.


1. Test Script / Test Runner
  
The scripts that we write in playwright supported programming languages like in JavaScript, Typescript, Python, C#, or Java, we can run these scripts using built in playwright test runner known as playwright test or by frameworks such as Jest, Mocha, Pytest, etc.  and ultimately, test script sends commands to the Playwright client.


2. Playwright Client Library

It acts as a high-level API wrapper over browser protocols. It has methods like page.goto(), page.click(), page.fill(), etc. which internally communicates with the browser using protocols like:

  • CDP (Chrome DevTools Protocol) for Chromium
  • WebKit Remote Debug Protocol
  • Firefox Remote Protocol
    
    
3. Browser Layer

Playwright uses browser-specific binaries that it installs automatically (or manually configured). It launches and controls browsers via their native debugging protocols. We can run browsers either in headless or headed mode. Browsers are sandboxed in separate contexts or isolated incognito sessions.

How Playwright Interacts with the Browser

  • Test Script calls Playwright API (example: page.click()).
  • Playwright Client translates this to protocol commands.
  • Browser Driver receives commands and performs actions in the browser.
  • The response is returned back through the same path.


Key Architectural Features


1. Auto Waiting: Automatically waits for elements to be ready before interacting. Playwright Wait refers to the mechanisms that pause the script execution until certain conditions in the browser are met; such as elements becoming visible or network responses being completed. These waits are integral to synchronizing tests with the dynamic nature of web applications.


Importance of Playwright Wait

Here are the reasons that signify the importance of Playwright Wait in testing:

(a) If our website has transitions or animations, Playwright wait ensures that these actions are done, before executing the tests, thereby reducing the opportunity of errors.

(b) There is an unpredictability or flakiness associated with tests where the actions occur before the elements are fully loaded or visible. Playwright automatically waits for elements to be ready, which helps the tests to run reliably. Thus preventing flaky tests.

(c) Before performing any action, like clicking a button, entering details in a form etc., it’s important to wait until that element is available in the DOM. This prevents errors that occur when trying to interact with non-existent or hidden elements.

(d) Playwright offers high customizability by providing wait options like waitForSelector, waitForNavigation, and waitForTimeout to fit different testing requirements.

(e) Playwright Wait improves test accuracy and reliability of results since actions are performed at the right time.


2. Browser Contexts: It Provides isolated sessions like incognito mode for parallel testing. Playwright browser context is like a separate profile. It’s a clean slate within a single browser instance. Each context isolates itself from the others. It has its own cookies, local storage, and cache. This isolation is crucial for testing. It lets you simulate users or states without interference.  

For instance, to test how two users interact with your app at once, use separate contexts for each user. This ensures that their sessions do not overlap or affect one another. 


3. Tracing: In Playwright, tracing refers to recording a detailed log of your test’s execution. This log captures information like user actions (clicks, navigation), screenshots of the page at specific points, and any console messages generated during the test run. This record is particularly useful for debugging, especially when dealing with headless tests on CI platforms.

With the debugging feature of Playwright, we can walk through your test code slowly and use developer tools to find the exact spot where the error occurs.


4. Network Interception: It allows mocking or modifying network requests/responsesNetwork interception in Playwright is a powerful feature that allows you to monitor, modify, or block network requests and responses while running browser automation tests.


Purpose of Network Interception:

(a) Monitor requests/responses: Capture HTTP requests and responses to verify the data being sent and received.

(b) Mock responses: Simulate server responses without hitting the actual backend. Useful for testing error handling, API failures, or specific scenarios.

(c) Modify requests/responses: Change request headers, payloads, or responses on the fly to test different behaviors.

(d) Block requests: Prevent certain resources (like images, ads, or analytics scripts) from loading to speed up tests.


5. Multiple Browser Support: It has API to run the same tests across Chromium, Firefox, and WebKit. It provides comprehensive support for running tests across multiple browsers, including Chromium (which encompasses Chrome and Edge), WebKit (Safari), and Firefox. This cross-browser capability is a core feature of Playwright, enabling developers to ensure their web applications function correctly across different rendering engines and user environments.


6. Parallel Execution: Tests can run in parallel using multiple contexts or processes.
Below are points showing how Playwright supports parallel execution:

Playwright uses a concept called workers to run tests in parallel:

(a) Each worker is an independent instance of the browser and test context.

(b) Tests running in different workers do not share the same state (isolated execution).

(c) Parallelism can be configured based on the number of CPU cores or the desired concurrency level.


7. Security & Isolation: Playwright runs each test in a new browser context to ensure isolation. It supports permissions control, geolocation, device emulation, etc.

Playwright's architecture is designed to be:

  • Cross-browser
  • Reliable and fast
  • Isolation-friendly
  • Modern web-friendly (SPAs, animations, lazy-loading, etc.)

This makes it an excellent choice for UI automationcross-browser testing, and CI/CD integration.


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