Playwright for Java

repository·main·Indexed 23 days ago

https://github.com/microsoft/playwright-java

A 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.

Tokens
22.8K
Snippets
68
Records
147
Agent score
80%

What's inside Playwright for Java

  1. How to get help with Playwright for Java

    main

    If 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-playwright forum 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.
  2. Run Playwright Java examples using Maven

    main

    The examples in this repository are structured as Maven projects. You can execute a specific example class from your terminal using the mvn compile exec:java command, specifying the main class via the -Dexec.mainClass property.

    mvn compile exec:java -Dexec.mainClass=org.example.PageScreenshot
  3. How to monitor and interact with Web Workers

    main

    The Worker class 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 a Promise, Playwright waits for it to resolve.
    • evaluateHandle(String expression): Similar to evaluate, but returns the result as a JSHandle.

    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());
  4. How to gracefully close a Browser and its Contexts

    main

    To ensure all artifacts like HAR files and videos are fully flushed and saved, you should close your BrowserContext instances explicitly before closing the Browser instance.

    Calling browser.close() is similar to force-quitting the browser and may prevent graceful cleanup. The recommended pattern is:

    1. Perform actions in the context.
    2. Call context.close().
    3. 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();
  5. Use the Mouse API for low-level interactions

    main

    The Mouse class allows for low-level mouse interactions using CSS pixels relative to the top-left corner of the viewport. Every Page object provides its own Mouse instance via page.mouse().

    Common tasks include:

    • Moving the cursor: Use move(x, y) or move(x, y, options).
    • Clicking: Use click(x, y) for a single click or dblclick(x, y) for a double click.
    • Pressing/Releasing buttons: Use down(options) to dispatch a mousedown event and up(options) to dispatch a mouseup event.
    • Scrolling: Use wheel(deltaX, deltaY) to dispatch a wheel event 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();
  6. Handle file upload dialogs with FileChooser

    main

    FileChooser objects are used to interact with file upload dialogs. You can capture a FileChooser instance by using page.waitForFileChooser() which takes a lambda that performs the action triggering the dialog (like a click).

    Once you have the FileChooser instance, you can use setFiles() to upload files. If you provide relative paths, they are resolved relative to the current working directory. Passing an empty array to setFiles will clear the selected files.

    FileChooser fileChooser = page.waitForFileChooser(() -> page.getByText("Upload file").click());
    fileChooser.setFiles(Paths.get("myfile.pdf"));
  7. How to use Locator assertions in Playwright Java

    main

    Playwright provides a web-first assertion API via PlaywrightAssertions.assertThat(). These assertions are designed to be used with Locator objects to verify the state of elements (e.g., visibility, text content, attributes) with built-in retries. Instead of manually checking conditions, you use assertThat(locator).method() which will automatically retry until the condition is met or the timeout is reached.

    To use them, import the static assertThat method from com.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");
  8. How network routing works in Playwright

    main

    When you set up a network route using Page.route() or BrowserContext.route(), Playwright provides a Route object to handle that specific request. You can interact with the Route object in four primary ways:

    1. abort(): Stops the request from proceeding.
    2. resume(): Sends the request to the network immediately, bypassing any other matching handlers. You can use ResumeOptions to override headers, method, post data, or the URL.
    3. 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 use FallbackOptions to modify the request before it reaches the next handler.
    4. fulfill(): Intercepts the request and provides a mock response instead of going to the network. You can use FulfillOptions to 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 calling fulfill() to return the modified version to the client.

  9. Configure timeouts and options for Locator assertions

    main

    Most locator assertions allow you to customize the assertion behavior using specific Options classes. The most common customization is the timeout, which defines how long (in milliseconds) Playwright should retry the assertion before failing. The default timeout is 5000 ms.

    Example of setting a custom timeout for a visibility assertion:

    assertThat(locator).isVisible(new IsVisibleOptions().setTimeout(10000));
  10. Initialize Playwright using Playwright.create()

    main

    To start using Playwright, call the static Playwright.create() method. This launches the Playwright driver process. Because Playwright implements AutoCloseable, 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(), or webkit().

    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();
        }
      }
    }