1
0
mirror of synced 2026-05-23 19:23:20 +00:00

Compare commits

..

24 Commits

Author SHA1 Message Date
Yury Semikhatsky ea48985e21 chore: set version to 1.48.0 (#1688) 2024-10-17 12:35:16 -07:00
Yury Semikhatsky 20b13ad0c0 chore: roll driver 1.48.1 (#1687) 2024-10-17 12:06:13 -07:00
dependabot[bot] 08ac52ca53 chore(deps): bump the all group with 4 updates (#1680) 2024-10-17 11:56:19 -07:00
Yury Semikhatsky 9c220cd359 test: update web socket tests to properly dispatch ws messages (#1683) 2024-10-03 11:19:15 -07:00
Yury Semikhatsky ab443d1638 chore: roll 1.48 beta driver (#1681) 2024-10-02 14:21:13 -07:00
Max Schmitt 186aede95c devops: use wget for driver downloads (#1679) 2024-10-01 09:39:38 +02:00
Yury Semikhatsky db52fa94e7 docs: remove snapshot badge from README 2024-09-12 17:04:25 -07:00
Yury Semikhatsky ee18e1a499 chore: roll 1.47.0-beta-1726138322000 (#1672) 2024-09-12 15:02:49 -07:00
Yury Semikhatsky 9cf4bf2263 docs: Update ROLLING.md with new roll script 2024-09-12 12:03:29 -07:00
Yury Semikhatsky 36350f3c5c chore: roll 1.47.0 (#1670) 2024-09-09 11:06:17 -07:00
Max Schmitt f3476c68ff test: fix client-certificate tests (#1669) 2024-09-09 09:05:37 -07:00
Max Schmitt 8fd8f1c831 test: remove per-context proxy hacks for Windows/Chromium (#1668) 2024-09-09 10:09:00 +02:00
dependabot[bot] 7d2066693b chore(deps): bump the all group with 2 updates (#1664) 2024-09-03 08:55:04 -07:00
Yury Semikhatsky 6b01b878cb chore: roll driver to 1.47.0 alpha 2024 08 28 (#1663) 2024-08-28 16:02:34 -07:00
uchagani 2e32eb704f feat(junit): Implement automatic saving of traces and screenshots via fixtures (#1560) 2024-08-28 13:52:07 -07:00
Chris Kocel b81b144680 fix: null check in ListenerCollection notify method (#1661) 2024-08-28 13:50:55 -07:00
Yury Semikhatsky 256e41a505 docs: add SUPPORT.md (#1662) 2024-08-28 11:09:38 -07:00
Yury Semikhatsky 3054364101 devops(dependabot): update all deps in single PR monthly (#1656) 2024-08-19 13:21:31 -07:00
dependabot[bot] 40b8802874 chore(deps): bump org.apache.maven.plugins:maven-deploy-plugin from 3.1.2 to 3.1.3 (#1654) 2024-08-19 12:11:29 -07:00
dependabot[bot] 49f53fceaf chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin from 3.3.1 to 3.4.0 (#1653) 2024-08-19 12:11:13 -07:00
dependabot[bot] 291c12a54c chore(deps): bump org.apache.maven.plugins:maven-install-plugin from 3.1.2 to 3.1.3 (#1655) 2024-08-19 12:11:01 -07:00
dependabot[bot] 2b3413fad4 chore(deps): bump junit.version from 5.10.3 to 5.11.0 (#1652) 2024-08-19 11:16:59 -07:00
dependabot[bot] 3eab530e95 chore(deps): bump org.apache.maven.plugins:maven-gpg-plugin from 3.2.4 to 3.2.5 (#1650) 2024-08-19 11:16:40 -07:00
Max Schmitt 7d35be4f89 devops: publish Ubuntu 24.04 Docker image (#1649) 2024-08-12 19:02:17 +02:00
74 changed files with 1822 additions and 422 deletions
+10 -1
View File
@@ -3,8 +3,17 @@ updates:
- package-ecosystem: "maven"
directory: "/" # Location of the pom.xml file
schedule:
interval: "weekly"
interval: "monthly"
open-pull-requests-limit: 10
groups:
# Create a group of dependencies to be updated together in one pull request
all:
applies-to: version-updates
patterns:
- "*"
update-types:
- "minor"
- "patch"
allow:
- dependency-type: "direct" # Optional: Only update direct dependencies
- dependency-type: "indirect" # Optional: Only update indirect (transitive) dependencies
-8
View File
@@ -3,11 +3,6 @@ on:
release:
types: [published]
workflow_dispatch:
inputs:
is_release:
required: true
type: boolean
description: "Is this a release image?"
jobs:
publish-canary-docker:
name: publish to DockerHub
@@ -33,6 +28,3 @@ jobs:
platforms: arm64
- uses: actions/checkout@v4
- run: ./utils/docker/publish_docker.sh stable
if: (github.event_name != 'workflow_dispatch' && !github.event.release.prerelease) || (github.event_name == 'workflow_dispatch' && github.event.inputs.is_release == 'true')
- run: ./utils/docker/publish_docker.sh canary
if: (github.event_name != 'workflow_dispatch' && github.event.release.prerelease) || (github.event_name == 'workflow_dispatch' && github.event.inputs.is_release != 'true')
+1 -1
View File
@@ -81,7 +81,7 @@ jobs:
- name: Install MS Edge
if: matrix.browser-channel == 'msedge' && matrix.os == 'macos-latest'
shell: bash
run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install msedge" -f playwright/pom.xml
run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install msedge" -f playwright/pom.xml
- name: Run tests
run: mvn test --no-transfer-progress --fail-at-end -D org.slf4j.simpleLogger.showDateTime=true -D org.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss
env:
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
strategy:
fail-fast: false
matrix:
flavor: [focal, jammy]
flavor: [focal, jammy, noble]
steps:
- uses: actions/checkout@v3
- name: Build Docker image
+2 -3
View File
@@ -2,7 +2,6 @@
[![javadoc](https://javadoc.io/badge2/com.microsoft.playwright/playwright/javadoc.svg)](https://javadoc.io/doc/com.microsoft.playwright/playwright)
[![maven version](https://img.shields.io/maven-central/v/com.microsoft.playwright/playwright)](https://search.maven.org/search?q=com.microsoft.playwright)
[![Sonatype Nexus (Snapshots)](https://img.shields.io/nexus/s/https/oss.sonatype.org/com.microsoft.playwright/playwright.svg)](https://oss.sonatype.org/content/repositories/snapshots/com/microsoft/playwright/playwright/)
[![Join Discord](https://img.shields.io/badge/join-discord-infomational)](https://aka.ms/playwright/discord)
#### [Website](https://playwright.dev/java/) | [API reference](https://www.javadoc.io/doc/com.microsoft.playwright/playwright/latest/index.html)
@@ -11,9 +10,9 @@ Playwright is a Java library to automate [Chromium](https://www.chromium.org/Hom
| | Linux | macOS | Windows |
| :--- | :---: | :---: | :---: |
| Chromium <!-- GEN:chromium-version -->128.0.6613.18<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Chromium <!-- GEN:chromium-version -->130.0.6723.31<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| WebKit <!-- GEN:webkit-version -->18.0<!-- GEN:stop --> | ✅ | ✅ | ✅ |
| Firefox <!-- GEN:firefox-version -->128.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Firefox <!-- GEN:firefox-version -->131.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Headless execution is supported for all the browsers on all platforms. Check out [system requirements](https://playwright.dev/java/docs/intro#system-requirements) for details.
+2 -3
View File
@@ -2,11 +2,10 @@
* make sure to have at least Java 8 and Maven 3.6.3
* clone playwright for java: http://github.com/microsoft/playwright-java
* set new driver version in `scripts/DRIVER_VERSION`
* regenerate API: `./scripts/download_driver.sh -f && ./scripts/generate_api.sh && ./scripts/update_readme.sh`
* `./scripts/roll_driver.sh 1.47.0-beta-1726138322000`
* commit & send PR with the roll
### Finding driver version
## Finding driver version
For development versions of Playwright, you can find the latest version by looking at [publish_canary](https://github.com/microsoft/playwright/actions/workflows/publish_canary.yml) workflow -> `publish canary NPM & Publish canary Docker` -> `build & publish driver` step -> `PACKAGE_VERSION`
<img width="960" alt="image" src="https://github.com/microsoft/playwright-java/assets/9798949/4f33a7f1-b39a-4179-8ae7-fb1d84094c75">
+17
View File
@@ -0,0 +1,17 @@
# Support
## How to file issues and get help
This project uses GitHub issues to track bugs and feature requests. Please search the [existing issues][gh-issues] before filing new ones to avoid duplicates. For new issues, file your bug or feature request as a new issue using corresponding template.
For help and questions about using this project, please see the [docs site for Playwright for Java][docs].
Join our community [Discord Server][discord-server] to connect with other developers using Playwright and ask questions in our 'help-playwright' forum.
## Microsoft Support Policy
Support for Playwright for Java is limited to the resources listed above.
[gh-issues]: https://github.com/microsoft/playwright-java/issues/
[docs]: https://playwright.dev/java/
[discord-server]: https://aka.ms/playwright/discord
+1 -1
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>com.microsoft.playwright</groupId>
<artifactId>parent-pom</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
</parent>
<artifactId>driver-bundle</artifactId>
+1 -1
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>com.microsoft.playwright</groupId>
<artifactId>parent-pom</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
</parent>
<artifactId>driver</artifactId>
+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>org.example</groupId>
<artifactId>examples</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
<name>Playwright Client Examples</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+5 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>com.microsoft.playwright</groupId>
<artifactId>parent-pom</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
</parent>
<artifactId>playwright</artifactId>
@@ -61,6 +61,10 @@
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
</dependency>
<dependency>
<groupId>org.opentest4j</groupId>
<artifactId>opentest4j</artifactId>
@@ -46,12 +46,10 @@ public interface APIRequest {
*
* <p> <strong>Details</strong>
*
* <p> An array of client certificates to be used. Each certificate object must have both {@code certPath} and {@code keyPath}
* or a single {@code pfxPath} to load the client certificate. Optionally, {@code passphrase} property should be provided
* if the certficiate is encrypted. The {@code origin} property should be provided with an exact match to the request
* origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> Using Client Certificates in combination with Proxy Servers is not supported.
* <p> An array of client certificates to be used. Each certificate object must have either both {@code certPath} and {@code
* keyPath}, a single {@code pfxPath}, or their corresponding direct value equivalents ({@code cert} and {@code key}, or
* {@code pfx}). Optionally, {@code passphrase} property should be provided if the certificate is encrypted. The {@code
* origin} property should be provided with an exact match to the request origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by
* replacing {@code localhost} with {@code local.playwright}.
@@ -121,12 +119,10 @@ public interface APIRequest {
*
* <p> <strong>Details</strong>
*
* <p> An array of client certificates to be used. Each certificate object must have both {@code certPath} and {@code keyPath}
* or a single {@code pfxPath} to load the client certificate. Optionally, {@code passphrase} property should be provided
* if the certficiate is encrypted. The {@code origin} property should be provided with an exact match to the request
* origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> Using Client Certificates in combination with Proxy Servers is not supported.
* <p> An array of client certificates to be used. Each certificate object must have either both {@code certPath} and {@code
* keyPath}, a single {@code pfxPath}, or their corresponding direct value equivalents ({@code cert} and {@code key}, or
* {@code pfx}). Optionally, {@code passphrase} property should be provided if the certificate is encrypted. The {@code
* origin} property should be provided with an exact match to the request origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by
* replacing {@code localhost} with {@code local.playwright}.
@@ -129,8 +129,7 @@ public interface APIRequestContext {
* }</pre>
*
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* multipart/form-data} encoding, by specifiying the {@code multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -167,8 +166,7 @@ public interface APIRequestContext {
* }</pre>
*
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* multipart/form-data} encoding, by specifiying the {@code multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -204,8 +202,7 @@ public interface APIRequestContext {
* }</pre>
*
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* multipart/form-data} encoding, by specifiying the {@code multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -242,8 +239,7 @@ public interface APIRequestContext {
* }</pre>
*
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* multipart/form-data} encoding, by specifiying the {@code multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -43,8 +43,8 @@ public interface APIResponse {
*/
Map<String, String> headers();
/**
* An array with all the request HTTP headers associated with this response. Header names are not lower-cased. Headers with
* multiple entries, such as {@code Set-Cookie}, appear in the array multiple times.
* An array with all the response HTTP headers associated with this response. Header names are not lower-cased. Headers
* with multiple entries, such as {@code Set-Cookie}, appear in the array multiple times.
*
* @since v1.16
*/
@@ -101,12 +101,10 @@ public interface Browser extends AutoCloseable {
*
* <p> <strong>Details</strong>
*
* <p> An array of client certificates to be used. Each certificate object must have both {@code certPath} and {@code keyPath}
* or a single {@code pfxPath} to load the client certificate. Optionally, {@code passphrase} property should be provided
* if the certficiate is encrypted. The {@code origin} property should be provided with an exact match to the request
* origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> Using Client Certificates in combination with Proxy Servers is not supported.
* <p> An array of client certificates to be used. Each certificate object must have either both {@code certPath} and {@code
* keyPath}, a single {@code pfxPath}, or their corresponding direct value equivalents ({@code cert} and {@code key}, or
* {@code pfx}). Optionally, {@code passphrase} property should be provided if the certificate is encrypted. The {@code
* origin} property should be provided with an exact match to the request origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by
* replacing {@code localhost} with {@code local.playwright}.
@@ -179,10 +177,6 @@ public interface Browser extends AutoCloseable {
public List<String> permissions;
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public Proxy proxy;
/**
@@ -316,12 +310,10 @@ public interface Browser extends AutoCloseable {
*
* <p> <strong>Details</strong>
*
* <p> An array of client certificates to be used. Each certificate object must have both {@code certPath} and {@code keyPath}
* or a single {@code pfxPath} to load the client certificate. Optionally, {@code passphrase} property should be provided
* if the certficiate is encrypted. The {@code origin} property should be provided with an exact match to the request
* origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> Using Client Certificates in combination with Proxy Servers is not supported.
* <p> An array of client certificates to be used. Each certificate object must have either both {@code certPath} and {@code
* keyPath}, a single {@code pfxPath}, or their corresponding direct value equivalents ({@code cert} and {@code key}, or
* {@code pfx}). Optionally, {@code passphrase} property should be provided if the certificate is encrypted. The {@code
* origin} property should be provided with an exact match to the request origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by
* replacing {@code localhost} with {@code local.playwright}.
@@ -446,20 +438,12 @@ public interface Browser extends AutoCloseable {
}
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public NewContextOptions setProxy(String server) {
return setProxy(new Proxy(server));
}
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public NewContextOptions setProxy(Proxy proxy) {
this.proxy = proxy;
@@ -666,12 +650,10 @@ public interface Browser extends AutoCloseable {
*
* <p> <strong>Details</strong>
*
* <p> An array of client certificates to be used. Each certificate object must have both {@code certPath} and {@code keyPath}
* or a single {@code pfxPath} to load the client certificate. Optionally, {@code passphrase} property should be provided
* if the certficiate is encrypted. The {@code origin} property should be provided with an exact match to the request
* origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> Using Client Certificates in combination with Proxy Servers is not supported.
* <p> An array of client certificates to be used. Each certificate object must have either both {@code certPath} and {@code
* keyPath}, a single {@code pfxPath}, or their corresponding direct value equivalents ({@code cert} and {@code key}, or
* {@code pfx}). Optionally, {@code passphrase} property should be provided if the certificate is encrypted. The {@code
* origin} property should be provided with an exact match to the request origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by
* replacing {@code localhost} with {@code local.playwright}.
@@ -744,10 +726,6 @@ public interface Browser extends AutoCloseable {
public List<String> permissions;
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public Proxy proxy;
/**
@@ -881,12 +859,10 @@ public interface Browser extends AutoCloseable {
*
* <p> <strong>Details</strong>
*
* <p> An array of client certificates to be used. Each certificate object must have both {@code certPath} and {@code keyPath}
* or a single {@code pfxPath} to load the client certificate. Optionally, {@code passphrase} property should be provided
* if the certficiate is encrypted. The {@code origin} property should be provided with an exact match to the request
* origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> Using Client Certificates in combination with Proxy Servers is not supported.
* <p> An array of client certificates to be used. Each certificate object must have either both {@code certPath} and {@code
* keyPath}, a single {@code pfxPath}, or their corresponding direct value equivalents ({@code cert} and {@code key}, or
* {@code pfx}). Optionally, {@code passphrase} property should be provided if the certificate is encrypted. The {@code
* origin} property should be provided with an exact match to the request origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by
* replacing {@code localhost} with {@code local.playwright}.
@@ -1011,20 +987,12 @@ public interface Browser extends AutoCloseable {
}
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public NewPageOptions setProxy(String server) {
return setProxy(new Proxy(server));
}
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public NewPageOptions setProxy(Proxy proxy) {
this.proxy = proxy;
@@ -30,8 +30,9 @@ import java.util.regex.Pattern;
* <p> If a page opens another page, e.g. with a {@code window.open} call, the popup will belong to the parent page's browser
* context.
*
* <p> Playwright allows creating "incognito" browser contexts with {@link com.microsoft.playwright.Browser#newContext
* Browser.newContext()} method. "Incognito" browser contexts don't write any browsing data to disk.
* <p> Playwright allows creating isolated non-persistent browser contexts with {@link
* com.microsoft.playwright.Browser#newContext Browser.newContext()} method. Non-persistent browser contexts don't write
* any browsing data to disk.
* <pre>{@code
* // Create a new incognito browser context
* BrowserContext context = browser.newContext();
@@ -926,7 +927,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -982,7 +983,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1036,7 +1037,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1092,7 +1093,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1146,7 +1147,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1202,7 +1203,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1256,7 +1257,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <a
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code
* path} is a relative path, then it is resolved relative to the current working directory.
@@ -1271,13 +1272,94 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <a
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code
* path} is a relative path, then it is resolved relative to the current working directory.
* @since v1.23
*/
void routeFromHAR(Path har, RouteFromHAROptions options);
/**
* This method allows to modify websocket connections that are made by any page in the browser context.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before creating any pages.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple handler that blocks some websocket messages. See {@code WebSocketRoute} for more details
* and examples.
* <pre>{@code
* context.routeWebSocket("/ws", ws -> {
* ws.routeSend(message -> {
* if ("to-be-blocked".equals(message))
* return;
* ws.send(message);
* });
* ws.connect();
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(String url, Consumer<WebSocketRoute> handler);
/**
* This method allows to modify websocket connections that are made by any page in the browser context.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before creating any pages.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple handler that blocks some websocket messages. See {@code WebSocketRoute} for more details
* and examples.
* <pre>{@code
* context.routeWebSocket("/ws", ws -> {
* ws.routeSend(message -> {
* if ("to-be-blocked".equals(message))
* return;
* ws.send(message);
* });
* ws.connect();
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(Pattern url, Consumer<WebSocketRoute> handler);
/**
* This method allows to modify websocket connections that are made by any page in the browser context.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before creating any pages.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple handler that blocks some websocket messages. See {@code WebSocketRoute} for more details
* and examples.
* <pre>{@code
* context.routeWebSocket("/ws", ws -> {
* ws.routeSend(message -> {
* if ("to-be-blocked".equals(message))
* return;
* ws.send(message);
* });
* ws.connect();
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(Predicate<String> url, Consumer<WebSocketRoute> handler);
/**
* This setting will change the default maximum navigation time for the following methods and related shortcuts:
* <ul>
@@ -460,12 +460,10 @@ public interface BrowserType {
*
* <p> <strong>Details</strong>
*
* <p> An array of client certificates to be used. Each certificate object must have both {@code certPath} and {@code keyPath}
* or a single {@code pfxPath} to load the client certificate. Optionally, {@code passphrase} property should be provided
* if the certficiate is encrypted. The {@code origin} property should be provided with an exact match to the request
* origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> Using Client Certificates in combination with Proxy Servers is not supported.
* <p> An array of client certificates to be used. Each certificate object must have either both {@code certPath} and {@code
* keyPath}, a single {@code pfxPath}, or their corresponding direct value equivalents ({@code cert} and {@code key}, or
* {@code pfx}). Optionally, {@code passphrase} property should be provided if the certificate is encrypted. The {@code
* origin} property should be provided with an exact match to the request origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by
* replacing {@code localhost} with {@code local.playwright}.
@@ -763,12 +761,10 @@ public interface BrowserType {
*
* <p> <strong>Details</strong>
*
* <p> An array of client certificates to be used. Each certificate object must have both {@code certPath} and {@code keyPath}
* or a single {@code pfxPath} to load the client certificate. Optionally, {@code passphrase} property should be provided
* if the certficiate is encrypted. The {@code origin} property should be provided with an exact match to the request
* origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> Using Client Certificates in combination with Proxy Servers is not supported.
* <p> An array of client certificates to be used. Each certificate object must have either both {@code certPath} and {@code
* keyPath}, a single {@code pfxPath}, or their corresponding direct value equivalents ({@code cert} and {@code key}, or
* {@code pfx}). Optionally, {@code passphrase} property should be provided if the certificate is encrypted. The {@code
* origin} property should be provided with an exact match to the request origin that the certificate is valid for.
*
* <p> <strong>NOTE:</strong> When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by
* replacing {@code localhost} with {@code local.playwright}.
@@ -777,7 +777,7 @@ public interface ElementHandle extends JSHandle {
*/
public Boolean force;
/**
* @deprecated This option will default to {@code true} in the future.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -797,7 +797,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* @deprecated This option will default to {@code true} in the future.
* @deprecated This option has no effect.
*/
public SelectOptionOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -290,7 +290,8 @@ public interface Frame {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -375,7 +376,8 @@ public interface Frame {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public ClickOptions setTrial(boolean trial) {
this.trial = trial;
@@ -426,7 +428,8 @@ public interface Frame {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -504,7 +507,8 @@ public interface Frame {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public DblclickOptions setTrial(boolean trial) {
this.trial = trial;
@@ -1127,7 +1131,8 @@ public interface Frame {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -1191,7 +1196,8 @@ public interface Frame {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public HoverOptions setTrial(boolean trial) {
this.trial = trial;
@@ -1661,7 +1667,7 @@ public interface Frame {
*/
public Boolean force;
/**
* @deprecated This option will default to {@code true} in the future.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1686,7 +1692,7 @@ public interface Frame {
return this;
}
/**
* @deprecated This option will default to {@code true} in the future.
* @deprecated This option has no effect.
*/
public SelectOptionOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1932,7 +1938,8 @@ public interface Frame {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -1996,7 +2003,8 @@ public interface Frame {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public TapOptions setTrial(boolean trial) {
this.trial = trial;
@@ -22,10 +22,10 @@ import java.util.regex.Pattern;
/**
* FrameLocator represents a view to the {@code iframe} on the page. It captures the logic sufficient to retrieve the
* {@code iframe} and locate elements in that iframe. FrameLocator can be created with either {@link
* com.microsoft.playwright.Page#frameLocator Page.frameLocator()} or {@link com.microsoft.playwright.Locator#frameLocator
* Locator.frameLocator()} method.
* com.microsoft.playwright.Locator#contentFrame Locator.contentFrame()}, {@link com.microsoft.playwright.Page#frameLocator
* Page.frameLocator()} or {@link com.microsoft.playwright.Locator#frameLocator Locator.frameLocator()} method.
* <pre>{@code
* Locator locator = page.frameLocator("#my-frame").getByText("Submit");
* Locator locator = page.locator("#my-frame").contentFrame().getByText("Submit");
* locator.click();
* }</pre>
*
@@ -35,10 +35,10 @@ import java.util.regex.Pattern;
* a given selector.
* <pre>{@code
* // Throws if there are several frames in DOM:
* page.frame_locator(".result-frame").getByRole(AriaRole.BUTTON).click();
* page.locator(".result-frame").contentFrame().getByRole(AriaRole.BUTTON).click();
*
* // Works because we explicitly tell locator to pick the first frame:
* page.frame_locator(".result-frame").first().getByRole(AriaRole.BUTTON).click();
* page.locator(".result-frame").first().contentFrame().getByRole(AriaRole.BUTTON).click();
* }</pre>
*
* <p> <strong>Converting Locator to FrameLocator</strong>
@@ -383,7 +383,8 @@ public interface FrameLocator {
}
}
/**
* Returns locator to the first matching frame.
* @deprecated Use {@link com.microsoft.playwright.Locator#first Locator.first()} followed by {@link
* com.microsoft.playwright.Locator#contentFrame Locator.contentFrame()} instead.
*
* @since v1.17
*/
@@ -953,7 +954,8 @@ public interface FrameLocator {
*/
Locator getByTitle(Pattern text, GetByTitleOptions options);
/**
* Returns locator to the last matching frame.
* @deprecated Use {@link com.microsoft.playwright.Locator#last Locator.last()} followed by {@link
* com.microsoft.playwright.Locator#contentFrame Locator.contentFrame()} instead.
*
* @since v1.17
*/
@@ -1003,7 +1005,8 @@ public interface FrameLocator {
*/
Locator locator(Locator selectorOrLocator, LocatorOptions options);
/**
* Returns locator to the n-th matching frame. It's zero based, {@code nth(0)} selects the first frame.
* @deprecated Use {@link com.microsoft.playwright.Locator#nth Locator.nth()} followed by {@link
* com.microsoft.playwright.Locator#contentFrame Locator.contentFrame()} instead.
*
* @since v1.17
*/
@@ -1018,7 +1021,7 @@ public interface FrameLocator {
*
* <p> <strong>Usage</strong>
* <pre>{@code
* FrameLocator frameLocator = page.frameLocator("iframe[name=\"embedded\"]");
* FrameLocator frameLocator = page.locator("iframe[name=\"embedded\"]").contentFrame();
* // ...
* Locator locator = frameLocator.owner();
* assertThat(locator).isVisible();
@@ -235,7 +235,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -312,7 +313,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public ClickOptions setTrial(boolean trial) {
this.trial = trial;
@@ -358,7 +360,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -428,7 +431,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public DblclickOptions setTrial(boolean trial) {
this.trial = trial;
@@ -1059,7 +1063,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -1115,7 +1120,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public HoverOptions setTrial(boolean trial) {
this.trial = trial;
@@ -1671,7 +1677,7 @@ public interface Locator {
*/
public Boolean force;
/**
* @deprecated This option will default to {@code true} in the future.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1691,7 +1697,7 @@ public interface Locator {
return this;
}
/**
* @deprecated This option will default to {@code true} in the future.
* @deprecated This option has no effect.
*/
public SelectOptionOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1882,7 +1888,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -1938,7 +1945,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public TapOptions setTrial(boolean trial) {
this.trial = trial;
@@ -2137,10 +2145,9 @@ public interface Locator {
* When the locator points to a list of elements, this returns an array of locators, pointing to their respective elements.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Locator#all Locator.all()} does not wait for elements to match the locator, and instead
* immediately returns whatever is present in the page. When the list of elements changes dynamically, {@link
* com.microsoft.playwright.Locator#all Locator.all()} will produce unpredictable and flaky results. When the list of
* elements is stable, but loaded dynamically, wait for the full list to finish loading before calling {@link
* com.microsoft.playwright.Locator#all Locator.all()}.
* immediately returns whatever is present in the page.When the list of elements changes dynamically, {@link com.microsoft.playwright.Locator#all Locator.all()} will produce
* unpredictable and flaky results.When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before calling
* {@link com.microsoft.playwright.Locator#all Locator.all()}.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -4077,7 +4084,10 @@ public interface Locator {
*/
Locator nth(int index);
/**
* Creates a locator that matches either of the two locators.
* Creates a locator matching all elements that match one or both of the two locators.
*
* <p> Note that when both locators match something, the resulting locator will have multiple matches and violate <a
* href="https://playwright.dev/java/docs/locators#strictness">locator strictness</a> guidelines.
*
* <p> <strong>Usage</strong>
*
@@ -560,7 +560,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -645,7 +646,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public ClickOptions setTrial(boolean trial) {
this.trial = trial;
@@ -723,7 +725,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -801,7 +804,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public DblclickOptions setTrial(boolean trial) {
this.trial = trial;
@@ -1591,7 +1595,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -1655,7 +1660,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public HoverOptions setTrial(boolean trial) {
this.trial = trial;
@@ -2421,7 +2427,7 @@ public interface Page extends AutoCloseable {
/**
* When set to {@code minimal}, only record information necessary for routing from HAR. This omits sizes, timing, page,
* cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to {@code
* full}.
* minimal}.
*/
public HarMode updateMode;
/**
@@ -2461,7 +2467,7 @@ public interface Page extends AutoCloseable {
/**
* When set to {@code minimal}, only record information necessary for routing from HAR. This omits sizes, timing, page,
* cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to {@code
* full}.
* minimal}.
*/
public RouteFromHAROptions setUpdateMode(HarMode updateMode) {
this.updateMode = updateMode;
@@ -2691,7 +2697,7 @@ public interface Page extends AutoCloseable {
*/
public Boolean force;
/**
* @deprecated This option will default to {@code true} in the future.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -2716,7 +2722,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* @deprecated This option will default to {@code true} in the future.
* @deprecated This option has no effect.
*/
public SelectOptionOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2962,7 +2968,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -3026,7 +3033,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public TapOptions setTrial(boolean trial) {
this.trial = trial;
@@ -5414,6 +5422,25 @@ public interface Page extends AutoCloseable {
* @since v1.8
*/
Response goForward(GoForwardOptions options);
/**
* Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will be
* collected.
*
* <p> This is useful to help detect memory leaks. For example, if your page has a large object {@code "suspect"} that might be
* leaked, you can check that it does not leak by using a <a
* href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef">{@code WeakRef}</a>.
* <pre>{@code
* // 1. In your page, save a WeakRef for the "suspect".
* page.evaluate("globalThis.suspectWeakRef = new WeakRef(suspect)");
* // 2. Request garbage collection.
* page.requestGC();
* // 3. Check that weak ref does not deref to the original object.
* assertTrue(page.evaluate("!globalThis.suspectWeakRef.deref()"));
* }</pre>
*
* @since v1.48
*/
void requestGC();
/**
* Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first
* non-redirect response.
@@ -5773,8 +5800,7 @@ public interface Page extends AutoCloseable {
* <p> User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from
* the place it was paused.
*
* <p> <strong>NOTE:</strong> This method requires Playwright to be started in a headed mode, with a falsy {@code headless} value in the {@link
* com.microsoft.playwright.BrowserType#launch BrowserType.launch()}.
* <p> <strong>NOTE:</strong> This method requires Playwright to be started in a headed mode, with a falsy {@code headless} option.
*
* @since v1.9
*/
@@ -6041,15 +6067,13 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> Running the handler will alter your page state mid-test. For example it will change the currently focused element and
* move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and
* mouse state being unchanged. <br /> <br /> For example, consider a test that calls {@link
* com.microsoft.playwright.Locator#focus Locator.focus()} followed by {@link com.microsoft.playwright.Keyboard#press
* Keyboard.press()}. If your handler clicks a button between these two actions, the focused element most likely will be
* wrong, and key press will happen on the unexpected element. Use {@link com.microsoft.playwright.Locator#press
* Locator.press()} instead to avoid this problem. <br /> <br /> Another example is a series of mouse actions, where {@link
* com.microsoft.playwright.Mouse#move Mouse.move()} is followed by {@link com.microsoft.playwright.Mouse#down
* Mouse.down()}. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse
* down. Prefer self-contained actions like {@link com.microsoft.playwright.Locator#click Locator.click()} that do not rely
* on the state being unchanged by a handler.
* mouse state being unchanged.For example, consider a test that calls {@link com.microsoft.playwright.Locator#focus Locator.focus()} followed by
* {@link com.microsoft.playwright.Keyboard#press Keyboard.press()}. If your handler clicks a button between these two
* actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use {@link
* com.microsoft.playwright.Locator#press Locator.press()} instead to avoid this problem.Another example is a series of mouse actions, where {@link com.microsoft.playwright.Mouse#move Mouse.move()} is followed
* by {@link com.microsoft.playwright.Mouse#down Mouse.down()}. Again, when the handler runs between these two actions, the
* mouse position will be wrong during the mouse down. Prefer self-contained actions like {@link
* com.microsoft.playwright.Locator#click Locator.click()} that do not rely on the state being unchanged by a handler.
*
* <p> <strong>Usage</strong>
*
@@ -6135,15 +6159,13 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> Running the handler will alter your page state mid-test. For example it will change the currently focused element and
* move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and
* mouse state being unchanged. <br /> <br /> For example, consider a test that calls {@link
* com.microsoft.playwright.Locator#focus Locator.focus()} followed by {@link com.microsoft.playwright.Keyboard#press
* Keyboard.press()}. If your handler clicks a button between these two actions, the focused element most likely will be
* wrong, and key press will happen on the unexpected element. Use {@link com.microsoft.playwright.Locator#press
* Locator.press()} instead to avoid this problem. <br /> <br /> Another example is a series of mouse actions, where {@link
* com.microsoft.playwright.Mouse#move Mouse.move()} is followed by {@link com.microsoft.playwright.Mouse#down
* Mouse.down()}. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse
* down. Prefer self-contained actions like {@link com.microsoft.playwright.Locator#click Locator.click()} that do not rely
* on the state being unchanged by a handler.
* mouse state being unchanged.For example, consider a test that calls {@link com.microsoft.playwright.Locator#focus Locator.focus()} followed by
* {@link com.microsoft.playwright.Keyboard#press Keyboard.press()}. If your handler clicks a button between these two
* actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use {@link
* com.microsoft.playwright.Locator#press Locator.press()} instead to avoid this problem.Another example is a series of mouse actions, where {@link com.microsoft.playwright.Mouse#move Mouse.move()} is followed
* by {@link com.microsoft.playwright.Mouse#down Mouse.down()}. Again, when the handler runs between these two actions, the
* mouse position will be wrong during the mouse down. Prefer self-contained actions like {@link
* com.microsoft.playwright.Locator#click Locator.click()} that do not rely on the state being unchanged by a handler.
*
* <p> <strong>Usage</strong>
*
@@ -6240,7 +6262,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6299,7 +6321,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6356,7 +6378,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6415,7 +6437,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6472,7 +6494,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6531,7 +6553,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6585,7 +6607,7 @@ public interface Page extends AutoCloseable {
*
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <a
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code
* path} is a relative path, then it is resolved relative to the current working directory.
@@ -6600,13 +6622,88 @@ public interface Page extends AutoCloseable {
*
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <a
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code
* path} is a relative path, then it is resolved relative to the current working directory.
* @since v1.23
*/
void routeFromHAR(Path har, RouteFromHAROptions options);
/**
* This method allows to modify websocket connections that are made by the page.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before navigating the page.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple mock that responds to a single message. See {@code WebSocketRoute} for more details and
* examples.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* ws.onMessage(message -> {
* if ("request".equals(message))
* ws.send("response");
* });
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(String url, Consumer<WebSocketRoute> handler);
/**
* This method allows to modify websocket connections that are made by the page.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before navigating the page.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple mock that responds to a single message. See {@code WebSocketRoute} for more details and
* examples.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* ws.onMessage(message -> {
* if ("request".equals(message))
* ws.send("response");
* });
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(Pattern url, Consumer<WebSocketRoute> handler);
/**
* This method allows to modify websocket connections that are made by the page.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before navigating the page.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple mock that responds to a single message. See {@code WebSocketRoute} for more details and
* examples.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* ws.onMessage(message -> {
* if ("request".equals(message))
* ws.send("response");
* });
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(Predicate<String> url, Consumer<WebSocketRoute> handler);
/**
* Returns the buffer with the captured screenshot.
*
@@ -7256,6 +7353,8 @@ public interface Page extends AutoCloseable {
* page.navigate("https://example.com");
* }</pre>
*
* @param width Page width in pixels.
* @param height Page height in pixels.
* @since v1.8
*/
void setViewportSize(int width, int height);
@@ -348,7 +348,7 @@ public interface Route {
*/
void abort(String errorCode);
/**
* Continues route's request with optional overrides.
* Sends route's request to the network with optional overrides.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -368,13 +368,17 @@ public interface Route {
* through redirects, use the combination of {@link com.microsoft.playwright.Route#fetch Route.fetch()} and {@link
* com.microsoft.playwright.Route#fulfill Route.fulfill()} instead.
*
* <p> {@link com.microsoft.playwright.Route#resume Route.resume()} will immediately send the request to the network, other
* matching handlers won't be invoked. Use {@link com.microsoft.playwright.Route#fallback Route.fallback()} If you want
* next matching handler in the chain to be invoked.
*
* @since v1.8
*/
default void resume() {
resume(null);
}
/**
* Continues route's request with optional overrides.
* Sends route's request to the network with optional overrides.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -394,16 +398,23 @@ public interface Route {
* through redirects, use the combination of {@link com.microsoft.playwright.Route#fetch Route.fetch()} and {@link
* com.microsoft.playwright.Route#fulfill Route.fulfill()} instead.
*
* <p> {@link com.microsoft.playwright.Route#resume Route.resume()} will immediately send the request to the network, other
* matching handlers won't be invoked. Use {@link com.microsoft.playwright.Route#fallback Route.fallback()} If you want
* next matching handler in the chain to be invoked.
*
* @since v1.8
*/
void resume(ResumeOptions options);
/**
* When several routes match the given pattern, they run in the order opposite to their registration. That way the last
* Continues route's request with optional overrides. The method is similar to {@link com.microsoft.playwright.Route#resume
* Route.resume()} with the difference that other matching handlers will be invoked before sending the request.
*
* <p> <strong>Usage</strong>
*
* <p> When several routes match the given pattern, they run in the order opposite to their registration. That way the last
* registered route can always override all the previous ones. In the example below, request will be handled by the
* bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
* registered route.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.route("**\/*", route -> {
* // Runs last.
@@ -457,18 +468,24 @@ public interface Route {
* });
* }</pre>
*
* <p> Use {@link com.microsoft.playwright.Route#resume Route.resume()} to immediately send the request to the network, other
* matching handlers won't be invoked in that case.
*
* @since v1.23
*/
default void fallback() {
fallback(null);
}
/**
* When several routes match the given pattern, they run in the order opposite to their registration. That way the last
* Continues route's request with optional overrides. The method is similar to {@link com.microsoft.playwright.Route#resume
* Route.resume()} with the difference that other matching handlers will be invoked before sending the request.
*
* <p> <strong>Usage</strong>
*
* <p> When several routes match the given pattern, they run in the order opposite to their registration. That way the last
* registered route can always override all the previous ones. In the example below, request will be handled by the
* bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
* registered route.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.route("**\/*", route -> {
* // Runs last.
@@ -522,6 +539,9 @@ public interface Route {
* });
* }</pre>
*
* <p> Use {@link com.microsoft.playwright.Route#resume Route.resume()} to immediately send the request to the network, other
* matching handlers won't be invoked in that case.
*
* @since v1.23
*/
void fallback(FallbackOptions options);
@@ -39,8 +39,8 @@ public interface Tracing {
class StartOptions {
/**
* If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the {@code
* tracesDir} folder specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify the
* final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stop
* tracesDir} directory specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify
* the final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stop
* Tracing.stop()} instead.
*/
public String name;
@@ -69,8 +69,8 @@ public interface Tracing {
/**
* If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the {@code
* tracesDir} folder specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify the
* final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stop
* tracesDir} directory specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify
* the final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stop
* Tracing.stop()} instead.
*/
public StartOptions setName(String name) {
@@ -115,8 +115,8 @@ public interface Tracing {
class StartChunkOptions {
/**
* If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the {@code
* tracesDir} folder specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify the
* final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stopChunk
* tracesDir} directory specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify
* the final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stopChunk
* Tracing.stopChunk()} instead.
*/
public String name;
@@ -127,8 +127,8 @@ public interface Tracing {
/**
* If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the {@code
* tracesDir} folder specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify the
* final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stopChunk
* tracesDir} directory specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify
* the final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stopChunk
* Tracing.stopChunk()} instead.
*/
public StartChunkOptions setName(String name) {
@@ -0,0 +1,223 @@
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.playwright;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Whenever a <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket">{@code WebSocket}</a> route is set up
* with {@link com.microsoft.playwright.Page#routeWebSocket Page.routeWebSocket()} or {@link
* com.microsoft.playwright.BrowserContext#routeWebSocket BrowserContext.routeWebSocket()}, the {@code WebSocketRoute}
* object allows to handle the WebSocket, like an actual server would do.
*
* <p> <strong>Mocking</strong>
*
* <p> By default, the routed WebSocket will not connect to the server. This way, you can mock entire communcation over the
* WebSocket. Here is an example that responds to a {@code "request"} with a {@code "response"}.
* <pre>{@code
* page.routeWebSocket("wss://example.com/ws", ws -> {
* ws.onMessage(message -> {
* if ("request".equals(message))
* ws.send("response");
* });
* });
* }</pre>
*
* <p> Since we do not call {@link com.microsoft.playwright.WebSocketRoute#connectToServer WebSocketRoute.connectToServer()}
* inside the WebSocket route handler, Playwright assumes that WebSocket will be mocked, and opens the WebSocket inside the
* page automatically.
*
* <p> Here is another example that handles JSON messages:
* <pre>{@code
* page.routeWebSocket("wss://example.com/ws", ws -> {
* ws.onMessage(message -> {
* JsonObject json = new JsonParser().parse(message).getAsJsonObject();
* if ("question".equals(json.get("request").getAsString())) {
* Map<String, String> result = new HashMap();
* result.put("response", "answer");
* ws.send(gson.toJson(result));
* }
* });
* });
* }</pre>
*
* <p> <strong>Intercepting</strong>
*
* <p> Alternatively, you may want to connect to the actual server, but intercept messages in-between and modify or block them.
* Calling {@link com.microsoft.playwright.WebSocketRoute#connectToServer WebSocketRoute.connectToServer()} returns a
* server-side {@code WebSocketRoute} instance that you can send messages to, or handle incoming messages.
*
* <p> Below is an example that modifies some messages sent by the page to the server. Messages sent from the server to the
* page are left intact, relying on the default forwarding.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* WebSocketRoute server = ws.connectToServer();
* ws.onMessage(message -> {
* if ("request".equals(message))
* server.send("request2");
* else
* server.send(message);
* });
* });
* }</pre>
*
* <p> After connecting to the server, all **messages are forwarded** between the page and the server by default.
*
* <p> However, if you call {@link com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} on the
* original route, messages from the page to the server **will not be forwarded** anymore, but should instead be handled by
* the {@code handler}.
*
* <p> Similarly, calling {@link com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} on the
* server-side WebSocket will **stop forwarding messages** from the server to the page, and {@code handler} should take
* care of them.
*
* <p> The following example blocks some messages in both directions. Since it calls {@link
* com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} in both directions, there is no automatic
* forwarding at all.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* WebSocketRoute server = ws.connectToServer();
* ws.onMessage(message -> {
* if (!"blocked-from-the-page".equals(message))
* server.send(message);
* });
* server.onMessage(message -> {
* if (!"blocked-from-the-server".equals(message))
* ws.send(message);
* });
* });
* }</pre>
*/
public interface WebSocketRoute {
class CloseOptions {
/**
* Optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code">close code</a>.
*/
public Integer code;
/**
* Optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason">close reason</a>.
*/
public String reason;
/**
* Optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code">close code</a>.
*/
public CloseOptions setCode(int code) {
this.code = code;
return this;
}
/**
* Optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason">close reason</a>.
*/
public CloseOptions setReason(String reason) {
this.reason = reason;
return this;
}
}
/**
* Closes one side of the WebSocket connection.
*
* @since v1.48
*/
default void close() {
close(null);
}
/**
* Closes one side of the WebSocket connection.
*
* @since v1.48
*/
void close(CloseOptions options);
/**
* By default, routed WebSocket does not connect to the server, so you can mock entire WebSocket communication. This method
* connects to the actual WebSocket server, and returns the server-side {@code WebSocketRoute} instance, giving the ability
* to send and receive messages from the server.
*
* <p> Once connected to the server:
* <ul>
* <li> Messages received from the server will be **automatically forwarded** to the WebSocket in the page, unless {@link
* com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} is called on the server-side {@code
* WebSocketRoute}.</li>
* <li> Messages sent by the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send">{@code
* WebSocket.send()}</a> call in the page will be **automatically forwarded** to the server, unless {@link
* com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} is called on the original {@code
* WebSocketRoute}.</li>
* </ul>
*
* <p> See examples at the top for more details.
*
* @since v1.48
*/
WebSocketRoute connectToServer();
/**
* Allows to handle <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close">{@code WebSocket.close}</a>.
*
* <p> By default, closing one side of the connection, either in the page or on the server, will close the other side. However,
* when {@link com.microsoft.playwright.WebSocketRoute#onClose WebSocketRoute.onClose()} handler is set up, the default
* forwarding of closure is disabled, and handler should take care of it.
*
* @param handler Function that will handle WebSocket closure. Received an optional <a
* href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code">close code</a> and an optional <a
* href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason">close reason</a>.
* @since v1.48
*/
void onClose(BiConsumer<Integer, String> handler);
/**
* This method allows to handle messages that are sent by the WebSocket, either from the page or from the server.
*
* <p> When called on the original WebSocket route, this method handles messages sent from the page. You can handle this
* messages by responding to them with {@link com.microsoft.playwright.WebSocketRoute#send WebSocketRoute.send()},
* forwarding them to the server-side connection returned by {@link com.microsoft.playwright.WebSocketRoute#connectToServer
* WebSocketRoute.connectToServer()} or do something else.
*
* <p> Once this method is called, messages are not automatically forwarded to the server or to the page - you should do that
* manually by calling {@link com.microsoft.playwright.WebSocketRoute#send WebSocketRoute.send()}. See examples at the top
* for more details.
*
* <p> Calling this method again will override the handler with a new one.
*
* @param handler Function that will handle messages.
* @since v1.48
*/
void onMessage(Consumer<WebSocketFrame> handler);
/**
* Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called on
* the result of {@link com.microsoft.playwright.WebSocketRoute#connectToServer WebSocketRoute.connectToServer()}, sends
* the message to the server. See examples at the top for more details.
*
* @param message Message to send.
* @since v1.48
*/
void send(String message);
/**
* Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called on
* the result of {@link com.microsoft.playwright.WebSocketRoute#connectToServer WebSocketRoute.connectToServer()}, sends
* the message to the server. See examples at the top for more details.
*
* @param message Message to send.
* @since v1.48
*/
void send(byte[] message);
/**
* URL of the WebSocket created in the page.
*
* @since v1.48
*/
String url();
}
@@ -50,6 +50,7 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
final List<PageImpl> backgroundPages = new ArrayList<>();
final Router routes = new Router();
final WebSocketRouter webSocketRoutes = new WebSocketRouter();
private boolean closeWasCalled;
private final WaitableEvent<EventType, ?> closePromise;
final Map<String, BindingCallback> bindings = new HashMap<>();
@@ -514,6 +515,28 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
});
}
@Override
public void routeWebSocket(String url, Consumer<WebSocketRoute> handler) {
routeWebSocketImpl(new UrlMatcher(baseUrl, url), handler);
}
@Override
public void routeWebSocket(Pattern pattern, Consumer<WebSocketRoute> handler) {
routeWebSocketImpl(new UrlMatcher(pattern), handler);
}
@Override
public void routeWebSocket(Predicate<String> predicate, Consumer<WebSocketRoute> handler) {
routeWebSocketImpl(new UrlMatcher(predicate), handler);
}
private void routeWebSocketImpl(UrlMatcher matcher, Consumer<WebSocketRoute> handler) {
withLogging("BrowserContext.routeWebSocket", () -> {
webSocketRoutes.add(matcher, handler);
updateWebSocketInterceptionPatterns();
});
}
void recordIntoHar(PageImpl page, Path har, RouteFromHAROptions options) {
JsonObject params = new JsonObject();
if (page != null) {
@@ -681,6 +704,10 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
sendMessage("setNetworkInterceptionPatterns", routes.interceptionPatterns());
}
private void updateWebSocketInterceptionPatterns() {
sendMessage("setWebSocketInterceptionPatterns", webSocketRoutes.interceptionPatterns());
}
void handleRoute(RouteImpl route) {
Router.HandleResult handled = routes.handle(route);
if (handled != Router.HandleResult.NoMatchingHandler) {
@@ -691,6 +718,12 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
}
}
void handleWebSocketRoute(WebSocketRouteImpl route) {
if (!webSocketRoutes.handle(route)) {
route.connectToServer();
}
}
WaitableResult<JsonElement> pause() {
return sendMessageAsync("pause", new JsonObject());
}
@@ -730,6 +763,9 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
RouteImpl route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString());
route.browserContext = this;
handleRoute(route);
} else if ("webSocketRoute".equals(event)) {
WebSocketRouteImpl route = connection.getExistingObject(params.getAsJsonObject("webSocketRoute").get("guid").getAsString());
handleWebSocketRoute(route);
} else if ("page".equals(event)) {
PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString());
pages.add(page);
@@ -35,6 +35,7 @@ class ChannelOwner extends LoggingSupport {
final String guid;
final JsonObject initializer;
private boolean wasCollected;
private boolean isInternalType;
protected ChannelOwner(ChannelOwner parent, String type, String guid, JsonObject initializer) {
this(parent.connection, parent, type, guid, initializer);
@@ -58,6 +59,10 @@ class ChannelOwner extends LoggingSupport {
}
}
void markAsInternalType() {
isInternalType = true;
}
void disposeChannelOwner(boolean wasGarbageCollected) {
// Clean up from parent and connection.
if (parent != null) {
@@ -84,6 +89,9 @@ class ChannelOwner extends LoggingSupport {
@Override
<T> T withLogging(String apiName, Supplier<T> code) {
if (isInternalType) {
apiName = null;
}
String previousApiName = connection.setApiName(apiName);
try {
return super.withLogging(apiName, code);
@@ -92,6 +100,10 @@ class ChannelOwner extends LoggingSupport {
}
}
WaitableResult<JsonElement> sendMessageAsync(String method) {
return sendMessageAsync(method, new JsonObject());
}
WaitableResult<JsonElement> sendMessageAsync(String method, JsonObject params) {
checkNotCollected();
return connection.sendMessageAsync(guid, method, params);
@@ -384,6 +384,9 @@ public class Connection {
case "WebSocket":
result = new WebSocketImpl(parent, type, guid, initializer);
break;
case "WebSocketRoute":
result = new WebSocketRouteImpl(parent, type, guid, initializer);
break;
case "Worker":
result = new WorkerImpl(parent, type, guid, initializer);
break;
@@ -17,6 +17,7 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonObject;
import com.microsoft.playwright.PlaywrightException;
import java.util.*;
import java.util.function.Consumer;
@@ -46,6 +47,9 @@ class ListenerCollection <EventType> {
}
void add(EventType type, Consumer<?> listener) {
if (listener == null) {
throw new PlaywrightException("Can't add a null listener");
}
List<Consumer<?>> list = listeners.get(type);
if (list == null) {
list = new ArrayList<>();
@@ -27,6 +27,7 @@ import static com.microsoft.playwright.impl.Serialization.gson;
class LocalUtils extends ChannelOwner {
LocalUtils(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
markAsInternalType();
}
JsonArray deviceDescriptors() {
@@ -48,6 +48,7 @@ public class PageImpl extends ChannelOwner implements Page {
final Waitable<?> waitableClosedOrCrashed;
private ViewportSize viewport;
private final Router routes = new Router();
private final WebSocketRouter webSocketRoutes = new WebSocketRouter();
private final Set<FrameImpl> frames = new LinkedHashSet<>();
private final Map<Integer, LocatorHandler> locatorHandlers = new HashMap<>();
@@ -212,6 +213,11 @@ public class PageImpl extends ChannelOwner implements Page {
if (handled == Router.HandleResult.NoMatchingHandler || handled == Router.HandleResult.Fallback) {
browserContext.handleRoute(route);
}
} else if ("webSocketRoute".equals(event)) {
WebSocketRouteImpl route = connection.getExistingObject(params.getAsJsonObject("webSocketRoute").get("guid").getAsString());
if (!webSocketRoutes.handle(route)) {
browserContext.handleWebSocketRoute(route);
}
} else if ("video".equals(event)) {
String artifactGuid = params.getAsJsonObject("artifact").get("guid").getAsString();
ArtifactImpl artifact = connection.getExistingObject(artifactGuid);
@@ -927,6 +933,11 @@ public class PageImpl extends ChannelOwner implements Page {
return null;
}
@Override
public void requestGC() {
withLogging("Page.requestGC", () -> sendMessage("requestGC"));
}
@Override
public ResponseImpl navigate(String url, NavigateOptions options) {
return withLogging("Page.navigate", () -> mainFrame.navigateImpl(url, convertType(options, Frame.NavigateOptions.class)));
@@ -1129,6 +1140,28 @@ public class PageImpl extends ChannelOwner implements Page {
});
}
@Override
public void routeWebSocket(String url, Consumer<WebSocketRoute> handler) {
routeWebSocketImpl(new UrlMatcher(browserContext.baseUrl, url), handler);
}
@Override
public void routeWebSocket(Pattern pattern, Consumer<WebSocketRoute> handler) {
routeWebSocketImpl(new UrlMatcher(pattern), handler);
}
@Override
public void routeWebSocket(Predicate<String> predicate, Consumer<WebSocketRoute> handler) {
routeWebSocketImpl(new UrlMatcher(predicate), handler);
}
private void routeWebSocketImpl(UrlMatcher matcher, Consumer<WebSocketRoute> handler) {
withLogging("Page.routeWebSocket", () -> {
webSocketRoutes.add(matcher, handler);
updateWebSocketInterceptionPatterns();
});
}
@Override
public byte[] screenshot(ScreenshotOptions options) {
return withLogging("Page.screenshot", () -> screenshotImpl(options));
@@ -1356,6 +1389,10 @@ public class PageImpl extends ChannelOwner implements Page {
sendMessage("setNetworkInterceptionPatterns", routes.interceptionPatterns());
}
private void updateWebSocketInterceptionPatterns() {
sendMessage("setWebSocketInterceptionPatterns", webSocketRoutes.interceptionPatterns());
}
@Override
public String url() {
return mainFrame.url();
@@ -38,6 +38,7 @@ public class RouteImpl extends ChannelOwner implements Route {
public RouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
markAsInternalType();
request = connection.getExistingObject(initializer.getAsJsonObject("request").get("guid").getAsString());
}
@@ -47,7 +48,6 @@ public class RouteImpl extends ChannelOwner implements Route {
withLogging("Route.abort", () -> {
JsonObject params = new JsonObject();
params.addProperty("errorCode", errorCode);
params.addProperty("requestUrl", request.initializer.get("url").getAsString());
sendMessageAsync("abort", params);
});
}
@@ -135,7 +135,6 @@ public class RouteImpl extends ChannelOwner implements Route {
params.addProperty("postData", base64);
}
}
params.addProperty("requestUrl", request.initializer.get("url").getAsString());
params.addProperty("isFallback", isFallback);
sendMessageAsync("continue", params);
}
@@ -231,7 +230,6 @@ public class RouteImpl extends ChannelOwner implements Route {
if (fetchResponseUid != null) {
params.addProperty("fetchResponseUid", fetchResponseUid);
}
params.addProperty("requestUrl", request.initializer.get("url").getAsString());
sendMessageAsync("fulfill", params);
}
@@ -23,6 +23,7 @@ import com.microsoft.playwright.Route;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -99,27 +100,7 @@ class Router {
}
JsonObject interceptionPatterns() {
JsonArray jsonPatterns = new JsonArray();
for (RouteInfo route : routes) {
JsonObject jsonPattern = new JsonObject();
Object urlFilter = route.matcher.rawSource;
if (urlFilter instanceof String) {
jsonPattern.addProperty("glob", (String) urlFilter);
} else if (urlFilter instanceof Pattern) {
Pattern pattern = (Pattern) urlFilter;
jsonPattern.addProperty("regexSource", pattern.pattern());
jsonPattern.addProperty("regexFlags", toJsRegexFlags(pattern));
} else {
// Match all requests.
jsonPattern.addProperty("glob", "**/*");
jsonPatterns = new JsonArray();
jsonPatterns.add(jsonPattern);
break;
}
jsonPatterns.add(jsonPattern);
}
JsonObject result = new JsonObject();
result.add("patterns", jsonPatterns);
return result;
List<UrlMatcher> matchers = routes.stream().map(r -> r.matcher).collect(Collectors.toList());
return Utils.interceptionPatterns(matchers);
}
}
@@ -33,6 +33,7 @@ class TracingImpl extends ChannelOwner implements Tracing {
TracingImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
markAsInternalType();
}
private void stopChunkImpl(Path path) {
@@ -16,6 +16,8 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.microsoft.playwright.PlaywrightException;
import java.net.MalformedURLException;
@@ -25,6 +27,7 @@ import java.util.function.Predicate;
import java.util.regex.Pattern;
import static com.microsoft.playwright.impl.Utils.globToRegex;
import static com.microsoft.playwright.impl.Utils.toJsRegexFlags;
class UrlMatcher {
final Object rawSource;
@@ -424,20 +424,17 @@ public class Utils {
JsonObject jsonCert = new JsonObject();
jsonCert.addProperty("origin", cert.origin);
try {
if (cert.certPath != null) {
byte[] bytes = readAllBytes(cert.certPath);
String base64 = Base64.getEncoder().encodeToString(bytes);
jsonCert.addProperty("cert", base64);
String certBase64 = base64Buffer(cert.cert, cert.certPath);
if (certBase64 != null) {
jsonCert.addProperty("cert", certBase64);
}
if (cert.keyPath != null) {
byte[] bytes = readAllBytes(cert.keyPath);
String base64 = Base64.getEncoder().encodeToString(bytes);
jsonCert.addProperty("key", base64);
String keyBase64 = base64Buffer(cert.key, cert.keyPath);
if (keyBase64 != null) {
jsonCert.addProperty("key", keyBase64);
}
if (cert.pfxPath != null) {
byte[] bytes = readAllBytes(cert.pfxPath);
String base64 = Base64.getEncoder().encodeToString(bytes);
params.addProperty("pfx", base64);
String pfxBase64 = base64Buffer(cert.pfx, cert.pfxPath);
if (pfxBase64 != null) {
params.addProperty("pfx", pfxBase64);
}
} catch (IOException e) {
throw new PlaywrightException("Failed to read from file", e);
@@ -450,4 +447,39 @@ public class Utils {
params.remove("clientCertificates");
params.add("clientCertificates", clientCertificates);
}
private static String base64Buffer(byte[] bytes, Path path) throws IOException {
if (path != null) {
bytes = readAllBytes(path);
}
if (bytes == null) {
return null;
}
return Base64.getEncoder().encodeToString(bytes);
}
static JsonObject interceptionPatterns(List<UrlMatcher> matchers) {
JsonArray jsonPatterns = new JsonArray();
for (UrlMatcher matcher: matchers) {
JsonObject jsonPattern = new JsonObject();
Object urlFilter = matcher.rawSource;
if (urlFilter instanceof String) {
jsonPattern.addProperty("glob", (String) urlFilter);
} else if (urlFilter instanceof Pattern) {
Pattern pattern = (Pattern) urlFilter;
jsonPattern.addProperty("regexSource", pattern.pattern());
jsonPattern.addProperty("regexFlags", toJsRegexFlags(pattern));
} else {
// Match all requests.
jsonPattern.addProperty("glob", "**/*");
jsonPatterns = new JsonArray();
jsonPatterns.add(jsonPattern);
break;
}
jsonPatterns.add(jsonPattern);
}
JsonObject result = new JsonObject();
result.add("patterns", jsonPatterns);
return result;
}
}
@@ -0,0 +1,29 @@
package com.microsoft.playwright.impl;
import com.microsoft.playwright.WebSocketFrame;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
class WebSocketFrameImpl implements WebSocketFrame {
private byte[] bytes;
private String text;
WebSocketFrameImpl(String payload, boolean isBase64) {
if (isBase64) {
bytes = Base64.getDecoder().decode(payload);
} else {
text = payload;
}
}
@Override
public byte[] binary() {
return bytes;
}
@Override
public String text() {
return text;
}
}
@@ -21,9 +21,7 @@ import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.WebSocket;
import com.microsoft.playwright.WebSocketFrame;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
@@ -151,28 +149,6 @@ class WebSocketImpl extends ChannelOwner implements WebSocket {
return runUntil(code, new WaitableRace<>(waitables));
}
private static class WebSocketFrameImpl implements WebSocketFrame {
private final byte[] bytes;
WebSocketFrameImpl(String payload, boolean isBase64) {
if (isBase64) {
bytes = Base64.getDecoder().decode(payload);
} else {
bytes = payload.getBytes();
}
}
@Override
public byte[] binary() {
return bytes;
}
@Override
public String text() {
return new String(bytes, StandardCharsets.UTF_8);
}
}
@Override
void handleEvent(String event, JsonObject parameters) {
switch (event) {
@@ -0,0 +1,186 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonObject;
import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.WebSocketFrame;
import com.microsoft.playwright.WebSocketRoute;
import java.util.Base64;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import static com.microsoft.playwright.impl.Serialization.gson;
class WebSocketRouteImpl extends ChannelOwner implements WebSocketRoute {
private Consumer<WebSocketFrame> onPageMessage;
private BiConsumer<Integer, String> onPageClose;
private Consumer<WebSocketFrame> onServerMessage;
private BiConsumer<Integer, String> onServerClose;
private boolean connected;
private WebSocketRoute server = new WebSocketRoute() {
@Override
public void close(CloseOptions options) {
if (options == null) {
options = new CloseOptions();
}
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
params.addProperty("wasClean", true);
sendMessageAsync("closeServer", params);
}
@Override
public WebSocketRoute connectToServer() {
throw new PlaywrightException("connectToServer must be called on the page-side WebSocketRoute");
}
@Override
public void onClose(BiConsumer<Integer, String> handler) {
onServerClose = handler;
}
@Override
public void onMessage(Consumer<WebSocketFrame> handler) {
onServerMessage = handler;
}
@Override
public void send(String message) {
JsonObject params = new JsonObject();
params.addProperty("message", message);
params.addProperty("isBase64", false);
sendMessageAsync("sendToServer", params);
}
@Override
public void send(byte[] message) {
JsonObject params = new JsonObject();
String base64 = Base64.getEncoder().encodeToString(message);
params.addProperty("message", base64);
params.addProperty("isBase64", true);
sendMessageAsync("sendToServer", params);
}
@Override
public String url() {
return initializer.get("url").getAsString();
}
};
WebSocketRouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
}
@Override
public void close(CloseOptions options) {
if (options == null) {
options = new CloseOptions();
}
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
params.addProperty("wasClean", true);
sendMessageAsync("closePage", params);
}
@Override
public WebSocketRoute connectToServer() {
if (connected) {
throw new PlaywrightException("Already connected to the server");
}
connected = true;
sendMessageAsync("connect");
return server;
}
@Override
public void onClose(BiConsumer<Integer, String> handler) {
onPageClose = handler;
}
@Override
public void onMessage(Consumer<WebSocketFrame> handler) {
onPageMessage = handler;
}
@Override
public void send(String message) {
JsonObject params = new JsonObject();
params.addProperty("message", message);
params.addProperty("isBase64", false);
sendMessageAsync("sendToPage", params);
}
@Override
public void send(byte[] message) {
JsonObject params = new JsonObject();
String base64 = Base64.getEncoder().encodeToString(message);
params.addProperty("message", base64);
params.addProperty("isBase64", true);
sendMessageAsync("sendToPage", params);
}
@Override
public String url() {
return initializer.get("url").getAsString();
}
void afterHandle() {
if (this.connected) {
return;
}
// Ensure that websocket is "open" and can send messages without an actual server connection.
sendMessageAsync("ensureOpened");
}
@Override
protected void handleEvent(String event, JsonObject params) {
if ("messageFromPage".equals(event)) {
String message = params.get("message").getAsString();
boolean isBase64 = params.get("isBase64").getAsBoolean();
if (onPageMessage != null) {
onPageMessage.accept(new WebSocketFrameImpl(message, isBase64));
} else if (connected) {
JsonObject messageParams = new JsonObject();
messageParams.addProperty("message", message);
messageParams.addProperty("isBase64", isBase64);
sendMessageAsync("sendToServer", messageParams);
}
} else if ("messageFromServer".equals(event)) {
String message = params.get("message").getAsString();
boolean isBase64 = params.get("isBase64").getAsBoolean();
if (onServerMessage != null) {
onServerMessage.accept(new WebSocketFrameImpl(message, isBase64));
} else {
JsonObject messageParams = new JsonObject();
messageParams.addProperty("message", message);
messageParams.addProperty("isBase64", isBase64);
sendMessageAsync("sendToPage", messageParams);
}
} else if ("closePage".equals(event)) {
int code = params.get("code").getAsInt();
String reason = params.get("reason").getAsString();
boolean wasClean = params.get("wasClean").getAsBoolean();
if (onPageClose != null) {
onPageClose.accept(code, reason);
} else {
JsonObject closeParams = new JsonObject();
closeParams.addProperty("code", code);
closeParams.addProperty("reason", reason);
closeParams.addProperty("wasClean", wasClean);
sendMessageAsync("closeServer", closeParams);
}
} else if ("closeServer".equals(event)) {
int code = params.get("code").getAsInt();
String reason = params.get("reason").getAsString();
boolean wasClean = params.get("wasClean").getAsBoolean();
if (onServerClose != null) {
onServerClose.accept(code, reason);
} else {
JsonObject closeParams = new JsonObject();
closeParams.addProperty("code", code);
closeParams.addProperty("reason", reason);
closeParams.addProperty("wasClean", wasClean);
sendMessageAsync("closePage", closeParams);
}
}
}
}
@@ -0,0 +1,47 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonObject;
import com.microsoft.playwright.WebSocketRoute;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class WebSocketRouter {
private List<RouteInfo> routes = new ArrayList<>();
private static class RouteInfo {
final UrlMatcher matcher;
private final Consumer<WebSocketRoute> handler;
RouteInfo(UrlMatcher matcher, Consumer<WebSocketRoute> handler) {
this.matcher = matcher;
this.handler = handler;
}
void handle(WebSocketRouteImpl route) {
handler.accept(route);
route.afterHandle();
}
}
void add(UrlMatcher matcher, Consumer<WebSocketRoute> handler) {
routes.add(0, new RouteInfo(matcher, handler));
}
boolean handle(WebSocketRouteImpl route) {
for (RouteInfo routeInfo: routes) {
if (routeInfo.matcher.test(route.url())) {
routeInfo.handle(route);
return true;
}
}
return false;
}
JsonObject interceptionPatterns() {
List<UrlMatcher> matchers = routes.stream().map(r -> r.matcher).collect(Collectors.toList());
return Utils.interceptionPatterns(matchers);
}
}
@@ -16,28 +16,22 @@
package com.microsoft.playwright.impl.junit;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.*;
import com.microsoft.playwright.impl.Utils;
import com.microsoft.playwright.junit.Options;
import org.junit.jupiter.api.extension.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.microsoft.playwright.impl.junit.ExtensionUtils.*;
import static com.microsoft.playwright.impl.junit.PageExtension.cleanUpPage;
public class BrowserContextExtension implements ParameterResolver, AfterEachCallback {
public class BrowserContextExtension implements ParameterResolver, TestWatcher {
private static final ThreadLocal<BrowserContext> threadLocalBrowserContext = new ThreadLocal<>();
@Override
public void afterEach(ExtensionContext extensionContext) {
BrowserContext browserContext = threadLocalBrowserContext.get();
threadLocalBrowserContext.remove();
if (browserContext != null) {
browserContext.close();
}
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return !isClassHook(extensionContext) && isParameterSupported(parameterContext, extensionContext, BrowserContext.class);
@@ -51,6 +45,7 @@ public class BrowserContextExtension implements ParameterResolver, AfterEachCall
/**
* Returns the BrowserContext that belongs to the current test. Will be created if it doesn't already exist.
* <strong>NOTE:</strong> this method is subject to change.
*
* @param extensionContext the context in which the current test or container is being executed.
* @return The BrowserContext that belongs to the current test.
*/
@@ -66,10 +61,97 @@ public class BrowserContextExtension implements ParameterResolver, AfterEachCall
Browser browser = BrowserExtension.getOrCreateBrowser(extensionContext);
Browser.NewContextOptions contextOptions = getContextOptions(playwright, options);
browserContext = browser.newContext(contextOptions);
if (shouldRecordTrace(options)) {
Tracing.StartOptions startOptions = new Tracing.StartOptions().setSnapshots(true).setScreenshots(true).setTitle(extensionContext.getDisplayName());
if (System.getenv("PLAYWRIGHT_JAVA_SRC") != null) {
startOptions.setSources(true);
}
browserContext.tracing().start(startOptions);
}
threadLocalBrowserContext.set(browserContext);
return browserContext;
}
@Override
public void testSuccessful(ExtensionContext extensionContext) {
saveTraceWhenOn(extensionContext);
closeBrowserContext();
}
@Override
public void testAborted(ExtensionContext extensionContext, Throwable cause) {
saveTraceWhenOn(extensionContext);
closeBrowserContext();
}
@Override
public void testFailed(ExtensionContext extensionContext, Throwable cause) {
Options options = OptionsExtension.getOptions(extensionContext);
if (shouldRecordTrace(options)) {
saveTrace(extensionContext);
}
closeBrowserContext();
}
private static void saveTraceWhenOn(ExtensionContext extensionContext) {
Options options = OptionsExtension.getOptions(extensionContext);
if (options.trace.equals(Options.Trace.ON)) {
saveTrace(extensionContext);
}
}
private static void saveTrace(ExtensionContext extensionContext) {
BrowserContext browserContext = threadLocalBrowserContext.get();
if (browserContext == null) {
return;
}
Path outputPath = getOutputPath(extensionContext);
createOutputPath(outputPath);
Tracing.StopOptions stopOptions = new Tracing.StopOptions().setPath(outputPath.resolve("trace.zip"));
browserContext.tracing().stop(stopOptions);
}
private static void createOutputPath(Path outputPath) {
if (!Files.exists(outputPath)) {
try {
Files.createDirectories(outputPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private static Path getOutputPath(ExtensionContext extensionContext) {
BrowserType browserType = BrowserExtension.getBrowser().browserType();
Path defaultOutputPath = getDefaultOutputPath(extensionContext);
String outputDirName = extensionContext.getRequiredTestClass().getName() + "." +
extensionContext.getRequiredTestMethod().getName() + "-" +
browserType.name();
return defaultOutputPath.resolve(outputDirName);
}
private static Path getDefaultOutputPath(ExtensionContext extensionContext) {
Options options = OptionsExtension.getOptions(extensionContext);
Path outputPath = options.outputDir;
if (outputPath == null) {
outputPath = Paths.get(System.getProperty("user.dir")).resolve("test-results");
}
return outputPath;
}
private void closeBrowserContext() {
cleanUpPage();
BrowserContext browserContext = threadLocalBrowserContext.get();
threadLocalBrowserContext.remove();
if (browserContext != null) {
browserContext.close();
}
}
private static boolean shouldRecordTrace(Options options) {
return options.trace.equals(Options.Trace.ON) || options.trace.equals(Options.Trace.RETAIN_ON_FAILURE);
}
private static Browser.NewContextOptions getContextOptions(Playwright playwright, Options options) {
Browser.NewContextOptions contextOptions = Utils.clone(options.contextOptions);
if (contextOptions == null) {
@@ -94,7 +176,7 @@ public class BrowserContextExtension implements ParameterResolver, AfterEachCall
contextOptions.hasTouch = deviceDescriptor.hasTouch;
}
if(options.ignoreHTTPSErrors != null) {
if (options.ignoreHTTPSErrors != null) {
contextOptions.setIgnoreHTTPSErrors(options.ignoreHTTPSErrors);
}
@@ -86,6 +86,10 @@ public class BrowserExtension implements ParameterResolver, AfterAllCallback {
return browser;
}
static Browser getBrowser() {
return threadLocalBrowser.get();
}
private static BrowserType.ConnectOptions getConnectOptions(Options options) {
BrowserType.ConnectOptions connectOptions = options.connectOptions;
if(connectOptions == null) {
@@ -22,17 +22,8 @@ import org.junit.jupiter.api.extension.*;
import static com.microsoft.playwright.impl.junit.ExtensionUtils.*;
public class PageExtension implements ParameterResolver, AfterEachCallback {
private static final ThreadLocal<Page> threadLocalPage = new ThreadLocal<>();
@Override
public void afterEach(ExtensionContext extensionContext) {
Page page = threadLocalPage.get();
threadLocalPage.remove();
if (page != null) {
page.close();
}
}
public class PageExtension implements ParameterResolver {
private static final ThreadLocal<Page> threadLocalPage = new ThreadLocal<>();
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
@@ -47,6 +38,7 @@ public class PageExtension implements ParameterResolver, AfterEachCallback {
/**
* Returns the Page that belongs to the current test. Will be created if it doesn't already exist.
* <strong>NOTE:</strong> this method is subject to change.
*
* @param extensionContext the context in which the current test or container is being executed.
* @return The Page that belongs to the current test.
*/
@@ -61,4 +53,8 @@ public class PageExtension implements ParameterResolver, AfterEachCallback {
threadLocalPage.set(page);
return page;
}
static void cleanUpPage() {
threadLocalPage.remove();
}
}
@@ -16,10 +16,9 @@
package com.microsoft.playwright.junit;
import com.microsoft.playwright.APIRequest;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.*;
import java.nio.file.Path;
/**
* <strong>NOTE:</strong> this API is experimental and is subject to changes.
@@ -47,6 +46,26 @@ public class Options {
// If this is set, BrowserType.connect will be used. Otherwise, BrowserType.launch will be used.
public String wsEndpoint;
public BrowserType.ConnectOptions connectOptions;
// The dir where test artifacts will be stored
public Path outputDir;
// When to record traces. Default is OFF.
public Trace trace = Trace.OFF;
public enum Trace {
OFF,
ON,
RETAIN_ON_FAILURE;
}
public Options setTrace(Trace trace) {
this.trace = trace;
return this;
}
public Options setOutputDir(Path outputDir) {
this.outputDir = outputDir;
return this;
}
public Options setWsEndpoint(String wsEndpoint) {
this.wsEndpoint = wsEndpoint;
@@ -28,14 +28,26 @@ public class ClientCertificate {
* Path to the file with the certificate in PEM format.
*/
public Path certPath;
/**
* Direct value of the certificate in PEM format.
*/
public byte[] cert;
/**
* Path to the file with the private key in PEM format.
*/
public Path keyPath;
/**
* Direct value of the private key in PEM format.
*/
public byte[] key;
/**
* Path to the PFX or PKCS12 encoded private key and certificate chain.
*/
public Path pfxPath;
/**
* Direct value of the PFX or PKCS12 encoded private key and certificate chain.
*/
public byte[] pfx;
/**
* Passphrase for the private key (PEM or PFX).
*/
@@ -51,6 +63,13 @@ public class ClientCertificate {
this.certPath = certPath;
return this;
}
/**
* Direct value of the certificate in PEM format.
*/
public ClientCertificate setCert(byte[] cert) {
this.cert = cert;
return this;
}
/**
* Path to the file with the private key in PEM format.
*/
@@ -58,6 +77,13 @@ public class ClientCertificate {
this.keyPath = keyPath;
return this;
}
/**
* Direct value of the private key in PEM format.
*/
public ClientCertificate setKey(byte[] key) {
this.key = key;
return this;
}
/**
* Path to the PFX or PKCS12 encoded private key and certificate chain.
*/
@@ -65,6 +91,13 @@ public class ClientCertificate {
this.pfxPath = pfxPath;
return this;
}
/**
* Direct value of the PFX or PKCS12 encoded private key and certificate chain.
*/
public ClientCertificate setPfx(byte[] pfx) {
this.pfx = pfx;
return this;
}
/**
* Passphrase for the private key (PEM or PFX).
*/
@@ -43,8 +43,8 @@ class HttpsConfiguratorImpl extends HttpsConfigurator {
public void configure(HttpsParameters params) {
SSLContext sslContext = getSSLContext();
SSLParameters sslParams = sslContext.getDefaultSSLParameters();
sslParams.setNeedClientAuth(true);
params.setNeedClientAuth(true);
sslParams.setWantClientAuth(true);
params.setWantClientAuth(true);
params.setSSLParameters(sslParams);
}
@@ -136,8 +136,8 @@ public class ServerWithClientCertificate implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
SSLSession sslSession = ((HttpsExchange) exchange).getSSLSession();
String response = div("servername", sslSession.getPeerHost());
Certificate[] certs = sslSession.getPeerCertificates();
if (certs.length > 0 && certs[0] instanceof X509Certificate) {
try {
Certificate[] certs = sslSession.getPeerCertificates();
X509Certificate cert = (X509Certificate) certs[0];
exchange.getResponseHeaders().add("Content-Type", "text/html");
if (validateCertChain(certs)) {
@@ -149,7 +149,7 @@ public class ServerWithClientCertificate implements HttpHandler {
cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName()));
exchange.sendResponseHeaders(403, 0);
}
} else {
} catch (SSLPeerUnverifiedException e) {
response += div("message", "Sorry, but you need to provide a client certificate to continue.");
exchange.sendResponseHeaders(401, 0);
}
@@ -132,7 +132,7 @@ public class TestBrowserContextFetch extends TestBase {
context.request().get(server.EMPTY_PAGE + "?p1=foo",
RequestOptions.create().setQueryParam("p1", "v1").setQueryParam("парам2", "знач2"));
assertNotNull(req.get());
assertEquals("/empty.html?p1=v1&%D0%BF%D0%B0%D1%80%D0%B0%D0%BC2=%D0%B7%D0%BD%D0%B0%D1%872", req.get().url);
assertEquals("/empty.html?p1=foo&p1=v1&%D0%BF%D0%B0%D1%80%D0%B0%D0%BC2=%D0%B7%D0%BD%D0%B0%D1%872", req.get().url);
}
;
@@ -218,7 +218,7 @@ public class TestBrowserContextFetch extends TestBase {
writer.write("<title>Served by the proxy</title>");
}
});
try (Browser browser = browserType.launch(new BrowserType.LaunchOptions().setProxy("http://per-context"))) {
try (Browser browser = browserType.launch()) {
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setProxy("localhost:" + server.PORT));
Future<Server.Request> request = server.futureRequest("/target.html");
APIResponse response = context.request().get("http://non-existent.com/target.html");
@@ -29,31 +29,6 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class TestBrowserContextProxy extends TestBase {
@Override
@BeforeAll
// Hide base class method to provide extra option.
void launchBrowser() {
BrowserType.LaunchOptions options = createLaunchOptions();
options.setProxy(new Proxy("per-context"));
launchBrowser(options);
}
static boolean isChromiumWindows() {
return isChromium() && isWindows;
}
@Test
@EnabledIf(value="isChromiumWindows", disabledReason="Platform-specific")
void shouldThrowForMissingGlobalProxyOnChromiumWindows() {
try (Browser browser = browserType.launch(createLaunchOptions())) {
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
browser.newContext(new Browser.NewContextOptions().setProxy("localhost:" + server.PORT));
});
assertTrue(e.getMessage().contains("Browser needs to be launched with the global proxy"));
}
}
void shouldThrowForBadServerValue() {
// Enforced by compiler in Java
}
@@ -16,6 +16,7 @@ import java.nio.file.Paths;
import static com.microsoft.playwright.Utils.nextFreePort;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import static java.nio.file.Files.readAllBytes;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.*;
@@ -56,19 +57,12 @@ public class TestClientCertificates extends TestBase {
super.stopServer();
}
@BeforeAll
@Override
void launchBrowser() {
// TODO: remove once Chromium Stable tests pass without it on Windows.
launchBrowser(createLaunchOptions().setProxy(new Proxy("per-context")));
}
@Test
public void shouldFailWithNoClientCertificatesProvided() {
APIRequestContext request = playwright.request().newContext(
new APIRequest.NewContextOptions().setIgnoreHTTPSErrors(true));
PlaywrightException e = assertThrows(PlaywrightException.class, () -> request.get(customServer.url));
assertTrue(e.getMessage().contains("Error: socket hang up"), e.getMessage());
APIResponse response = request.get(customServer.url);
assertTrue(response.text().contains("Sorry, but you need to provide a client certificate to continue."), response.text());
request.dispose();
}
@@ -142,8 +136,14 @@ public class TestClientCertificates extends TestBase {
try (BrowserContext context = browser.newContext(options)) {
Page page = context.newPage();
assertThrows(PlaywrightException.class, () -> page.navigate(customServer.crossOrigin));
assertThrows(PlaywrightException.class, () -> page.request().get(customServer.crossOrigin));
{
APIResponse response = page.request().get(customServer.crossOrigin);
assertTrue(response.text().contains("Sorry, but you need to provide a client certificate to continue."), response.text());
}
{
page.navigate(customServer.crossOrigin);
assertThat(page.getByTestId("message")).hasText("Sorry, but you need to provide a client certificate to continue.");
}
page.navigate(customServer.url);
assertThat(page.getByText("Hello CN=Alice")).isVisible();
APIResponse response = page.request().get(customServer.url);
@@ -162,8 +162,40 @@ public class TestClientCertificates extends TestBase {
.setKeyPath(asset("client-certificates/client/trusted/key.pem"))));
try (Page page = browser.newPage(options)) {
assertThrows(PlaywrightException.class, () -> page.navigate(customServer.crossOrigin));
assertThrows(PlaywrightException.class, () -> page.request().get(customServer.crossOrigin));
{
page.navigate(customServer.crossOrigin);
assertThat(page.getByTestId("message")).hasText("Sorry, but you need to provide a client certificate to continue.");
}
{
APIResponse response = page.request().get(customServer.crossOrigin);
assertTrue(response.text().contains("Sorry, but you need to provide a client certificate to continue."), response.text());
}
page.navigate(customServer.url);
assertThat(page.getByText("Hello CN=Alice")).isVisible();
APIResponse response = page.request().get(customServer.url);
assertTrue(response.text().contains("Hello CN=Alice"), response.text());
}
}
@Test
@DisabledIf(value="com.microsoft.playwright.TestClientCertificates#isWebKitMacOS", disabledReason="The network connection was lost.")
public void shouldWorkWithBrowserNewPageWhenPassingAsContent() throws IOException {
Browser.NewPageOptions options = new Browser.NewPageOptions()
.setIgnoreHTTPSErrors(true) // TODO: remove once we can pass a custom CA.
.setClientCertificates(asList(
new ClientCertificate(customServer.origin)
.setCert(readAllBytes(asset("client-certificates/client/trusted/cert.pem")))
.setKey(readAllBytes(asset("client-certificates/client/trusted/key.pem")))));
try (Page page = browser.newPage(options)) {
{
page.navigate(customServer.crossOrigin);
assertThat(page.getByTestId("message")).hasText("Sorry, but you need to provide a client certificate to continue.");
}
{
APIResponse response = page.request().get(customServer.crossOrigin);
assertTrue(response.text().contains("Sorry, but you need to provide a client certificate to continue."), response.text());
}
page.navigate(customServer.url);
assertThat(page.getByText("Hello CN=Alice")).isVisible();
APIResponse response = page.request().get(customServer.url);
@@ -183,8 +215,14 @@ public class TestClientCertificates extends TestBase {
try (BrowserContext context = browser.browserType().launchPersistentContext(tmpDir.resolve("profile") , options)) {
Page page = context.pages().get(0);
assertThrows(PlaywrightException.class, () -> page.navigate(customServer.crossOrigin));
assertThrows(PlaywrightException.class, () -> page.request().get(customServer.crossOrigin));
{
page.navigate(customServer.crossOrigin);
assertThat(page.getByTestId("message")).hasText("Sorry, but you need to provide a client certificate to continue.");
}
{
APIResponse response = page.request().get(customServer.crossOrigin);
assertTrue(response.text().contains("Sorry, but you need to provide a client certificate to continue."), response.text());
}
page.navigate(customServer.url);
assertThat(page.getByText("Hello CN=Alice")).isVisible();
APIResponse response = page.request().get(customServer.url);
@@ -168,35 +168,6 @@ public class TestDefaultBrowserContext2 extends TestBase {
browserContext3.close();
}
@Test
void shouldRestoreCookiesFromUserDataDir() throws IOException {
// TODO: test.flaky(browserName === "chromium");
Path userDataDir = tempDir.resolve("user-data-dir");
BrowserType.LaunchPersistentContextOptions browserOptions = null;
BrowserContext browserContext = browserType.launchPersistentContext(userDataDir, browserOptions);
Page page = browserContext.newPage();
page.navigate(server.EMPTY_PAGE);
Object documentCookie = page.evaluate("() => {\n" +
" document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT';\n" +
" return document.cookie;\n" +
" }");
assertEquals("doSomethingOnlyOnce=true", documentCookie);
browserContext.close();
BrowserContext browserContext2 = browserType.launchPersistentContext(userDataDir, browserOptions);
Page page2 = browserContext2.newPage();
page2.navigate(server.EMPTY_PAGE);
assertEquals("doSomethingOnlyOnce=true", page2.evaluate("() => document.cookie"));
browserContext2.close();
Path userDataDir2 = tempDir.resolve("user-data-dir-2");
BrowserContext browserContext3 = browserType.launchPersistentContext(userDataDir2, browserOptions);
Page page3 = browserContext3.newPage();
page3.navigate(server.EMPTY_PAGE);
assertNotEquals("doSomethingOnlyOnce=true", page3.evaluate("() => document.cookie"));
browserContext3.close();
}
@Test
void shouldHaveDefaultURLWhenLaunchingBrowser() {
launchPersistent();
@@ -104,7 +104,7 @@ public class TestLocatorFrame extends TestBase {
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
page.frameLocator("iframe").locator("span").click(new Locator.ClickOptions().setTimeout(300));
});
assertTrue(e.getMessage().contains("waiting for frameLocator(\"iframe\")"), e.getMessage());
assertTrue(e.getMessage().contains("waiting for locator(\"iframe\").contentFrame()"), e.getMessage());
}
@Test
@@ -44,7 +44,7 @@ public class TestOptionsFactories {
return headfulEnv != null && !"0".equals(headfulEnv) && !"false".equals(headfulEnv);
}
private static String getBrowserName() {
public static String getBrowserName() {
String browserName = System.getenv("BROWSER");
if (browserName == null) {
browserName = "chromium";
@@ -347,4 +347,13 @@ public class TestPageBasic extends TestBase {
}));
assertTrue(e.getMessage().contains("The reason."), e.getMessage());
}
@Test
void shouldProhibitNullListeners() {
Page newPage = context.newPage();
PlaywrightException e = assertThrows(PlaywrightException.class, () -> newPage.onClose(null));
assertTrue(e.getMessage().contains("Can't add a null listener"));
}
}
@@ -81,7 +81,6 @@ public class TestPageInterception extends TestBase {
void shouldFulfillInterceptedResponseUsingAlias() {
page.route("**/*", route -> {
APIResponse response = route.fetch();
System.out.println(response.headers().get("content-type"));
route.fulfill(new Route.FulfillOptions().setResponse(response));
});
Response response = page.navigate(server.PREFIX + "/empty.html");
@@ -35,7 +35,6 @@ import static org.junit.jupiter.api.Assertions.*;
public class TestPlaywrightCreate {
@Test
void shouldSupportEnvSkipBrowserDownload(@TempDir Path browsersDir) throws IOException, NoSuchFieldException, IllegalAccessException {
System.err.println("shouldSupportEnvSkipBrowserDownload PLAYWRIGHT_BROWSERS_PATH = " + browsersDir);
Map<String, String> env = mapOf("PLAYWRIGHT_BROWSERS_PATH", browsersDir.toString(),
"PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "1");
Playwright.CreateOptions options = new Playwright.CreateOptions().setEnv(env);
@@ -0,0 +1,33 @@
package com.microsoft.playwright;
import com.microsoft.playwright.junit.FixtureTest;
import com.microsoft.playwright.junit.UsePlaywright;
import org.junit.jupiter.api.Test;
import static com.microsoft.playwright.Utils.mapOf;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@FixtureTest
@UsePlaywright(TestOptionsFactories.BasicOptionsFactory.class)
public class TestRequestGC {
@Test
void shouldWork(Page page) {
page.evaluate("() => {\n" +
" globalThis.objectToDestroy = { hello: 'world' };\n" +
" globalThis.weakRef = new WeakRef(globalThis.objectToDestroy);\n" +
" }");
page.requestGC();
assertEquals(mapOf("hello", "world"), page.evaluate("() => globalThis.weakRef.deref()"));
page.requestGC();
assertEquals(mapOf("hello", "world"), page.evaluate("() => globalThis.weakRef.deref()"));
page.evaluate("() => globalThis.objectToDestroy = null");
page.requestGC();
assertNull(page.evaluate("() => globalThis.weakRef.deref()"));
}
}
@@ -0,0 +1,320 @@
package com.microsoft.playwright;
import com.microsoft.playwright.junit.FixtureTest;
import com.microsoft.playwright.junit.UsePlaywright;
import org.java_websocket.WebSocket;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
import static com.microsoft.playwright.Utils.mapOf;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
@FixtureTest
@UsePlaywright(TestOptionsFactories.BasicOptionsFactory.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class TestRouteWebSocket {
private WebSocketServerImpl webSocketServer;
@BeforeAll
void startWebSockerServer() throws InterruptedException {
webSocketServer = WebSocketServerImpl.create();
}
@AfterAll
void stopWebSockerServer() throws IOException, InterruptedException {
webSocketServer.stop();
}
@AfterEach
void resetWebSocketServer() {
webSocketServer.reset();
}
private void setupWS(Page target, int port, String binaryType) {
setupWS(target.mainFrame(), port, binaryType);
}
private void setupWS(Frame target, int port, String binaryType) {
target.navigate("about:blank");
target.evaluate("({ port, binaryType }) => {\n" +
" window.log = [];\n" +
" window.ws = new WebSocket('ws://localhost:' + port + '/ws');\n" +
" window.ws.binaryType = binaryType;\n" +
" window.ws.addEventListener('open', () => window.log.push('open'));\n" +
" window.ws.addEventListener('close', event => window.log.push(`close code=${event.code} reason=${event.reason}`));\n" +
" window.ws.addEventListener('error', event => window.log.push(`error`));\n" +
" window.ws.addEventListener('message', async event => {\n" +
" let data;\n" +
" if (typeof event.data === 'string')\n" +
" data = event.data;\n" +
" else if (event.data instanceof Blob)\n" +
" data = 'blob:' + await event.data.text();\n" +
" else\n" +
" data = 'arraybuffer:' + await (new Blob([event.data])).text();\n" +
" window.log.push(`message: data=${data} origin=${event.origin} lastEventId=${event.lastEventId}`);\n" +
" });\n" +
" window.wsOpened = new Promise(f => window.ws.addEventListener('open', () => f()));\n" +
" }", mapOf("port", port, "binaryType", binaryType));
}
private void setupRoute(Page page, String mock) {
if ("no-match".equals(mock)) {
page.routeWebSocket(Pattern.compile("/zzz/"), ws -> {});
} else if ("pass-through".equals(mock)) {
page.routeWebSocket(Pattern.compile("/.*/"), ws -> {
WebSocketRoute server = ws.connectToServer();
ws.onMessage(message -> {
if (message.text() != null) {
server.send(message.text());
} else {
server.send(message.binary());
}
});
server.onMessage(message -> {
if (message.text() != null) {
ws.send(message.text());
} else {
ws.send(message.binary());
}
});
});
}
}
@ParameterizedTest
@ValueSource(strings = {"no-mock", "no-match", "pass-through"})
public void shouldWorkWithTextMessage(String mock, Page page) throws Exception {
setupRoute(page, mock);
Future<WebSocket> wsPromise = webSocketServer.waitForWebSocket();
setupWS(page, webSocketServer.getPort(), "blob");
page.waitForCondition(() -> {
Boolean result = (Boolean) page.evaluate("() => window.log.length >= 1");
return result;
});
assertEquals(asList("open"), page.evaluate("window.log"));
org.java_websocket.WebSocket ws = wsPromise.get();
ws.send("hello");
page.waitForCondition(() -> {
Boolean result = (Boolean) page.evaluate("() => window.log.length >= 2");
return result;
});
assertEquals(
asList("open", "message: data=hello origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId="),
page.evaluate("window.log"));
assertEquals(1, page.evaluate("window.ws.readyState"));
Future<String> messagePromise = webSocketServer.waitForMessage();
page.evaluate("() => window.ws.send('hi')");
assertEquals("hi", messagePromise.get());
ws.close(1008, "oops");
page.waitForCondition(() -> {
Integer result = (Integer) page.evaluate("window.ws.readyState");
return result == 3;
});
assertEquals(
asList("open", "message: data=hello origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"close code=1008 reason=oops"),
page.evaluate("window.log"));
}
@ParameterizedTest
@ValueSource(strings = {"no-mock", "no-match", "pass-through"})
public void shouldWorkWithBinaryTypeBlob(String mock, Page page) throws Exception {
setupRoute(page, mock);
Future<WebSocket> wsPromise = webSocketServer.waitForWebSocket();
setupWS(page, webSocketServer.getPort(), "blob");
org.java_websocket.WebSocket ws = wsPromise.get();
ws.send("hi".getBytes(StandardCharsets.UTF_8));
page.waitForCondition(() -> {
Boolean result = (Boolean) page.evaluate("() => window.log.length >= 2");
return result;
});
assertEquals(
asList("open", "message: data=blob:hi origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId="),
page.evaluate("window.log"));
Future<String> messagePromise = webSocketServer.waitForMessage();
page.evaluate("() => window.ws.send(new Blob([new Uint8Array(['h'.charCodeAt(0), 'i'.charCodeAt(0)])]))");
// Dispatch messages until web socket route is received.
page.waitForCondition(() -> messagePromise.isDone());
assertEquals("hi", messagePromise.get());
}
@ParameterizedTest
@ValueSource(strings = {"no-mock", "no-match", "pass-through"})
public void shouldWorkWithBinaryTypeArrayBuffer(String mock, Page page) throws Exception {
setupRoute(page, mock);
Future<WebSocket> wsPromise = webSocketServer.waitForWebSocket();
setupWS(page, webSocketServer.getPort(), "arraybuffer");
org.java_websocket.WebSocket ws = wsPromise.get();
ws.send("hi".getBytes(StandardCharsets.UTF_8));
page.waitForCondition(() -> {
Boolean result = (Boolean) page.evaluate("() => window.log.length >= 2");
return result;
});
assertEquals(
asList("open", "message: data=arraybuffer:hi origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId="),
page.evaluate("window.log"));
Future<String> messagePromise = webSocketServer.waitForMessage();
page.evaluate("() => window.ws.send(new Blob([new Uint8Array(['h'.charCodeAt(0), 'i'.charCodeAt(0)])]))");
// Dispatch messages until web socket route is received.
page.waitForCondition(() -> messagePromise.isDone());
assertEquals("hi", messagePromise.get());
}
@Test
public void shouldWorkWithServer(Page page) throws ExecutionException, InterruptedException {
WebSocketRoute[] wsRoute = new WebSocketRoute[]{null};
page.routeWebSocket(Pattern.compile("/.*/"), ws -> {
WebSocketRoute server = ws.connectToServer();
ws.onMessage(frame -> {
String message = frame.text();
switch (message) {
case "to-respond":
ws.send("response");
break;
case "to-block":
break;
case "to-modify":
server.send("modified");
break;
default:
server.send(message);
}
});
server.onMessage(frame -> {
String message = frame.text();
switch (message) {
case "to-block":
break;
case "to-modify":
ws.send("modified");
break;
default:
ws.send(message);
}
});
server.send("fake");
wsRoute[0] = ws;
});
Future<WebSocket> ws = webSocketServer.waitForWebSocket();
setupWS(page, webSocketServer.getPort(), "blob");
page.waitForCondition(() -> webSocketServer.logCopy().size() >= 1);
assertEquals(
asList("message: fake"),
webSocketServer.logCopy());
ws.get().send("to-modify");
ws.get().send("to-block");
ws.get().send("pass-server");
page.waitForCondition(() -> (Boolean) page.evaluate("() => window.log.length >= 3"));
assertEquals(
asList(
"open",
"message: data=modified origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=pass-server origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId="),
page.evaluate("window.log"));
page.evaluate("async () => {\n" +
" window.ws.send('to-respond');\n" +
" window.ws.send('to-modify');\n" +
" window.ws.send('to-block');\n" +
" window.ws.send('pass-client');\n" +
" }");
page.waitForCondition(() -> webSocketServer.logCopy().size() >= 3);
assertEquals(
asList("message: fake", "message: modified", "message: pass-client"),
webSocketServer.logCopy());
page.waitForCondition(() -> (Boolean) page.evaluate("() => window.log.length >= 4"));
assertEquals(
asList(
"open",
"message: data=modified origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=pass-server origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=response origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId="),
page.evaluate("window.log"));
wsRoute[0].send("another");
page.waitForCondition(() -> (Boolean) page.evaluate("() => window.log.length >= 5"));
assertEquals(
asList(
"open",
"message: data=modified origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=pass-server origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=response origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=another origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId="),
page.evaluate("window.log"));
page.evaluate("window.ws.send('pass-client-2');");
page.waitForCondition(() -> webSocketServer.logCopy().size() >= 4);
assertEquals(
asList("message: fake", "message: modified", "message: pass-client", "message: pass-client-2"),
webSocketServer.logCopy());
page.evaluate("window.ws.close(3009, 'problem');");
page.waitForCondition(() -> webSocketServer.logCopy().size() >= 5);
assertEquals(
asList("message: fake", "message: modified", "message: pass-client", "message: pass-client-2", "close: code=3009 reason=problem"),
webSocketServer.logCopy());
}
@Test
public void shouldWorkWithoutServer(Page page) {
WebSocketRoute[] wsRoute = new WebSocketRoute[]{ null };
page.routeWebSocket(Pattern.compile("/.*/"), ws -> {
ws.onMessage(frame -> {
String message = frame.text();
if ("to-respond".equals(message)) {
ws.send("response");
}
});
wsRoute[0] = ws;
});
setupWS(page, webSocketServer.getPort(), "blob");
page.evaluate("async () => {\n" +
" await window.wsOpened;\n" +
" window.ws.send('to-respond');\n" +
" window.ws.send('to-block');\n" +
" window.ws.send('to-respond');\n" +
" }");
page.waitForCondition(() -> (Boolean) page.evaluate("() => window.log.length >= 3"));
assertEquals(
asList(
"open",
"message: data=response origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=response origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId="),
page.evaluate("window.log"));
wsRoute[0].send("another");
wsRoute[0].close(new WebSocketRoute.CloseOptions().setCode(3008).setReason("oops"));
page.waitForCondition(() -> (Boolean) page.evaluate("() => window.log.length >= 5"));
assertEquals(
asList(
"open",
"message: data=response origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=response origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"message: data=another origin=ws://localhost:" + webSocketServer.getPort() + " lastEventId=",
"close code=3008 reason=oops"),
page.evaluate("window.log"));
}
}
@@ -35,6 +35,7 @@ public class TestWorkers extends TestBase {
}
@Test
@DisabledIf(value="com.microsoft.playwright.TestBase#isChromium", disabledReason="Started failing since last driver roll, flaky upstream")
void pageWorkers() {
Worker worker = page.waitForWorker(() -> page.navigate(server.PREFIX + "/worker/worker.html"));
assertTrue(worker.url().contains("worker.js"));
@@ -150,6 +151,7 @@ public class TestWorkers extends TestBase {
}
@Test
@DisabledIf(value="com.microsoft.playwright.TestBase#isChromium", disabledReason="Started failing since last driver roll, flaky upstream")
void shouldReportNetworkActivity() {
Assumptions.assumeFalse(isFirefox() && browserMajorVersion() < 114);
Worker worker = page.waitForWorker(() -> page.navigate(server.PREFIX + "/worker/worker.html"));
@@ -21,15 +21,25 @@ import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import static com.microsoft.playwright.Utils.nextFreePort;
class WebSocketServerImpl extends WebSocketServer implements AutoCloseable {
volatile ClientHandshake lastClientHandshake;
private volatile CompletableFuture<WebSocket> futureWebSocket;
private volatile CompletableFuture<String> futureMessage;
private final Semaphore startSemaphore = new Semaphore(0);
private List<String> log = new ArrayList<>();
static WebSocketServerImpl create() throws InterruptedException {
// FIXME: WebSocketServer.stop() doesn't release socket immediately and starting another server
// fails with "Address already in use", so we just allocate new port.
@@ -44,6 +54,40 @@ class WebSocketServerImpl extends WebSocketServer implements AutoCloseable {
super(address, 1);
}
synchronized void reset() {
futureMessage = null;
futureWebSocket = null;
synchronized (log) {
log.clear();
}
}
Future<org.java_websocket.WebSocket> waitForWebSocket() {
if (futureWebSocket == null) {
futureWebSocket = new CompletableFuture<>();
}
return futureWebSocket;
}
Future<String> waitForMessage() {
if (futureMessage == null) {
futureMessage = new CompletableFuture<>();
}
return futureMessage;
}
List<String> logCopy() {
synchronized (log) {
return new ArrayList<>(log);
}
}
private void addLog(String line) {
synchronized (log) {
log.add(line);
}
}
@Override
public void close() throws Exception {
this.stop();
@@ -52,19 +96,41 @@ class WebSocketServerImpl extends WebSocketServer implements AutoCloseable {
@Override
public void onOpen(org.java_websocket.WebSocket webSocket, ClientHandshake clientHandshake) {
lastClientHandshake = clientHandshake;
if (futureWebSocket != null) {
futureWebSocket.complete(webSocket);
futureWebSocket = null;
return;
}
webSocket.send("incoming");
}
@Override
public void onClose(org.java_websocket.WebSocket webSocket, int i, String s, boolean b) {
public void onClose(org.java_websocket.WebSocket webSocket, int code, String reason, boolean remote) {
addLog("close: code=" + code + " reason=" + reason);
}
@Override
public void onMessage(org.java_websocket.WebSocket webSocket, String s) {
addLog("message: " + s);
if (futureMessage != null) {
futureMessage.complete(s);
futureMessage = null;
}
}
public void onMessage(WebSocket conn, ByteBuffer message) {
String text = new String(message.array(), StandardCharsets.UTF_8);
addLog("message: " + text);
if (futureMessage != null) {
futureMessage.complete(text);
futureMessage = null;
}
}
@Override
public void onError(WebSocket webSocket, Exception e) {
addLog("error: " + e.toString());
e.printStackTrace();
startSemaphore.release();
}
+13 -7
View File
@@ -6,7 +6,7 @@
<groupId>com.microsoft.playwright</groupId>
<artifactId>parent-pom</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
<packaging>pom</packaging>
<name>Playwright Parent Project</name>
<description>Java library to automate Chromium, Firefox and WebKit with a single API.
@@ -45,7 +45,7 @@
<maven.compiler.target>8</maven.compiler.target>
<maven.compiler.parameters>true</maven.compiler.parameters>
<gson.version>2.11.0</gson.version>
<junit.version>5.10.3</junit.version>
<junit.version>5.11.1</junit.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<websocket.version>1.5.7</websocket.version>
<opentest4j.version>1.3.0</opentest4j.version>
@@ -79,6 +79,12 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
@@ -115,12 +121,12 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.2</version>
<version>3.1.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.2</version>
<version>3.1.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -130,7 +136,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.8.0</version>
<version>3.10.1</version>
<configuration>
<additionalOptions>--allow-script-in-comments</additionalOptions>
<failOnError>false</failOnError>
@@ -141,7 +147,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.3.1</version>
<version>3.5.0</version>
<configuration>
<properties>
<configurationParameters>
@@ -161,7 +167,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.2.4</version>
<version>3.2.7</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
+1 -1
View File
@@ -1 +1 @@
1.46.0
1.48.1
+7 -1
View File
@@ -45,7 +45,13 @@ do
fi
URL=$URL/$FILE_NAME
echo "Using url: $URL"
curl -O $URL
# Ubuntu 24.04-arm64 emulated via qemu has a bug, so we prefer wget over curl.
# See https://github.com/microsoft/playwright-java/issues/1678.
if command -v wget &> /dev/null; then
wget $URL
else
curl -O $URL
fi
unzip $FILE_NAME -d .
rm $FILE_NAME
+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>com.microsoft.playwright</groupId>
<artifactId>api-generator</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
<name>Playwright - API Generator</name>
<description>
This is an internal module used to generate Java API from the upstream Playwright
@@ -134,6 +134,18 @@ abstract class Element {
out.add(line.getAsString());
}
out.add("}</pre>");
} else if ("note".equals(type)) {
StringBuilder paragraph = new StringBuilder();
if (!out.isEmpty())
paragraph.append("\n<p> ");
paragraph.append("<strong>NOTE:</strong> ");
for (JsonElement text : node.getAsJsonArray("children")) {
if (!"text".equals(text.getAsJsonObject().get("type").getAsString())) {
continue;
}
paragraph.append(beautify(text.getAsJsonObject().get("text").getAsString()));
}
out.add(paragraph.toString());
} else {
String paragraph = node.get("text").getAsString();
Matcher matcher = Pattern.compile("^\\*\\*(.+)\\*\\*$").matcher(paragraph);
@@ -143,9 +155,6 @@ abstract class Element {
paragraph = "<strong>" + title + "</strong>";
} else {
paragraph = beautify(paragraph);
if ("note".equals(type)) {
paragraph = "<strong>NOTE:</strong> " + paragraph;
}
}
if (!out.isEmpty())
paragraph = "\n<p> " + paragraph;
@@ -532,6 +541,9 @@ class TypeRef extends Element {
throw new RuntimeException("Missing mapping for " + jsonPath);
}
}
if ("WebSocketRoute.onClose.handler".equals(jsonPath)) {
return "BiConsumer<Integer, String>";
}
if (jsonType.getAsJsonArray("args").size() == 1) {
String paramType = convertBuiltinType(jsonType.getAsJsonArray("args").get(0).getAsJsonObject());
if (!jsonType.has("returnType") || jsonType.get("returnType").isJsonNull()) {
@@ -989,7 +1001,10 @@ class Interface extends TypeDefinition {
if (asList("Page", "Frame", "ElementHandle", "Locator", "APIRequest", "Browser", "BrowserContext", "BrowserType", "Route", "Request", "Response", "JSHandle", "ConsoleMessage", "APIResponse", "Playwright").contains(jsonName)) {
output.add("import java.util.*;");
}
if (asList("Page", "Browser", "BrowserContext", "WebSocket", "Worker", "CDPSession").contains(jsonName)) {
if (asList("WebSocketRoute").contains(jsonName)) {
output.add("import java.util.function.BiConsumer;");
}
if (asList("Page", "Browser", "BrowserContext", "WebSocket", "Worker", "CDPSession", "WebSocketRoute").contains(jsonName)) {
output.add("import java.util.function.Consumer;");
}
if (asList("Page", "BrowserContext").contains(jsonName)) {
+1 -1
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.microsoft.playwright</groupId>
<artifactId>test-cli-fatjar</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
<name>Test Playwright Command Line FatJar</name>
<properties>
<compiler.version>1.8</compiler.version>
+1 -1
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.microsoft.playwright</groupId>
<artifactId>test-cli-version</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
<name>Test Playwright Command Line Version</name>
<properties>
<compiler.version>1.8</compiler.version>
+10 -4
View File
@@ -4,15 +4,15 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.microsoft.playwright</groupId>
<artifactId>test-local-installation</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
<name>Test local installation</name>
<description>Runs Playwright test suite (copied from playwright module) against locally cached Playwright</description>
<properties>
<compiler.version>1.8</compiler.version>
<gson.version>2.10.1</gson.version>
<junit.version>5.10.2</junit.version>
<gson.version>2.11.0</gson.version>
<junit.version>5.11.0</junit.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<websocket.version>1.5.6</websocket.version>
<websocket.version>1.5.7</websocket.version>
</properties>
<dependencies>
<dependency>
@@ -38,6 +38,12 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
+1 -1
View File
@@ -9,7 +9,7 @@
</parent>
<groupId>com.microsoft.playwright</groupId>
<artifactId>test-spring-boot-starter</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
<name>Test Playwright With Spring Boot</name>
<properties>
<spring.version>2.4.3</spring.version>
+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>com.microsoft.playwright</groupId>
<artifactId>update-version</artifactId>
<version>1.46.0</version>
<version>1.48.0</version>
<name>Playwright - Update Version in Documentation</name>
<description>
This is an internal module used to update versions in the documentation based on
+2 -2
View File
@@ -9,7 +9,7 @@ ARG DOCKER_IMAGE_NAME_TEMPLATE="mcr.microsoft.com/playwright/java:v%version%-foc
RUN apt-get update && \
apt-get install -y --no-install-recommends openjdk-21-jdk \
# Install utilities required for downloading browsers
curl \
wget \
# Install utilities required for downloading driver
unzip \
# For the MSEdge install script
@@ -21,7 +21,7 @@ RUN apt-get update && \
# Ubuntu 22.04 and earlier come with Maven 3.6.3 which fails with
# Java 21, so we install latest Maven from Apache instead.
RUN VERSION=3.9.6 && \
curl -o - https://archive.apache.org/dist/maven/maven-3/$VERSION/binaries/apache-maven-$VERSION-bin.tar.gz | tar zxfv - -C /opt/ && \
wget -O - https://archive.apache.org/dist/maven/maven-3/$VERSION/binaries/apache-maven-$VERSION-bin.tar.gz | tar zxfv - -C /opt/ && \
ln -s /opt/apache-maven-$VERSION/bin/mvn /usr/local/bin/
ARG PW_TARGET_ARCH
+2 -2
View File
@@ -9,7 +9,7 @@ ARG DOCKER_IMAGE_NAME_TEMPLATE="mcr.microsoft.com/playwright/java:v%version%-jam
RUN apt-get update && \
apt-get install -y --no-install-recommends openjdk-21-jdk \
# Install utilities required for downloading browsers
curl \
wget \
# Install utilities required for downloading driver
unzip \
# For the MSEdge install script
@@ -21,7 +21,7 @@ RUN apt-get update && \
# Ubuntu 22.04 and earlier come with Maven 3.6.3 which fails with
# Java 21, so we install latest Maven from Apache instead.
RUN VERSION=3.9.6 && \
curl -o - https://archive.apache.org/dist/maven/maven-3/$VERSION/binaries/apache-maven-$VERSION-bin.tar.gz | tar zxfv - -C /opt/ && \
wget -O - https://archive.apache.org/dist/maven/maven-3/$VERSION/binaries/apache-maven-$VERSION-bin.tar.gz | tar zxfv - -C /opt/ && \
ln -s /opt/apache-maven-$VERSION/bin/mvn /usr/local/bin/
ARG PW_TARGET_ARCH
+53
View File
@@ -0,0 +1,53 @@
FROM ubuntu:noble
ARG DEBIAN_FRONTEND=noninteractive
ARG TZ=America/Los_Angeles
ARG DOCKER_IMAGE_NAME_TEMPLATE="mcr.microsoft.com/playwright/java:v%version%-noble"
# === INSTALL JDK and Maven ===
RUN apt-get update && \
apt-get install -y --no-install-recommends openjdk-21-jdk \
# Install utilities required for downloading browsers
wget \
# Install utilities required for downloading driver
unzip \
# For the MSEdge install script
gpg && \
rm -rf /var/lib/apt/lists/* && \
# Create the pwuser
adduser pwuser
# Ubuntu 22.04 and earlier come with Maven 3.6.3 which fails with
# Java 21, so we install latest Maven from Apache instead.
RUN VERSION=3.9.6 && \
wget -O - https://archive.apache.org/dist/maven/maven-3/$VERSION/binaries/apache-maven-$VERSION-bin.tar.gz | tar zxfv - -C /opt/ && \
ln -s /opt/apache-maven-$VERSION/bin/mvn /usr/local/bin/
ARG PW_TARGET_ARCH
ENV JAVA_HOME=/usr/lib/jvm/java-21-openjdk-${PW_TARGET_ARCH}
# === BAKE BROWSERS INTO IMAGE ===
# Browsers will remain downloaded in `/ms-playwright`.
# Note: make sure to set 777 to the registry so that any user can access
# registry.
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
RUN mkdir /ms-playwright && \
mkdir /tmp/pw-java
COPY . /tmp/pw-java
RUN cd /tmp/pw-java && \
./scripts/download_driver.sh && \
mvn install -D skipTests --no-transfer-progress && \
DEBIAN_FRONTEND=noninteractive mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI \
-D exec.args="install-deps" -f playwright/pom.xml --no-transfer-progress && \
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI \
-D exec.args="install" -f playwright/pom.xml --no-transfer-progress && \
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI \
-D exec.args="mark-docker-image '${DOCKER_IMAGE_NAME_TEMPLATE}'" -f playwright/pom.xml --no-transfer-progress && \
rm -rf /tmp/pw-java && \
chmod -R 777 $PLAYWRIGHT_BROWSERS_PATH
+19 -18
View File
@@ -21,34 +21,27 @@ if [[ "${RELEASE_CHANNEL}" == "stable" ]]; then
echo "ERROR: cannot publish stable docker with Playwright version '${PW_VERSION}'"
exit 1
fi
elif [[ "${RELEASE_CHANNEL}" == "canary" ]]; then
:
else
echo "ERROR: unknown release channel - ${RELEASE_CHANNEL}"
echo "Must be either 'stable' or 'canary'"
exit 1
fi
# Ubuntu 20.04
FOCAL_TAGS=(
"next-focal"
"v${PW_VERSION}-focal"
)
if [[ "$RELEASE_CHANNEL" == "stable" ]]; then
FOCAL_TAGS+=("focal")
FOCAL_TAGS+=("v${PW_VERSION}-focal")
fi
# Ubuntu 22.04
JAMMY_TAGS=(
"next"
"next-jammy"
"v${PW_VERSION}-jammy"
)
if [[ "$RELEASE_CHANNEL" == "stable" ]]; then
JAMMY_TAGS+=("jammy")
JAMMY_TAGS+=("latest")
JAMMY_TAGS+=("v${PW_VERSION}")
JAMMY_TAGS+=("v${PW_VERSION}-jammy")
fi
# Ubuntu 24.04
NOBLE_TAGS=(
"v${PW_VERSION}"
"v${PW_VERSION}-noble"
)
tag_and_push() {
local source="$1"
@@ -86,8 +79,10 @@ publish_docker_images_with_arch_suffix() {
TAGS=("${FOCAL_TAGS[@]}")
elif [[ "$FLAVOR" == "jammy" ]]; then
TAGS=("${JAMMY_TAGS[@]}")
elif [[ "$FLAVOR" == "noble" ]]; then
TAGS=("${NOBLE_TAGS[@]}")
else
echo "ERROR: unknown flavor - $FLAVOR. Must be either 'focal' or 'jammy'"
echo "ERROR: unknown flavor - $FLAVOR. Must be either 'focal', 'jammy', or 'noble'"
exit 1
fi
local ARCH="$2"
@@ -112,8 +107,10 @@ publish_docker_manifest () {
TAGS=("${FOCAL_TAGS[@]}")
elif [[ "$FLAVOR" == "jammy" ]]; then
TAGS=("${JAMMY_TAGS[@]}")
elif [[ "$FLAVOR" == "noble" ]]; then
TAGS=("${NOBLE_TAGS[@]}")
else
echo "ERROR: unknown flavor - $FLAVOR. Must be either 'focal' or 'jammy'"
echo "ERROR: unknown flavor - $FLAVOR. Must be either 'focal', 'jammy', 'noble'"
exit 1
fi
@@ -139,3 +136,7 @@ publish_docker_manifest focal amd64 arm64
publish_docker_images_with_arch_suffix jammy amd64
publish_docker_images_with_arch_suffix jammy arm64
publish_docker_manifest jammy amd64 arm64
publish_docker_images_with_arch_suffix noble amd64
publish_docker_images_with_arch_suffix noble arm64
publish_docker_manifest noble amd64 arm64