Playwright for Java
repository·main·Indexed 23 days ago
https://github.com/microsoft/playwright-javaA Java library for reliable and fast cross-browser web automation of Chromium, Firefox, and WebKit browsers using a single, unified API. It includes a web-first assertion API via PlaywrightAssertions.assertThat() for verifying element states—such as visibility, text content, and attributes—with built-in retries and customizable timeouts.
What's inside Playwright for Java
- Playwright is a Java library designed for cross-browser web automation. It provides a single API to automate Chromium, Firefox, and WebKit engines. It is built to be evergreen, capable, reliable, and fast.
How to get help with Playwright for Java
mainIf you encounter issues or have questions while using Playwright for Java, you can access support through the following channels:
- Documentation: The official Playwright for Java documentation site is the primary resource for guides and API references.
- Community Support: Join the Playwright Discord Server and use the
help-playwrightforum to connect with other developers. - Issue Tracking: For bugs or feature requests, search the GitHub issues repository first to avoid duplicates. If you need to file a new issue, use the provided issue templates on GitHub.
Run Playwright Java examples using Maven
mainThe examples in this repository are structured as Maven projects. You can execute a specific example class from your terminal using the
mvn compile exec:javacommand, specifying the main class via the-Dexec.mainClassproperty.mvn compile exec:java -Dexec.mainClass=org.example.PageScreenshotHow to monitor and interact with Web Workers
mainThe
Workerclass represents a Web Worker. You can monitor a worker's lifecycle and console activity using event handlers, or execute JavaScript directly within the worker's context.Lifecycle Events
onClose(Consumer<Worker> handler): Emitted when the worker is terminated.onConsole(Consumer<ConsoleMessage> handler): Emitted when JavaScript within the worker calls a console API method (e.g.,console.log).
Executing JavaScript
evaluate(String expression): Evaluates a JavaScript expression in the worker context and returns the result. If the expression returns aPromise, Playwright waits for it to resolve.evaluateHandle(String expression): Similar toevaluate, but returns the result as aJSHandle.
Waiting for Events
waitForClose(Runnable callback): Performs an action and waits for the worker to close.waitForConsoleMessage(Runnable callback): Performs an action and waits for a console message to be emitted.
page.onWorker(worker -> { System.out.println("Worker created: " + worker.url()); worker.onClose(worker1 -> System.out.println("Worker destroyed: " + worker1.url())); }); System.out.println("Current workers:"); for (Worker worker : page.workers()) System.out.println(" " + worker.url());How to gracefully close a Browser and its Contexts
mainTo ensure all artifacts like HAR files and videos are fully flushed and saved, you should close your
BrowserContextinstances explicitly before closing theBrowserinstance.Calling
browser.close()is similar to force-quitting the browser and may prevent graceful cleanup. The recommended pattern is:- Perform actions in the context.
- Call
context.close(). - Call
browser.close().
Browser browser = playwright.firefox().launch(); // Create a new incognito browser context. BrowserContext context = browser.newContext(); // Create a new page in a pristine context. Page page = context.newPage(); page.navigate("https://example.com"); // Graceful close up everything context.close(); browser.close();Use the Mouse API for low-level interactions
mainThe
Mouseclass allows for low-level mouse interactions using CSS pixels relative to the top-left corner of the viewport. EveryPageobject provides its ownMouseinstance viapage.mouse().Common tasks include:
- Moving the cursor: Use
move(x, y)ormove(x, y, options). - Clicking: Use
click(x, y)for a single click ordblclick(x, y)for a double click. - Pressing/Releasing buttons: Use
down(options)to dispatch amousedownevent andup(options)to dispatch amouseupevent. - Scrolling: Use
wheel(deltaX, deltaY)to dispatch awheelevent for manual scrolling.
To debug mouse movements, you can use the Playwright Trace Viewer or Playwright Inspector, which will display a red dot at the mouse location for every action.
// Using ‘page.mouse’ to trace a 100x100 square. page.mouse().move(0, 0); page.mouse().down(); page.mouse().move(0, 100); page.mouse().move(100, 100); page.mouse().move(100, 0); page.mouse().move(0, 0); page.mouse().up();- Moving the cursor: Use
Handle file upload dialogs with FileChooser
mainFileChooserobjects are used to interact with file upload dialogs. You can capture aFileChooserinstance by usingpage.waitForFileChooser()which takes a lambda that performs the action triggering the dialog (like a click).Once you have the
FileChooserinstance, you can usesetFiles()to upload files. If you provide relative paths, they are resolved relative to the current working directory. Passing an empty array tosetFileswill clear the selected files.FileChooser fileChooser = page.waitForFileChooser(() -> page.getByText("Upload file").click()); fileChooser.setFiles(Paths.get("myfile.pdf"));How to use Locator assertions in Playwright Java
mainPlaywright provides a web-first assertion API via
PlaywrightAssertions.assertThat(). These assertions are designed to be used withLocatorobjects to verify the state of elements (e.g., visibility, text content, attributes) with built-in retries. Instead of manually checking conditions, you useassertThat(locator).method()which will automatically retry until the condition is met or the timeout is reached.To use them, import the static
assertThatmethod fromcom.microsoft.playwright.assertions.PlaywrightAssertions.import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; // ... inside a test method page.getByRole(AriaRole.BUTTON).click(); assertThat(page.locator(".status")).hasText("Submitted");Monitor WebSocket connections with the WebSocket class
mainThe
WebSocketclass allows you to inspect and monitor WebSocket connections within a page. You can listen for events such as connection closure, frame reception, frame transmission, and socket errors.Note: If your goal is to intercept or modify WebSocket frames, use
WebSocketRouteinstead of theWebSocketclass.How network routing works in Playwright
mainWhen you set up a network route using
Page.route()orBrowserContext.route(), Playwright provides aRouteobject to handle that specific request. You can interact with theRouteobject in four primary ways:abort(): Stops the request from proceeding.resume(): Sends the request to the network immediately, bypassing any other matching handlers. You can useResumeOptionsto override headers, method, post data, or the URL.fallback(): Passes the request to the next matching handler in the chain. This allows multiple handlers to process a request in reverse order of registration. You can useFallbackOptionsto modify the request before it reaches the next handler.fulfill(): Intercepts the request and provides a mock response instead of going to the network. You can useFulfillOptionsto set the status, headers, content type, or body (as text, bytes, or a file path).
Additionally,
fetch()allows you to perform the actual network request, retrieve the real response, and then modify it before callingfulfill()to return the modified version to the client.Configure timeouts and options for Locator assertions
mainMost locator assertions allow you to customize the assertion behavior using specific
Optionsclasses. The most common customization is thetimeout, which defines how long (in milliseconds) Playwright should retry the assertion before failing. The default timeout is5000ms.Example of setting a custom timeout for a visibility assertion:
assertThat(locator).isVisible(new IsVisibleOptions().setTimeout(10000));Initialize Playwright using Playwright.create()
mainTo start using Playwright, call the static
Playwright.create()method. This launches the Playwright driver process. BecausePlaywrightimplementsAutoCloseable, it is recommended to use it within a try-with-resources block to ensure that the driver process is terminated and all associated browsers are closed when finished.Once initialized, you can access different browser engines via
chromium(),firefox(), orwebkit().import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType chromium = playwright.chromium(); Browser browser = chromium.launch(); Page page = browser.newPage(); page.navigate("http://example.com"); // other actions... browser.close(); } } }