Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cec4d663e9 | |||
| 2ff37da5f5 | |||
| ee99afc3a3 | |||
| 34017a26a3 | |||
| 29f58a5840 | |||
| d2d78a7299 | |||
| 6e66ee7c35 | |||
| 4bda800e11 | |||
| 2cce9776be | |||
| 20b13ad0c0 | |||
| 08ac52ca53 | |||
| 9c220cd359 | |||
| ab443d1638 | |||
| 186aede95c | |||
| db52fa94e7 | |||
| ee18e1a499 | |||
| 9cf4bf2263 | |||
| 36350f3c5c | |||
| f3476c68ff | |||
| 8fd8f1c831 | |||
| 7d2066693b | |||
| 6b01b878cb | |||
| 2e32eb704f | |||
| b81b144680 | |||
| 256e41a505 | |||
| 3054364101 | |||
| 40b8802874 | |||
| 49f53fceaf | |||
| 291c12a54c | |||
| 2b3413fad4 | |||
| 3eab530e95 | |||
| 7d35be4f89 |
+10
-1
@@ -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
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -19,7 +19,6 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: microsoft/playwright-github-action@v1
|
||||
- name: Set up JDK 1.8
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
@@ -30,6 +29,8 @@ jobs:
|
||||
run: scripts/download_driver.sh
|
||||
- name: Build & Install
|
||||
run: mvn -B install -D skipTests --no-transfer-progress
|
||||
- name: Install browsers
|
||||
run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
|
||||
- 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:
|
||||
@@ -63,7 +64,6 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: microsoft/playwright-github-action@v1
|
||||
- name: Install Media Pack
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: powershell
|
||||
@@ -78,10 +78,12 @@ jobs:
|
||||
run: scripts/download_driver.sh
|
||||
- name: Build & Install
|
||||
run: mvn -B install -D skipTests --no-transfer-progress
|
||||
- name: Install browsers
|
||||
run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
|
||||
- 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:
|
||||
@@ -97,7 +99,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: microsoft/playwright-github-action@v1
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
@@ -108,6 +109,8 @@ jobs:
|
||||
run: scripts/download_driver.sh
|
||||
- name: Build & Install
|
||||
run: mvn -B install -D skipTests --no-transfer-progress
|
||||
- name: Install browsers
|
||||
run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
|
||||
- name: Run tests
|
||||
run: mvn test --no-transfer-progress --fail-at-end
|
||||
env:
|
||||
|
||||
@@ -24,7 +24,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
flavor: [focal, jammy]
|
||||
flavor: [jammy, noble]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Build Docker image
|
||||
|
||||
@@ -9,7 +9,7 @@ on:
|
||||
jobs:
|
||||
trigger:
|
||||
name: "trigger"
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- run: |
|
||||
curl -X POST \
|
||||
|
||||
@@ -20,11 +20,14 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: microsoft/playwright-github-action@v1
|
||||
- name: Download drivers
|
||||
run: scripts/download_driver.sh
|
||||
- name: Regenerate APIs
|
||||
run: scripts/generate_api.sh
|
||||
- name: Build & Install
|
||||
run: mvn -B install -D skipTests --no-transfer-progress
|
||||
- name: Install browsers
|
||||
run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
|
||||
- name: Update browser versions in README
|
||||
run: scripts/update_readme.sh
|
||||
- name: Verify API is up to date
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
[](https://javadoc.io/doc/com.microsoft.playwright/playwright)
|
||||
[](https://search.maven.org/search?q=com.microsoft.playwright)
|
||||
[](https://oss.sonatype.org/content/repositories/snapshots/com/microsoft/playwright/playwright/)
|
||||
[](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: |
|
||||
| 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: |
|
||||
| Chromium <!-- GEN:chromium-version -->131.0.6778.33<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||
| WebKit <!-- GEN:webkit-version -->18.2<!-- GEN:stop --> | ✅ | ✅ | ✅ |
|
||||
| Firefox <!-- GEN:firefox-version -->132.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
@@ -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
@@ -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
|
||||
@@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>parent-pom</artifactId>
|
||||
<version>1.46.0</version>
|
||||
<version>1.49.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>driver-bundle</artifactId>
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>parent-pom</artifactId>
|
||||
<version>1.46.0</version>
|
||||
<version>1.49.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>driver</artifactId>
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>org.example</groupId>
|
||||
<artifactId>examples</artifactId>
|
||||
<version>1.46.0</version>
|
||||
<version>1.49.0</version>
|
||||
<name>Playwright Client Examples</name>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
||||
+5
-1
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>parent-pom</artifactId>
|
||||
<version>1.46.0</version>
|
||||
<version>1.49.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
|
||||
*/
|
||||
|
||||
@@ -29,15 +29,15 @@ import java.util.regex.Pattern;
|
||||
* import com.microsoft.playwright.*;
|
||||
*
|
||||
* public class Example {
|
||||
* public static void main(String[] args) {
|
||||
* try (Playwright playwright = Playwright.create()) {
|
||||
* BrowserType firefox = playwright.firefox()
|
||||
* Browser browser = firefox.launch();
|
||||
* Page page = browser.newPage();
|
||||
* page.navigate('https://example.com');
|
||||
* browser.close();
|
||||
* }
|
||||
* }
|
||||
* public static void main(String[] args) {
|
||||
* try (Playwright playwright = Playwright.create()) {
|
||||
* BrowserType firefox = playwright.firefox();
|
||||
* Browser browser = firefox.launch();
|
||||
* Page page = browser.newPage();
|
||||
* page.navigate("https://example.com");
|
||||
* browser.close();
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
@@ -101,21 +101,21 @@ 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}.
|
||||
*/
|
||||
public List<ClientCertificate> clientCertificates;
|
||||
/**
|
||||
* Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code
|
||||
* "no-preference"}. See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing
|
||||
* {@code null} resets emulation to system defaults. Defaults to {@code "light"}.
|
||||
* Emulates <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-colors-scheme</a> media
|
||||
* feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
|
||||
* "light"}.
|
||||
*/
|
||||
public Optional<ColorScheme> colorScheme;
|
||||
/**
|
||||
@@ -179,10 +179,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 +312,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}.
|
||||
@@ -331,9 +325,11 @@ public interface Browser extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code
|
||||
* "no-preference"}. See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing
|
||||
* {@code null} resets emulation to system defaults. Defaults to {@code "light"}.
|
||||
* Emulates <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-colors-scheme</a> media
|
||||
* feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
|
||||
* "light"}.
|
||||
*/
|
||||
public NewContextOptions setColorScheme(ColorScheme colorScheme) {
|
||||
this.colorScheme = Optional.ofNullable(colorScheme);
|
||||
@@ -446,20 +442,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,21 +654,21 @@ 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}.
|
||||
*/
|
||||
public List<ClientCertificate> clientCertificates;
|
||||
/**
|
||||
* Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code
|
||||
* "no-preference"}. See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing
|
||||
* {@code null} resets emulation to system defaults. Defaults to {@code "light"}.
|
||||
* Emulates <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-colors-scheme</a> media
|
||||
* feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
|
||||
* "light"}.
|
||||
*/
|
||||
public Optional<ColorScheme> colorScheme;
|
||||
/**
|
||||
@@ -744,10 +732,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 +865,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}.
|
||||
@@ -896,9 +878,11 @@ public interface Browser extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code
|
||||
* "no-preference"}. See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing
|
||||
* {@code null} resets emulation to system defaults. Defaults to {@code "light"}.
|
||||
* Emulates <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-colors-scheme</a> media
|
||||
* feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
|
||||
* "light"}.
|
||||
*/
|
||||
public NewPageOptions setColorScheme(ColorScheme colorScheme) {
|
||||
this.colorScheme = Optional.ofNullable(colorScheme);
|
||||
@@ -1011,20 +995,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;
|
||||
@@ -1321,7 +1297,7 @@ public interface Browser extends AutoCloseable {
|
||||
* BrowserContext context = browser.newContext();
|
||||
* // Create a new page in a pristine context.
|
||||
* Page page = context.newPage();
|
||||
* page.navigate('https://example.com');
|
||||
* page.navigate("https://example.com");
|
||||
*
|
||||
* // Graceful close up everything
|
||||
* context.close();
|
||||
@@ -1348,7 +1324,7 @@ public interface Browser extends AutoCloseable {
|
||||
* BrowserContext context = browser.newContext();
|
||||
* // Create a new page in a pristine context.
|
||||
* Page page = context.newPage();
|
||||
* page.navigate('https://example.com');
|
||||
* page.navigate("https://example.com");
|
||||
*
|
||||
* // Graceful close up everything
|
||||
* context.close();
|
||||
@@ -1396,7 +1372,7 @@ public interface Browser extends AutoCloseable {
|
||||
* <pre>{@code
|
||||
* browser.startTracing(page, new Browser.StartTracingOptions()
|
||||
* .setPath(Paths.get("trace.json")));
|
||||
* page.goto('https://www.google.com');
|
||||
* page.navigate("https://www.google.com");
|
||||
* browser.stopTracing();
|
||||
* }</pre>
|
||||
*
|
||||
@@ -1420,7 +1396,7 @@ public interface Browser extends AutoCloseable {
|
||||
* <pre>{@code
|
||||
* browser.startTracing(page, new Browser.StartTracingOptions()
|
||||
* .setPath(Paths.get("trace.json")));
|
||||
* page.goto('https://www.google.com');
|
||||
* page.navigate("https://www.google.com");
|
||||
* browser.stopTracing();
|
||||
* }</pre>
|
||||
*
|
||||
@@ -1443,7 +1419,7 @@ public interface Browser extends AutoCloseable {
|
||||
* <pre>{@code
|
||||
* browser.startTracing(page, new Browser.StartTracingOptions()
|
||||
* .setPath(Paths.get("trace.json")));
|
||||
* page.goto('https://www.google.com');
|
||||
* page.navigate("https://www.google.com");
|
||||
* browser.stopTracing();
|
||||
* }</pre>
|
||||
*
|
||||
|
||||
@@ -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();
|
||||
@@ -700,7 +701,7 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* public class Example {
|
||||
* public static void main(String[] args) {
|
||||
* try (Playwright playwright = Playwright.create()) {
|
||||
* BrowserType webkit = playwright.webkit()
|
||||
* BrowserType webkit = playwright.webkit();
|
||||
* Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
|
||||
* BrowserContext context = browser.newContext();
|
||||
* context.exposeBinding("pageURL", (source, args) -> source.page().url());
|
||||
@@ -747,7 +748,7 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* public class Example {
|
||||
* public static void main(String[] args) {
|
||||
* try (Playwright playwright = Playwright.create()) {
|
||||
* BrowserType webkit = playwright.webkit()
|
||||
* BrowserType webkit = playwright.webkit();
|
||||
* Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
|
||||
* BrowserContext context = browser.newContext();
|
||||
* context.exposeBinding("pageURL", (source, args) -> source.page().url());
|
||||
@@ -796,8 +797,9 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* public class Example {
|
||||
* public static void main(String[] args) {
|
||||
* try (Playwright playwright = Playwright.create()) {
|
||||
* BrowserType webkit = playwright.webkit()
|
||||
* BrowserType webkit = playwright.webkit();
|
||||
* Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
|
||||
* BrowserContext context = browser.newContext();
|
||||
* context.exposeFunction("sha256", args -> {
|
||||
* String text = (String) args[0];
|
||||
* MessageDigest crypto;
|
||||
@@ -926,7 +928,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 +984,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 +1038,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 +1094,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 +1148,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 +1204,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 +1258,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 +1273,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,21 +460,21 @@ 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}.
|
||||
*/
|
||||
public List<ClientCertificate> clientCertificates;
|
||||
/**
|
||||
* Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code
|
||||
* "no-preference"}. See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing
|
||||
* {@code null} resets emulation to system defaults. Defaults to {@code "light"}.
|
||||
* Emulates <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-colors-scheme</a> media
|
||||
* feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
|
||||
* "light"}.
|
||||
*/
|
||||
public Optional<ColorScheme> colorScheme;
|
||||
/**
|
||||
@@ -763,12 +763,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}.
|
||||
@@ -778,9 +776,11 @@ public interface BrowserType {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code
|
||||
* "no-preference"}. See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing
|
||||
* {@code null} resets emulation to system defaults. Defaults to {@code "light"}.
|
||||
* Emulates <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-colors-scheme</a> media
|
||||
* feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
|
||||
* "light"}.
|
||||
*/
|
||||
public LaunchPersistentContextOptions setColorScheme(ColorScheme colorScheme) {
|
||||
this.colorScheme = Optional.ofNullable(colorScheme);
|
||||
|
||||
@@ -227,6 +227,10 @@ public interface Clock {
|
||||
/**
|
||||
* Makes {@code Date.now} and {@code new Date()} return fixed fake time at all times, keeps all the timers running.
|
||||
*
|
||||
* <p> Use this method for simple scenarios where you only need to test with a predefined time. For more advanced scenarios,
|
||||
* use {@link com.microsoft.playwright.Clock#install Clock.install()} instead. Read docs on <a
|
||||
* href="https://playwright.dev/java/docs/clock">clock emulation</a> to learn more.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.clock().setFixedTime(new Date());
|
||||
@@ -241,6 +245,10 @@ public interface Clock {
|
||||
/**
|
||||
* Makes {@code Date.now} and {@code new Date()} return fixed fake time at all times, keeps all the timers running.
|
||||
*
|
||||
* <p> Use this method for simple scenarios where you only need to test with a predefined time. For more advanced scenarios,
|
||||
* use {@link com.microsoft.playwright.Clock#install Clock.install()} instead. Read docs on <a
|
||||
* href="https://playwright.dev/java/docs/clock">clock emulation</a> to learn more.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.clock().setFixedTime(new Date());
|
||||
@@ -255,6 +263,10 @@ public interface Clock {
|
||||
/**
|
||||
* Makes {@code Date.now} and {@code new Date()} return fixed fake time at all times, keeps all the timers running.
|
||||
*
|
||||
* <p> Use this method for simple scenarios where you only need to test with a predefined time. For more advanced scenarios,
|
||||
* use {@link com.microsoft.playwright.Clock#install Clock.install()} instead. Read docs on <a
|
||||
* href="https://playwright.dev/java/docs/clock">clock emulation</a> to learn more.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.clock().setFixedTime(new Date());
|
||||
@@ -267,7 +279,8 @@ public interface Clock {
|
||||
*/
|
||||
void setFixedTime(Date time);
|
||||
/**
|
||||
* Sets current system time but does not trigger any timers.
|
||||
* Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for example
|
||||
* switching from summer to winter time, or changing time zones.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
@@ -281,7 +294,8 @@ public interface Clock {
|
||||
*/
|
||||
void setSystemTime(long time);
|
||||
/**
|
||||
* Sets current system time but does not trigger any timers.
|
||||
* Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for example
|
||||
* switching from summer to winter time, or changing time zones.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
@@ -295,7 +309,8 @@ public interface Clock {
|
||||
*/
|
||||
void setSystemTime(String time);
|
||||
/**
|
||||
* Sets current system time but does not trigger any timers.
|
||||
* Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for example
|
||||
* switching from summer to winter time, or changing time zones.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
|
||||
@@ -39,8 +39,8 @@ import java.util.*;
|
||||
* });
|
||||
*
|
||||
* // Deconstruct console.log arguments
|
||||
* msg.args().get(0).jsonValue() // hello
|
||||
* msg.args().get(1).jsonValue() // 42
|
||||
* msg.args().get(0).jsonValue(); // hello
|
||||
* msg.args().get(1).jsonValue(); // 42
|
||||
* }</pre>
|
||||
*/
|
||||
public interface ConsoleMessage {
|
||||
|
||||
@@ -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;
|
||||
@@ -3491,19 +3499,19 @@ public interface Frame {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -3533,19 +3541,19 @@ public interface Frame {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -3573,19 +3581,19 @@ public interface Frame {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -3615,19 +3623,19 @@ public interface Frame {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
|
||||
@@ -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
|
||||
*/
|
||||
@@ -733,19 +734,19 @@ public interface FrameLocator {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -775,19 +776,19 @@ public interface FrameLocator {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -815,19 +816,19 @@ public interface FrameLocator {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -857,19 +858,19 @@ public interface FrameLocator {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -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();
|
||||
|
||||
@@ -48,10 +48,7 @@ import com.microsoft.playwright.options.*;
|
||||
*
|
||||
* <p> An example to trigger select-all with the keyboard
|
||||
* <pre>{@code
|
||||
* // on Windows and Linux
|
||||
* page.keyboard().press("Control+A");
|
||||
* // on macOS
|
||||
* page.keyboard().press("Meta+A");
|
||||
* page.keyboard().press("ControlOrMeta+A");
|
||||
* }</pre>
|
||||
*/
|
||||
public interface Keyboard {
|
||||
@@ -164,7 +161,7 @@ public interface Keyboard {
|
||||
* Page page = browser.newPage();
|
||||
* page.navigate("https://keycode.info");
|
||||
* page.keyboard().press("A");
|
||||
* page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png"));
|
||||
* page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png")));
|
||||
* page.keyboard().press("ArrowLeft");
|
||||
* page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png")));
|
||||
* page.keyboard().press("Shift+O");
|
||||
@@ -211,7 +208,7 @@ public interface Keyboard {
|
||||
* Page page = browser.newPage();
|
||||
* page.navigate("https://keycode.info");
|
||||
* page.keyboard().press("A");
|
||||
* page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png"));
|
||||
* page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png")));
|
||||
* page.keyboard().press("ArrowLeft");
|
||||
* page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png")));
|
||||
* page.keyboard().press("Shift+O");
|
||||
|
||||
@@ -29,6 +29,26 @@ import java.util.regex.Pattern;
|
||||
* <p> <a href="https://playwright.dev/java/docs/locators">Learn more about locators</a>.
|
||||
*/
|
||||
public interface Locator {
|
||||
class AriaSnapshotOptions {
|
||||
/**
|
||||
* Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default
|
||||
* value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout
|
||||
* BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()}
|
||||
* methods.
|
||||
*/
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default
|
||||
* value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout
|
||||
* BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()}
|
||||
* methods.
|
||||
*/
|
||||
public AriaSnapshotOptions setTimeout(double timeout) {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class BlurOptions {
|
||||
/**
|
||||
* Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default
|
||||
@@ -235,7 +255,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 +333,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 +380,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 +451,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 +1083,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 +1140,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 +1697,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 +1717,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 +1908,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 +1965,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,14 +2165,13 @@ 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
|
||||
* for (Locator li : page.getByRole('listitem').all())
|
||||
* for (Locator li : page.getByRole("listitem").all())
|
||||
* li.click();
|
||||
* }</pre>
|
||||
*
|
||||
@@ -2195,6 +2222,66 @@ public interface Locator {
|
||||
* @since v1.34
|
||||
*/
|
||||
Locator and(Locator locator);
|
||||
/**
|
||||
* Captures the aria snapshot of the given element. Read more about <a
|
||||
* href="https://playwright.dev/java/docs/aria-snapshots">aria snapshots</a> and {@link
|
||||
* com.microsoft.playwright.assertions.LocatorAssertions#matchesAriaSnapshot LocatorAssertions.matchesAriaSnapshot()} for
|
||||
* the corresponding assertion.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.getByRole(AriaRole.LINK).ariaSnapshot();
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
*
|
||||
* <p> This method captures the aria snapshot of the given element. The snapshot is a string that represents the state of the
|
||||
* element and its children. The snapshot can be used to assert the state of the element in the test, or to compare it to
|
||||
* state in the future.
|
||||
*
|
||||
* <p> The ARIA snapshot is represented using <a href="https://yaml.org/spec/1.2.2/">YAML</a> markup language:
|
||||
* <ul>
|
||||
* <li> The keys of the objects are the roles and optional accessible names of the elements.</li>
|
||||
* <li> The values are either text content or an array of child elements.</li>
|
||||
* <li> Generic static text can be represented with the {@code text} key.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p> Below is the HTML markup and the respective ARIA snapshot:
|
||||
*
|
||||
* @since v1.49
|
||||
*/
|
||||
default String ariaSnapshot() {
|
||||
return ariaSnapshot(null);
|
||||
}
|
||||
/**
|
||||
* Captures the aria snapshot of the given element. Read more about <a
|
||||
* href="https://playwright.dev/java/docs/aria-snapshots">aria snapshots</a> and {@link
|
||||
* com.microsoft.playwright.assertions.LocatorAssertions#matchesAriaSnapshot LocatorAssertions.matchesAriaSnapshot()} for
|
||||
* the corresponding assertion.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.getByRole(AriaRole.LINK).ariaSnapshot();
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
*
|
||||
* <p> This method captures the aria snapshot of the given element. The snapshot is a string that represents the state of the
|
||||
* element and its children. The snapshot can be used to assert the state of the element in the test, or to compare it to
|
||||
* state in the future.
|
||||
*
|
||||
* <p> The ARIA snapshot is represented using <a href="https://yaml.org/spec/1.2.2/">YAML</a> markup language:
|
||||
* <ul>
|
||||
* <li> The keys of the objects are the roles and optional accessible names of the elements.</li>
|
||||
* <li> The values are either text content or an array of child elements.</li>
|
||||
* <li> Generic static text can be represented with the {@code text} key.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p> Below is the HTML markup and the respective ARIA snapshot:
|
||||
*
|
||||
* @since v1.49
|
||||
*/
|
||||
String ariaSnapshot(AriaSnapshotOptions options);
|
||||
/**
|
||||
* Calls <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur">blur</a> on the element.
|
||||
*
|
||||
@@ -3448,19 +3535,19 @@ public interface Locator {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -3490,19 +3577,19 @@ public interface Locator {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -3530,19 +3617,19 @@ public interface Locator {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -3572,19 +3659,19 @@ public interface Locator {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -4077,7 +4164,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;
|
||||
@@ -955,8 +959,10 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class EmulateMediaOptions {
|
||||
/**
|
||||
* Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code
|
||||
* "no-preference"}. Passing {@code null} disables color scheme emulation.
|
||||
* Emulates <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-colors-scheme</a> media
|
||||
* feature, supported values are {@code "light"} and {@code "dark"}. Passing {@code null} disables color scheme emulation.
|
||||
* {@code "no-preference"} is deprecated.
|
||||
*/
|
||||
public Optional<ColorScheme> colorScheme;
|
||||
/**
|
||||
@@ -976,8 +982,10 @@ public interface Page extends AutoCloseable {
|
||||
public Optional<ReducedMotion> reducedMotion;
|
||||
|
||||
/**
|
||||
* Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code
|
||||
* "no-preference"}. Passing {@code null} disables color scheme emulation.
|
||||
* Emulates <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme">prefers-colors-scheme</a> media
|
||||
* feature, supported values are {@code "light"} and {@code "dark"}. Passing {@code null} disables color scheme emulation.
|
||||
* {@code "no-preference"} is deprecated.
|
||||
*/
|
||||
public EmulateMediaOptions setColorScheme(ColorScheme colorScheme) {
|
||||
this.colorScheme = Optional.ofNullable(colorScheme);
|
||||
@@ -1591,7 +1599,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 +1664,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 +2431,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 +2471,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 +2701,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 +2726,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 +2972,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 +3037,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;
|
||||
@@ -4143,9 +4155,9 @@ public interface Page extends AutoCloseable {
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.dragAndDrop("#source", '#target');
|
||||
* page.dragAndDrop("#source", "#target");
|
||||
* // or specify exact positions relative to the top-left corners of the elements:
|
||||
* page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions()
|
||||
* page.dragAndDrop("#source", "#target", new Page.DragAndDropOptions()
|
||||
* .setSourcePosition(34, 7).setTargetPosition(10, 20));
|
||||
* }</pre>
|
||||
*
|
||||
@@ -4164,9 +4176,9 @@ public interface Page extends AutoCloseable {
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.dragAndDrop("#source", '#target');
|
||||
* page.dragAndDrop("#source", "#target");
|
||||
* // or specify exact positions relative to the top-left corners of the elements:
|
||||
* page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions()
|
||||
* page.dragAndDrop("#source", "#target", new Page.DragAndDropOptions()
|
||||
* .setSourcePosition(34, 7).setTargetPosition(10, 20));
|
||||
* }</pre>
|
||||
*
|
||||
@@ -4206,8 +4218,6 @@ public interface Page extends AutoCloseable {
|
||||
* // → true
|
||||
* page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches");
|
||||
* // → false
|
||||
* page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches");
|
||||
* // → false
|
||||
* }</pre>
|
||||
*
|
||||
* @since v1.8
|
||||
@@ -4244,8 +4254,6 @@ public interface Page extends AutoCloseable {
|
||||
* // → true
|
||||
* page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches");
|
||||
* // → false
|
||||
* page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches");
|
||||
* // → false
|
||||
* }</pre>
|
||||
*
|
||||
* @since v1.8
|
||||
@@ -4552,7 +4560,7 @@ public interface Page extends AutoCloseable {
|
||||
* public static void main(String[] args) {
|
||||
* try (Playwright playwright = Playwright.create()) {
|
||||
* BrowserType webkit = playwright.webkit();
|
||||
* Browser browser = webkit.launch({ headless: false });
|
||||
* Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
|
||||
* BrowserContext context = browser.newContext();
|
||||
* Page page = context.newPage();
|
||||
* page.exposeBinding("pageURL", (source, args) -> source.page().url());
|
||||
@@ -4602,7 +4610,7 @@ public interface Page extends AutoCloseable {
|
||||
* public static void main(String[] args) {
|
||||
* try (Playwright playwright = Playwright.create()) {
|
||||
* BrowserType webkit = playwright.webkit();
|
||||
* Browser browser = webkit.launch({ headless: false });
|
||||
* Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
|
||||
* BrowserContext context = browser.newContext();
|
||||
* Page page = context.newPage();
|
||||
* page.exposeBinding("pageURL", (source, args) -> source.page().url());
|
||||
@@ -4654,26 +4662,27 @@ public interface Page extends AutoCloseable {
|
||||
* public static void main(String[] args) {
|
||||
* try (Playwright playwright = Playwright.create()) {
|
||||
* BrowserType webkit = playwright.webkit();
|
||||
* Browser browser = webkit.launch({ headless: false });
|
||||
* Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
|
||||
* Page page = browser.newPage();
|
||||
* page.exposeFunction("sha256", args -> {
|
||||
* String text = (String) args[0];
|
||||
* MessageDigest crypto;
|
||||
* try {
|
||||
* crypto = MessageDigest.getInstance("SHA-256");
|
||||
* String text = (String) args[0];
|
||||
* MessageDigest crypto = MessageDigest.getInstance("SHA-256");
|
||||
* byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
|
||||
* return Base64.getEncoder().encodeToString(token);
|
||||
* } catch (NoSuchAlgorithmException e) {
|
||||
* return null;
|
||||
* }
|
||||
* byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
|
||||
* return Base64.getEncoder().encodeToString(token);
|
||||
* });
|
||||
* page.setContent("<script>\n" +
|
||||
* page.setContent(
|
||||
* "<script>\n" +
|
||||
* " async function onClick() {\n" +
|
||||
* " document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +
|
||||
* " }\n" +
|
||||
* "</script>\n" +
|
||||
* "<button onclick=\"onClick()\">Click me</button>\n" +
|
||||
* "<div></div>\n");
|
||||
* "<div></div>"
|
||||
* );
|
||||
* page.click("button");
|
||||
* }
|
||||
* }
|
||||
@@ -4749,7 +4758,7 @@ public interface Page extends AutoCloseable {
|
||||
* Frame frame = page.frame("frame-name");
|
||||
* }</pre>
|
||||
* <pre>{@code
|
||||
* Frame frame = page.frameByUrl(Pattern.compile(".*domain.*");
|
||||
* Frame frame = page.frameByUrl(Pattern.compile(".*domain.*"));
|
||||
* }</pre>
|
||||
*
|
||||
* @param name Frame name specified in the {@code iframe}'s {@code name} attribute.
|
||||
@@ -5155,19 +5164,19 @@ public interface Page extends AutoCloseable {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -5197,19 +5206,19 @@ public interface Page extends AutoCloseable {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -5237,19 +5246,19 @@ public interface Page extends AutoCloseable {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -5279,19 +5288,19 @@ public interface Page extends AutoCloseable {
|
||||
* <p> You can locate by text substring, exact string, or a regular expression:
|
||||
* <pre>{@code
|
||||
* // Matches <span>
|
||||
* page.getByText("world")
|
||||
* page.getByText("world");
|
||||
*
|
||||
* // Matches first <div>
|
||||
* page.getByText("Hello world")
|
||||
* page.getByText("Hello world");
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
|
||||
* page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
|
||||
*
|
||||
* // Matches both <div>s
|
||||
* page.getByText(Pattern.compile("Hello"))
|
||||
* page.getByText(Pattern.compile("Hello"));
|
||||
*
|
||||
* // Matches second <div>
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
|
||||
* page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
@@ -5414,6 +5423,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 +5801,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,39 +6068,37 @@ 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>
|
||||
*
|
||||
* <p> An example that closes a "Sign up to the newsletter" dialog when it appears:
|
||||
* <pre>{@code
|
||||
* // Setup the handler.
|
||||
* page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () => {
|
||||
* page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () -> {
|
||||
* page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("No thanks")).click();
|
||||
* });
|
||||
*
|
||||
* // Write the test as usual.
|
||||
* page.goto("https://example.com");
|
||||
* page.navigate("https://example.com");
|
||||
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
|
||||
* }</pre>
|
||||
*
|
||||
* <p> An example that skips the "Confirm your security details" page when it is shown:
|
||||
* <pre>{@code
|
||||
* // Setup the handler.
|
||||
* page.addLocatorHandler(page.getByText("Confirm your security details")), () => {
|
||||
* page.addLocatorHandler(page.getByText("Confirm your security details"), () -> {
|
||||
* page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Remind me later")).click();
|
||||
* });
|
||||
*
|
||||
* // Write the test as usual.
|
||||
* page.goto("https://example.com");
|
||||
* page.navigate("https://example.com");
|
||||
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
|
||||
* }</pre>
|
||||
*
|
||||
@@ -6082,19 +6107,19 @@ public interface Page extends AutoCloseable {
|
||||
* handler does not hide the {@code <body>} element.
|
||||
* <pre>{@code
|
||||
* // Setup the handler.
|
||||
* page.addLocatorHandler(page.locator("body")), () => {
|
||||
* page.addLocatorHandler(page.locator("body"), () -> {
|
||||
* page.evaluate("window.removeObstructionsForTestIfNeeded()");
|
||||
* }, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true));
|
||||
* }, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true));
|
||||
*
|
||||
* // Write the test as usual.
|
||||
* page.goto("https://example.com");
|
||||
* page.navigate("https://example.com");
|
||||
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Handler takes the original locator as an argument. You can also automatically remove the handler after a number of
|
||||
* invocations by setting {@code times}:
|
||||
* <pre>{@code
|
||||
* page.addLocatorHandler(page.getByLabel("Close"), locator => {
|
||||
* page.addLocatorHandler(page.getByLabel("Close"), locator -> {
|
||||
* locator.click();
|
||||
* }, new Page.AddLocatorHandlerOptions().setTimes(1));
|
||||
* }</pre>
|
||||
@@ -6135,39 +6160,37 @@ 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>
|
||||
*
|
||||
* <p> An example that closes a "Sign up to the newsletter" dialog when it appears:
|
||||
* <pre>{@code
|
||||
* // Setup the handler.
|
||||
* page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () => {
|
||||
* page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () -> {
|
||||
* page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("No thanks")).click();
|
||||
* });
|
||||
*
|
||||
* // Write the test as usual.
|
||||
* page.goto("https://example.com");
|
||||
* page.navigate("https://example.com");
|
||||
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
|
||||
* }</pre>
|
||||
*
|
||||
* <p> An example that skips the "Confirm your security details" page when it is shown:
|
||||
* <pre>{@code
|
||||
* // Setup the handler.
|
||||
* page.addLocatorHandler(page.getByText("Confirm your security details")), () => {
|
||||
* page.addLocatorHandler(page.getByText("Confirm your security details"), () -> {
|
||||
* page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Remind me later")).click();
|
||||
* });
|
||||
*
|
||||
* // Write the test as usual.
|
||||
* page.goto("https://example.com");
|
||||
* page.navigate("https://example.com");
|
||||
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
|
||||
* }</pre>
|
||||
*
|
||||
@@ -6176,19 +6199,19 @@ public interface Page extends AutoCloseable {
|
||||
* handler does not hide the {@code <body>} element.
|
||||
* <pre>{@code
|
||||
* // Setup the handler.
|
||||
* page.addLocatorHandler(page.locator("body")), () => {
|
||||
* page.addLocatorHandler(page.locator("body"), () -> {
|
||||
* page.evaluate("window.removeObstructionsForTestIfNeeded()");
|
||||
* }, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true));
|
||||
* }, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true));
|
||||
*
|
||||
* // Write the test as usual.
|
||||
* page.goto("https://example.com");
|
||||
* page.navigate("https://example.com");
|
||||
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Handler takes the original locator as an argument. You can also automatically remove the handler after a number of
|
||||
* invocations by setting {@code times}:
|
||||
* <pre>{@code
|
||||
* page.addLocatorHandler(page.getByLabel("Close"), locator => {
|
||||
* page.addLocatorHandler(page.getByLabel("Close"), locator -> {
|
||||
* locator.click();
|
||||
* }, new Page.AddLocatorHandlerOptions().setTimes(1));
|
||||
* }</pre>
|
||||
@@ -6240,7 +6263,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 +6322,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 +6379,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 +6438,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 +6495,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 +6554,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 +6608,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 +6623,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(frame -> {
|
||||
* if ("request".equals(frame.text()))
|
||||
* 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(frame -> {
|
||||
* if ("request".equals(frame.text()))
|
||||
* 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(frame -> {
|
||||
* if ("request".equals(frame.text()))
|
||||
* 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 +7354,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
|
||||
@@ -363,10 +363,12 @@ public interface Route {
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
*
|
||||
* <p> Note that any overrides such as {@code url} or {@code headers} only apply to the request being routed. If this request
|
||||
* results in a redirect, overrides will not be applied to the new redirected request. If you want to propagate a header
|
||||
* 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> The {@code headers} option applies to both the routed request and any redirects it initiates. However, {@code url},
|
||||
* {@code method}, and {@code postData} only apply to the original request and are not carried over to redirected requests.
|
||||
*
|
||||
* <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
|
||||
*/
|
||||
@@ -374,7 +376,7 @@ public interface Route {
|
||||
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
|
||||
@@ -389,21 +391,26 @@ public interface Route {
|
||||
*
|
||||
* <p> <strong>Details</strong>
|
||||
*
|
||||
* <p> Note that any overrides such as {@code url} or {@code headers} only apply to the request being routed. If this request
|
||||
* results in a redirect, overrides will not be applied to the new redirected request. If you want to propagate a header
|
||||
* 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> The {@code headers} option applies to both the routed request and any redirects it initiates. However, {@code url},
|
||||
* {@code method}, and {@code postData} only apply to the original request and are not carried over to redirected requests.
|
||||
*
|
||||
* <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 +464,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 +535,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);
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package com.microsoft.playwright;
|
||||
|
||||
import com.microsoft.playwright.options.*;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
@@ -39,8 +40,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 +70,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 +116,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 +128,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) {
|
||||
@@ -143,6 +144,29 @@ public interface Tracing {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class GroupOptions {
|
||||
/**
|
||||
* Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the {@link
|
||||
* com.microsoft.playwright.Tracing#group Tracing.group()} call.
|
||||
*/
|
||||
public Location location;
|
||||
|
||||
/**
|
||||
* Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the {@link
|
||||
* com.microsoft.playwright.Tracing#group Tracing.group()} call.
|
||||
*/
|
||||
public GroupOptions setLocation(String file) {
|
||||
return setLocation(new Location(file));
|
||||
}
|
||||
/**
|
||||
* Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the {@link
|
||||
* com.microsoft.playwright.Tracing#group Tracing.group()} call.
|
||||
*/
|
||||
public GroupOptions setLocation(Location location) {
|
||||
this.location = location;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class StopOptions {
|
||||
/**
|
||||
* Export trace into the file with the given path.
|
||||
@@ -271,6 +295,56 @@ public interface Tracing {
|
||||
* @since v1.15
|
||||
*/
|
||||
void startChunk(StartChunkOptions options);
|
||||
/**
|
||||
* <strong>NOTE:</strong> Use {@code test.step} instead when available.
|
||||
*
|
||||
* <p> Creates a new group within the trace, assigning any subsequent API calls to this group, until {@link
|
||||
* com.microsoft.playwright.Tracing#groupEnd Tracing.groupEnd()} is called. Groups can be nested and will be visible in the
|
||||
* trace viewer.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* // All actions between group and groupEnd
|
||||
* // will be shown in the trace viewer as a group.
|
||||
* page.context().tracing.group("Open Playwright.dev > API");
|
||||
* page.navigate("https://playwright.dev/");
|
||||
* page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("API")).click();
|
||||
* page.context().tracing.groupEnd();
|
||||
* }</pre>
|
||||
*
|
||||
* @param name Group name shown in the trace viewer.
|
||||
* @since v1.49
|
||||
*/
|
||||
default void group(String name) {
|
||||
group(name, null);
|
||||
}
|
||||
/**
|
||||
* <strong>NOTE:</strong> Use {@code test.step} instead when available.
|
||||
*
|
||||
* <p> Creates a new group within the trace, assigning any subsequent API calls to this group, until {@link
|
||||
* com.microsoft.playwright.Tracing#groupEnd Tracing.groupEnd()} is called. Groups can be nested and will be visible in the
|
||||
* trace viewer.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* // All actions between group and groupEnd
|
||||
* // will be shown in the trace viewer as a group.
|
||||
* page.context().tracing.group("Open Playwright.dev > API");
|
||||
* page.navigate("https://playwright.dev/");
|
||||
* page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("API")).click();
|
||||
* page.context().tracing.groupEnd();
|
||||
* }</pre>
|
||||
*
|
||||
* @param name Group name shown in the trace viewer.
|
||||
* @since v1.49
|
||||
*/
|
||||
void group(String name, GroupOptions options);
|
||||
/**
|
||||
* Closes the last group created by {@link com.microsoft.playwright.Tracing#group Tracing.group()}.
|
||||
*
|
||||
* @since v1.49
|
||||
*/
|
||||
void groupEnd();
|
||||
/**
|
||||
* Stop tracing.
|
||||
*
|
||||
|
||||
@@ -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(frame -> {
|
||||
* if ("request".equals(frame.text()))
|
||||
* 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(frame -> {
|
||||
* JsonObject json = new JsonParser().parse(frame.text()).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(frame -> {
|
||||
* if ("request".equals(frame.text()))
|
||||
* server.send("request2");
|
||||
* else
|
||||
* server.send(frame.text());
|
||||
* });
|
||||
* });
|
||||
* }</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(frame -> {
|
||||
* if (!"blocked-from-the-page".equals(frame.text()))
|
||||
* server.send(frame.text());
|
||||
* });
|
||||
* server.onMessage(frame -> {
|
||||
* if (!"blocked-from-the-server".equals(frame.text()))
|
||||
* ws.send(frame.text());
|
||||
* });
|
||||
* });
|
||||
* }</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();
|
||||
}
|
||||
|
||||
+4
-4
@@ -21,15 +21,15 @@ package com.microsoft.playwright.assertions;
|
||||
* The {@code APIResponseAssertions} class provides assertion methods that can be used to make assertions about the {@code
|
||||
* APIResponse} in the tests.
|
||||
* <pre>{@code
|
||||
* ...
|
||||
* // ...
|
||||
* import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
|
||||
*
|
||||
* public class TestPage {
|
||||
* ...
|
||||
* // ...
|
||||
* @Test
|
||||
* void navigatesToLoginPage() {
|
||||
* ...
|
||||
* APIResponse response = page.request().get('https://playwright.dev');
|
||||
* // ...
|
||||
* APIResponse response = page.request().get("https://playwright.dev");
|
||||
* assertThat(response).isOK();
|
||||
* }
|
||||
* }
|
||||
|
||||
+55
-7
@@ -23,14 +23,14 @@ import com.microsoft.playwright.options.AriaRole;
|
||||
* The {@code LocatorAssertions} class provides assertion methods that can be used to make assertions about the {@code
|
||||
* Locator} state in the tests.
|
||||
* <pre>{@code
|
||||
* ...
|
||||
* // ...
|
||||
* import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
|
||||
*
|
||||
* public class TestLocator {
|
||||
* ...
|
||||
* // ...
|
||||
* @Test
|
||||
* void statusBecomesSubmitted() {
|
||||
* ...
|
||||
* // ...
|
||||
* page.getByRole(AriaRole.BUTTON).click();
|
||||
* assertThat(page.locator(".status")).hasText("Submitted");
|
||||
* }
|
||||
@@ -485,6 +485,20 @@ public interface LocatorAssertions {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class MatchesAriaSnapshotOptions {
|
||||
/**
|
||||
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
|
||||
*/
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
|
||||
*/
|
||||
public MatchesAriaSnapshotOptions setTimeout(double timeout) {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Makes the assertion check for the opposite condition. For example, this code tests that the Locator doesn't contain text
|
||||
* {@code "error"}:
|
||||
@@ -2097,7 +2111,7 @@ public interface LocatorAssertions {
|
||||
*
|
||||
* <p> For example, given the following element:
|
||||
* <pre>{@code
|
||||
* page.locator("id=favorite-colors").selectOption(["R", "G"]);
|
||||
* page.locator("id=favorite-colors").selectOption(new String[]{"R", "G"});
|
||||
* assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
|
||||
* }</pre>
|
||||
*
|
||||
@@ -2115,7 +2129,7 @@ public interface LocatorAssertions {
|
||||
*
|
||||
* <p> For example, given the following element:
|
||||
* <pre>{@code
|
||||
* page.locator("id=favorite-colors").selectOption(["R", "G"]);
|
||||
* page.locator("id=favorite-colors").selectOption(new String[]{"R", "G"});
|
||||
* assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
|
||||
* }</pre>
|
||||
*
|
||||
@@ -2131,7 +2145,7 @@ public interface LocatorAssertions {
|
||||
*
|
||||
* <p> For example, given the following element:
|
||||
* <pre>{@code
|
||||
* page.locator("id=favorite-colors").selectOption(["R", "G"]);
|
||||
* page.locator("id=favorite-colors").selectOption(new String[]{"R", "G"});
|
||||
* assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
|
||||
* }</pre>
|
||||
*
|
||||
@@ -2149,7 +2163,7 @@ public interface LocatorAssertions {
|
||||
*
|
||||
* <p> For example, given the following element:
|
||||
* <pre>{@code
|
||||
* page.locator("id=favorite-colors").selectOption(["R", "G"]);
|
||||
* page.locator("id=favorite-colors").selectOption(new String[]{"R", "G"});
|
||||
* assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
|
||||
* }</pre>
|
||||
*
|
||||
@@ -2157,5 +2171,39 @@ public interface LocatorAssertions {
|
||||
* @since v1.23
|
||||
*/
|
||||
void hasValues(Pattern[] values, HasValuesOptions options);
|
||||
/**
|
||||
* Asserts that the target element matches the given <a
|
||||
* href="https://playwright.dev/java/docs/aria-snapshots">accessibility snapshot</a>.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.navigate("https://demo.playwright.dev/todomvc/");
|
||||
* assertThat(page.locator("body")).matchesAriaSnapshot("""
|
||||
* - heading "todos"
|
||||
* - textbox "What needs to be done?"
|
||||
* """);
|
||||
* }</pre>
|
||||
*
|
||||
* @since v1.49
|
||||
*/
|
||||
default void matchesAriaSnapshot(String expected) {
|
||||
matchesAriaSnapshot(expected, null);
|
||||
}
|
||||
/**
|
||||
* Asserts that the target element matches the given <a
|
||||
* href="https://playwright.dev/java/docs/aria-snapshots">accessibility snapshot</a>.
|
||||
*
|
||||
* <p> <strong>Usage</strong>
|
||||
* <pre>{@code
|
||||
* page.navigate("https://demo.playwright.dev/todomvc/");
|
||||
* assertThat(page.locator("body")).matchesAriaSnapshot("""
|
||||
* - heading "todos"
|
||||
* - textbox "What needs to be done?"
|
||||
* """);
|
||||
* }</pre>
|
||||
*
|
||||
* @since v1.49
|
||||
*/
|
||||
void matchesAriaSnapshot(String expected, MatchesAriaSnapshotOptions options);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,14 +22,14 @@ import java.util.regex.Pattern;
|
||||
* The {@code PageAssertions} class provides assertion methods that can be used to make assertions about the {@code Page}
|
||||
* state in the tests.
|
||||
* <pre>{@code
|
||||
* ...
|
||||
* // ...
|
||||
* import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
|
||||
*
|
||||
* public class TestPage {
|
||||
* ...
|
||||
* // ...
|
||||
* @Test
|
||||
* void navigatesToLoginPage() {
|
||||
* ...
|
||||
* // ...
|
||||
* page.getByText("Sign in").click();
|
||||
* assertThat(page).hasURL(Pattern.compile(".*\/login"));
|
||||
* }
|
||||
|
||||
+2
-3
@@ -30,14 +30,13 @@ import com.microsoft.playwright.impl.PageAssertionsImpl;
|
||||
*
|
||||
* <p> Consider the following example:
|
||||
* <pre>{@code
|
||||
* ...
|
||||
* import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
|
||||
*
|
||||
* public class TestExample {
|
||||
* ...
|
||||
* // ...
|
||||
* @Test
|
||||
* void statusBecomesSubmitted() {
|
||||
* ...
|
||||
* // ...
|
||||
* page.locator("#submit-button").click();
|
||||
* assertThat(page.locator(".status")).hasText("Submitted");
|
||||
* }
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -326,6 +326,16 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
expectImpl("to.have.values", list, patterns, "Locator expected to have values matching regex", convertType(options, FrameExpectOptions.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void matchesAriaSnapshot(String expected, MatchesAriaSnapshotOptions snapshotOptions) {
|
||||
if (snapshotOptions == null) {
|
||||
snapshotOptions = new MatchesAriaSnapshotOptions();
|
||||
}
|
||||
FrameExpectOptions options = convertType(snapshotOptions, FrameExpectOptions.class);
|
||||
options.expectedValue = serializeArgument(expected);
|
||||
expectImpl("to.match.aria", options, expected,"Locator expected to match Aria snapshot");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void isChecked(IsCheckedOptions options) {
|
||||
boolean unchecked = options != null && options.checked != null && !options.checked;
|
||||
|
||||
@@ -119,6 +119,21 @@ class LocatorImpl implements Locator {
|
||||
return new LocatorImpl(frame, selector + " >> internal:and=" + gson().toJson(other.selector), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String ariaSnapshot(AriaSnapshotOptions options) {
|
||||
return frame.withLogging("Locator.ariaSnapshot", () -> ariaSnapshotImpl(options));
|
||||
}
|
||||
|
||||
private String ariaSnapshotImpl(AriaSnapshotOptions options) {
|
||||
if (options == null) {
|
||||
options = new AriaSnapshotOptions();
|
||||
}
|
||||
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
|
||||
params.addProperty("selector", selector);
|
||||
JsonObject result = frame.sendMessage("ariaSnapshot", params).getAsJsonObject();
|
||||
return result.get("snapshot").getAsString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void blur(BlurOptions options) {
|
||||
frame.withLogging("Locator.blur", () -> blurImpl(options));
|
||||
@@ -650,9 +665,6 @@ class LocatorImpl implements Locator {
|
||||
}
|
||||
|
||||
private FrameExpectResult expectImpl(String expression, FrameExpectOptions options) {
|
||||
if (options == null) {
|
||||
options = new FrameExpectOptions();
|
||||
}
|
||||
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
|
||||
params.addProperty("selector", selector);
|
||||
params.addProperty("expression", expression);
|
||||
|
||||
@@ -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) {
|
||||
@@ -85,6 +86,25 @@ class TracingImpl extends ChannelOwner implements Tracing {
|
||||
tracingStartChunk(options.name, options.title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void group(String name, GroupOptions options) {
|
||||
withLogging("Tracing.group", () -> groupImpl(name, options));
|
||||
}
|
||||
|
||||
private void groupImpl(String name, GroupOptions options) {
|
||||
if (options == null) {
|
||||
options = new GroupOptions();
|
||||
}
|
||||
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
|
||||
params.addProperty("name", name);
|
||||
sendMessage("tracingGroup", params);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void groupEnd() {
|
||||
withLogging("Tracing.groupEnd", () -> sendMessage("tracingGroupEnd"));
|
||||
}
|
||||
|
||||
private void tracingStartChunk(String name, String title) {
|
||||
JsonObject params = new JsonObject();
|
||||
if (name != null) {
|
||||
|
||||
@@ -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,187 @@
|
||||
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);
|
||||
markAsInternalType();
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
+97
-15
@@ -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).
|
||||
*/
|
||||
|
||||
@@ -23,7 +23,7 @@ import java.nio.file.Path;
|
||||
* The {@code FormData} is used create form data that is sent via {@code APIRequestContext}.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* .set("firstName", "John")
|
||||
* .set("lastName", "Doe")
|
||||
@@ -43,7 +43,7 @@ public interface FormData {
|
||||
* existing set of values.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .append("firstName", "John")
|
||||
@@ -70,7 +70,7 @@ public interface FormData {
|
||||
* existing set of values.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .append("firstName", "John")
|
||||
@@ -97,7 +97,7 @@ public interface FormData {
|
||||
* existing set of values.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .append("firstName", "John")
|
||||
@@ -124,7 +124,7 @@ public interface FormData {
|
||||
* existing set of values.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .append("firstName", "John")
|
||||
@@ -151,7 +151,7 @@ public interface FormData {
|
||||
* existing set of values.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .append("firstName", "John")
|
||||
@@ -179,7 +179,7 @@ public interface FormData {
|
||||
* Sets a field on the form. File values can be passed either as {@code Path} or as {@code FilePayload}.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .set("firstName", "John")
|
||||
@@ -200,7 +200,7 @@ public interface FormData {
|
||||
* Sets a field on the form. File values can be passed either as {@code Path} or as {@code FilePayload}.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .set("firstName", "John")
|
||||
@@ -221,7 +221,7 @@ public interface FormData {
|
||||
* Sets a field on the form. File values can be passed either as {@code Path} or as {@code FilePayload}.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .set("firstName", "John")
|
||||
@@ -242,7 +242,7 @@ public interface FormData {
|
||||
* Sets a field on the form. File values can be passed either as {@code Path} or as {@code FilePayload}.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .set("firstName", "John")
|
||||
@@ -263,7 +263,7 @@ public interface FormData {
|
||||
* Sets a field on the form. File values can be passed either as {@code Path} or as {@code FilePayload}.
|
||||
* <pre>{@code
|
||||
* import com.microsoft.playwright.options.FormData;
|
||||
* ...
|
||||
* // ...
|
||||
* FormData form = FormData.create()
|
||||
* // Only name and value are set.
|
||||
* .set("firstName", "John")
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* 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.options;
|
||||
|
||||
public class Location {
|
||||
public String file;
|
||||
public Integer line;
|
||||
public Integer column;
|
||||
|
||||
public Location(String file) {
|
||||
this.file = file;
|
||||
}
|
||||
public Location setLine(int line) {
|
||||
this.line = line;
|
||||
return this;
|
||||
}
|
||||
public Location setColumn(int column) {
|
||||
this.column = column;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+25
-7
@@ -16,6 +16,7 @@
|
||||
|
||||
package com.microsoft.playwright;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -49,7 +50,12 @@ public class TestBrowserContextCDPSession extends TestBase {
|
||||
cdpSession.send("Network.enable");
|
||||
|
||||
List<JsonElement> events = new ArrayList<>();
|
||||
cdpSession.on("Network.requestWillBeSent", events::add);
|
||||
cdpSession.on("Network.requestWillBeSent", (JsonObject jsonObject) -> {
|
||||
// Only register main request, ignore favicon requests.
|
||||
if ("Document".equals(jsonObject.get("type").getAsString())) {
|
||||
events.add(jsonObject);
|
||||
}
|
||||
});
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
|
||||
assertEquals(1, events.size());
|
||||
@@ -126,7 +132,7 @@ public class TestBrowserContextCDPSession extends TestBase {
|
||||
page.close();
|
||||
|
||||
PlaywrightException exception = assertThrows(PlaywrightException.class, session::detach);
|
||||
assertTrue(exception.getMessage().contains("Target page, context or browser has been closed"));
|
||||
assertTrue(exception.getMessage().contains("Target page, context or browser has been closed"), exception.getMessage());
|
||||
context.close();
|
||||
}
|
||||
|
||||
@@ -136,8 +142,14 @@ public class TestBrowserContextCDPSession extends TestBase {
|
||||
cdpSession.send("Network.enable");
|
||||
|
||||
List<JsonObject> events = new ArrayList<>();
|
||||
cdpSession.on("Network.requestWillBeSent", events::add);
|
||||
cdpSession.on("Network.requestWillBeSent", events::add);
|
||||
Consumer<JsonObject> listener1 = (JsonObject jsonObject) -> {
|
||||
// Only register main request, ignore favicon requests.
|
||||
if ("Document".equals(jsonObject.get("type").getAsString())) {
|
||||
events.add(jsonObject);
|
||||
}
|
||||
};
|
||||
cdpSession.on("Network.requestWillBeSent", listener1);
|
||||
cdpSession.on("Network.requestWillBeSent", listener1);
|
||||
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(2, events.size());
|
||||
@@ -149,9 +161,15 @@ public class TestBrowserContextCDPSession extends TestBase {
|
||||
cdpSession.send("Network.enable");
|
||||
|
||||
List<JsonObject> events = new ArrayList<>();
|
||||
Consumer<JsonObject> listener1 = events::add;
|
||||
Consumer<JsonObject> listener1 = (JsonObject jsonObject) -> {
|
||||
// Only register main request, ignore favicon requests.
|
||||
if ("Document".equals(jsonObject.get("type").getAsString())) {
|
||||
events.add(jsonObject);
|
||||
}
|
||||
};
|
||||
Consumer<JsonObject> listener2 = listener1::accept;
|
||||
cdpSession.on("Network.requestWillBeSent", listener1);
|
||||
cdpSession.on("Network.requestWillBeSent", events::add);
|
||||
cdpSession.on("Network.requestWillBeSent", listener2);
|
||||
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(2, events.size());
|
||||
@@ -160,6 +178,6 @@ public class TestBrowserContextCDPSession extends TestBase {
|
||||
events.clear();
|
||||
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(1, events.size());
|
||||
assertEquals(1, events.size(), new Gson().toJson(events));
|
||||
}
|
||||
}
|
||||
|
||||
+8
-3
@@ -25,13 +25,15 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestBrowserContextCredentials extends TestBase {
|
||||
|
||||
static boolean isChromiumHeadful() {
|
||||
return isChromium() && isHeadful();
|
||||
static boolean isChromiumHeadedLike() {
|
||||
// --headless=new, the default in all Chromium channels, is like headless.
|
||||
return isChromium() && (isHeadful() || getBrowserChannelFromEnv() != null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIf(value="isChromiumHeadful", disabledReason="fail")
|
||||
@DisabledIf(value="isChromiumHeadedLike", disabledReason="fail")
|
||||
void shouldFailWithoutCredentials() {
|
||||
System.out.println("channel2 " + getBrowserChannelFromEnv());
|
||||
server.setAuth("/empty.html", "user", "pass");
|
||||
Response response = page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(401, response.status());
|
||||
@@ -103,6 +105,7 @@ public class TestBrowserContextCredentials extends TestBase {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIf(value="isChromiumHeadedLike", disabledReason="fail")
|
||||
void shouldFailWithCorrectCredentialsAndWrongOriginScheme() {
|
||||
server.setAuth("/empty.html", "user", "pass");
|
||||
final HttpCredentials httpCredentials = new HttpCredentials("user", "pass");
|
||||
@@ -115,6 +118,7 @@ public class TestBrowserContextCredentials extends TestBase {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIf(value="isChromiumHeadedLike", disabledReason="fail")
|
||||
void shouldFailWithCorrectCredentialsAndWrongOriginHostname() {
|
||||
server.setAuth("/empty.html", "user", "pass");
|
||||
final HttpCredentials httpCredentials = new HttpCredentials("user", "pass");
|
||||
@@ -127,6 +131,7 @@ public class TestBrowserContextCredentials extends TestBase {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIf(value="isChromiumHeadedLike", disabledReason="fail")
|
||||
void shouldFailWithCorrectCredentialsAndWrongOriginPort() {
|
||||
server.setAuth("/empty.html", "user", "pass");
|
||||
final HttpCredentials httpCredentials = new HttpCredentials("user", "pass");
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.microsoft.playwright;
|
||||
|
||||
import com.microsoft.playwright.junit.FixtureTest;
|
||||
import com.microsoft.playwright.junit.UsePlaywright;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@FixtureTest
|
||||
@UsePlaywright
|
||||
public class TestPageAriaSnapshot {
|
||||
public static String unshift(String snapshot) {
|
||||
List<String> lines = Arrays.asList(snapshot.split("\n"));
|
||||
int whitespacePrefixLength = 100;
|
||||
Pattern pattern = Pattern.compile("^(\\s*).*");
|
||||
for (String line : lines) {
|
||||
if (line.trim().isEmpty())
|
||||
continue;
|
||||
Matcher matcher = pattern.matcher(line);
|
||||
if (!matcher.matches()) {
|
||||
continue;
|
||||
}
|
||||
String match = matcher.group(1);
|
||||
if (match.length() < whitespacePrefixLength) {
|
||||
whitespacePrefixLength = match.length();
|
||||
}
|
||||
}
|
||||
final int prefixLength = whitespacePrefixLength;
|
||||
return lines.stream()
|
||||
.filter(line -> !line.trim().isEmpty())
|
||||
.map(line -> line.substring(prefixLength))
|
||||
.collect(Collectors.joining("\n"));
|
||||
}
|
||||
|
||||
private static void checkAndMatchSnapshot(Locator locator, String snapshot) {
|
||||
assertEquals(unshift(snapshot), locator.ariaSnapshot());
|
||||
assertThat(locator).matchesAriaSnapshot(snapshot);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSnapshot(Page page) {
|
||||
page.setContent("<h1>title</h1>");
|
||||
checkAndMatchSnapshot(page.locator("body"), "- heading \"title\" [level=1]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSnapshotList(Page page) {
|
||||
page.setContent("<h1>title</h1><h1>title 2</h1>");
|
||||
checkAndMatchSnapshot(page.locator("body"), "" +
|
||||
" - heading \"title\" [level=1]\n" +
|
||||
" - heading \"title 2\" [level=1]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSnapshotListWithAccessibleName(Page page) {
|
||||
page.setContent("<ul aria-label=\"my list\"><li>one</li><li>two</li></ul>");
|
||||
checkAndMatchSnapshot(page.locator("body"), "- list \"my list\":\n - listitem: one\n - listitem: two");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSnapshotComplex(Page page) {
|
||||
page.setContent("<ul><li><a href='about:blank'>link</a></li></ul>");
|
||||
checkAndMatchSnapshot(page.locator("body"), "- list:\n - listitem:\n - link \"link\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAllowTextNodes(Page page) {
|
||||
page.setContent("<h1>Microsoft</h1><div>Open source projects and samples from Microsoft</div>");
|
||||
checkAndMatchSnapshot(page.locator("body"), "" +
|
||||
" - heading \"Microsoft\" [level=1]\n" +
|
||||
" - text: Open source projects and samples from Microsoft");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSnapshotDetailsVisibility(Page page) {
|
||||
page.setContent("<details><summary>Summary</summary><div>Details</div></details>");
|
||||
checkAndMatchSnapshot(page.locator("body"), "- group: Summary");
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,8 +290,9 @@ public class TestPageClock {
|
||||
Page popup = page.waitForPopup(() -> {
|
||||
page.evaluate("url => window.open(url)", server.PREFIX + "/popup.html");
|
||||
});
|
||||
popup.waitForURL(server.PREFIX + "/popup.html");
|
||||
Double popupTime = (Double) popup.evaluate("time");
|
||||
assertTrue(popupTime >= 2000);
|
||||
assertTrue(popupTime >= 2000, "popupTime = " + popupTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -310,6 +311,7 @@ public class TestPageClock {
|
||||
Page popup = page.waitForPopup(() -> {
|
||||
page.evaluate("url => window.open(url)", server.PREFIX + "/popup.html");
|
||||
});
|
||||
popup.waitForURL(server.PREFIX + "/popup.html");
|
||||
Object popupTime = popup.evaluate("time");
|
||||
assertEquals(1000, popupTime);
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@
|
||||
|
||||
package com.microsoft.playwright;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.microsoft.playwright.options.Location;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -26,12 +29,14 @@ import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestTracing extends TestBase {
|
||||
@Override
|
||||
@@ -154,4 +159,68 @@ public class TestTracing extends TestBase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void canCallTracingGroupGroupEndAtAnyTimeAndAutoClose(@TempDir Path tempDir) throws Exception {
|
||||
context.tracing().group("ignored");
|
||||
context.tracing().groupEnd();
|
||||
context.tracing().group("ignored2");
|
||||
|
||||
context.tracing().start(new Tracing.StartOptions());
|
||||
context.tracing().group("actual");
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
Path traceFile1 = tempDir.resolve("trace1.zip");
|
||||
context.tracing().stopChunk(new Tracing.StopChunkOptions().setPath(traceFile1));
|
||||
|
||||
context.tracing().group("ignored3");
|
||||
context.tracing().groupEnd();
|
||||
context.tracing().groupEnd();
|
||||
context.tracing().groupEnd();
|
||||
|
||||
List<TraceEvent> events = parseTraceEvents(traceFile1);
|
||||
List<TraceEvent> groups = events.stream().filter(e -> "tracingGroup".equals(e.method)).collect(Collectors.toList());
|
||||
assertEquals(1, groups.size());
|
||||
assertEquals("actual", groups.get(0).apiName);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void traceGroupGroupEnd(@TempDir Path tempDir) throws Exception {
|
||||
context.tracing().start(new Tracing.StartOptions());
|
||||
context.tracing().group("outer group");
|
||||
page.navigate("data:text/html,<!DOCTYPE html><body><div>Hello world</div></body>");
|
||||
context.tracing().group("inner group 1", new Tracing.GroupOptions().setLocation(new Location("foo.java").setLine(17).setColumn(1)));
|
||||
page.locator("body").click();
|
||||
context.tracing().groupEnd();
|
||||
context.tracing().group("inner group 2");
|
||||
assertTrue(page.locator("text=Hello").isVisible());
|
||||
context.tracing().groupEnd();
|
||||
context.tracing().groupEnd();
|
||||
|
||||
Path traceFile1 = tempDir.resolve("trace1.zip");
|
||||
context.tracing().stop(new Tracing.StopOptions().setPath(traceFile1));
|
||||
|
||||
List<TraceEvent> events = parseTraceEvents(traceFile1);
|
||||
List<String> calls = events.stream().filter(e -> e.apiName != null).map(e -> e.apiName).collect(Collectors.toList());
|
||||
assertEquals(asList("outer group", "Page.navigate", "inner group 1", "Frame.click", "inner group 2", "Page.isVisible"), calls);
|
||||
}
|
||||
|
||||
private static class TraceEvent {
|
||||
String type;
|
||||
String name;
|
||||
String apiName;
|
||||
String method;
|
||||
Double startTime;
|
||||
Double endTime;
|
||||
String callId;
|
||||
}
|
||||
|
||||
private static List<TraceEvent> parseTraceEvents(Path traceFile) throws IOException {
|
||||
Map<String, byte[]> files = Utils.parseZip(traceFile);
|
||||
Map<String, byte[]> traces = files.entrySet().stream().filter(e -> e.getKey().endsWith(".trace")).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
assertNotNull(traces.get("trace.trace"));
|
||||
return Arrays.stream(new String(traces.get("trace.trace"), UTF_8)
|
||||
.split("\n"))
|
||||
.map(s -> new Gson().fromJson(s, TraceEvent.class))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>parent-pom</artifactId>
|
||||
<version>1.46.0</version>
|
||||
<version>1.49.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.3</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.1</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 @@
|
||||
1.46.0
|
||||
1.49.0
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>api-generator</artifactId>
|
||||
<version>1.46.0</version>
|
||||
<version>1.49.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()) {
|
||||
@@ -974,7 +986,7 @@ class Interface extends TypeDefinition {
|
||||
if (methods.stream().anyMatch(m -> "create".equals(m.jsonName))) {
|
||||
output.add("import com.microsoft.playwright.impl." + jsonName + "Impl;");
|
||||
}
|
||||
if (asList("Page", "Request", "Response", "APIRequestContext", "APIRequest", "APIResponse", "FileChooser", "Frame", "FrameLocator", "ElementHandle", "Locator", "Browser", "BrowserContext", "BrowserType", "Mouse", "Keyboard").contains(jsonName)) {
|
||||
if (asList("Page", "Request", "Response", "APIRequestContext", "APIRequest", "APIResponse", "FileChooser", "Frame", "FrameLocator", "ElementHandle", "Locator", "Browser", "BrowserContext", "BrowserType", "Mouse", "Keyboard", "Tracing").contains(jsonName)) {
|
||||
output.add("import com.microsoft.playwright.options.*;");
|
||||
}
|
||||
if ("Download".equals(jsonName)) {
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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.49.0</version>
|
||||
<name>Test Playwright Command Line FatJar</name>
|
||||
<properties>
|
||||
<compiler.version>1.8</compiler.version>
|
||||
|
||||
@@ -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.49.0</version>
|
||||
<name>Test Playwright Command Line Version</name>
|
||||
<properties>
|
||||
<compiler.version>1.8</compiler.version>
|
||||
|
||||
@@ -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.49.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>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
</parent>
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>test-spring-boot-starter</artifactId>
|
||||
<version>1.46.0</version>
|
||||
<version>1.49.0</version>
|
||||
<name>Test Playwright With Spring Boot</name>
|
||||
<properties>
|
||||
<spring.version>2.4.3</spring.version>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>update-version</artifactId>
|
||||
<version>1.46.0</version>
|
||||
<version>1.49.0</version>
|
||||
<name>Playwright - Update Version in Documentation</name>
|
||||
<description>
|
||||
This is an internal module used to update versions in the documentation based on
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
FROM ubuntu:focal
|
||||
FROM ubuntu:noble
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ARG TZ=America/Los_Angeles
|
||||
ARG DOCKER_IMAGE_NAME_TEMPLATE="mcr.microsoft.com/playwright/java:v%version%-focal"
|
||||
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
|
||||
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
|
||||
@@ -3,12 +3,12 @@ set -e
|
||||
set +x
|
||||
|
||||
if [[ ($1 == '--help') || ($1 == '-h') || ($1 == '') || ($2 == '') ]]; then
|
||||
echo "usage: $(basename $0) {--arm64,--amd64} {focal,jammy} playwright:localbuild-focal"
|
||||
echo "usage: $(basename $0) {--arm64,--amd64} {jammy,noble} playwright:localbuild-noble"
|
||||
echo
|
||||
echo "Build Playwright docker image and tag it as 'playwright:localbuild-focal'."
|
||||
echo "Build Playwright docker image and tag it as 'playwright:localbuild-noble'."
|
||||
echo "Once image is built, you can run it with"
|
||||
echo ""
|
||||
echo " docker run --rm -it playwright:localbuild-focal /bin/bash"
|
||||
echo " docker run --rm -it playwright:localbuild-noble /bin/bash"
|
||||
echo ""
|
||||
echo "NOTE: this requires on Playwright PIP dependencies to be installed"
|
||||
echo ""
|
||||
|
||||
@@ -21,34 +21,22 @@ 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
|
||||
|
||||
FOCAL_TAGS=(
|
||||
"next-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"
|
||||
@@ -82,12 +70,12 @@ install_oras_if_needed() {
|
||||
publish_docker_images_with_arch_suffix() {
|
||||
local FLAVOR="$1"
|
||||
local TAGS=()
|
||||
if [[ "$FLAVOR" == "focal" ]]; then
|
||||
TAGS=("${FOCAL_TAGS[@]}")
|
||||
elif [[ "$FLAVOR" == "jammy" ]]; then
|
||||
if [[ "$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 'jammy', or 'noble'"
|
||||
exit 1
|
||||
fi
|
||||
local ARCH="$2"
|
||||
@@ -108,12 +96,12 @@ publish_docker_images_with_arch_suffix() {
|
||||
publish_docker_manifest () {
|
||||
local FLAVOR="$1"
|
||||
local TAGS=()
|
||||
if [[ "$FLAVOR" == "focal" ]]; then
|
||||
TAGS=("${FOCAL_TAGS[@]}")
|
||||
elif [[ "$FLAVOR" == "jammy" ]]; then
|
||||
if [[ "$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 'jammy', 'noble'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -132,10 +120,10 @@ publish_docker_manifest () {
|
||||
done
|
||||
}
|
||||
|
||||
publish_docker_images_with_arch_suffix focal amd64
|
||||
publish_docker_images_with_arch_suffix focal arm64
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user