1
0
mirror of synced 2026-05-23 11:13:15 +00:00

Compare commits

..

51 Commits

Author SHA1 Message Date
Yury Semikhatsky ea48985e21 chore: set version to 1.48.0 (#1688) 2024-10-17 12:35:16 -07:00
Yury Semikhatsky 20b13ad0c0 chore: roll driver 1.48.1 (#1687) 2024-10-17 12:06:13 -07:00
dependabot[bot] 08ac52ca53 chore(deps): bump the all group with 4 updates (#1680) 2024-10-17 11:56:19 -07:00
Yury Semikhatsky 9c220cd359 test: update web socket tests to properly dispatch ws messages (#1683) 2024-10-03 11:19:15 -07:00
Yury Semikhatsky ab443d1638 chore: roll 1.48 beta driver (#1681) 2024-10-02 14:21:13 -07:00
Max Schmitt 186aede95c devops: use wget for driver downloads (#1679) 2024-10-01 09:39:38 +02:00
Yury Semikhatsky db52fa94e7 docs: remove snapshot badge from README 2024-09-12 17:04:25 -07:00
Yury Semikhatsky ee18e1a499 chore: roll 1.47.0-beta-1726138322000 (#1672) 2024-09-12 15:02:49 -07:00
Yury Semikhatsky 9cf4bf2263 docs: Update ROLLING.md with new roll script 2024-09-12 12:03:29 -07:00
Yury Semikhatsky 36350f3c5c chore: roll 1.47.0 (#1670) 2024-09-09 11:06:17 -07:00
Max Schmitt f3476c68ff test: fix client-certificate tests (#1669) 2024-09-09 09:05:37 -07:00
Max Schmitt 8fd8f1c831 test: remove per-context proxy hacks for Windows/Chromium (#1668) 2024-09-09 10:09:00 +02:00
dependabot[bot] 7d2066693b chore(deps): bump the all group with 2 updates (#1664) 2024-09-03 08:55:04 -07:00
Yury Semikhatsky 6b01b878cb chore: roll driver to 1.47.0 alpha 2024 08 28 (#1663) 2024-08-28 16:02:34 -07:00
uchagani 2e32eb704f feat(junit): Implement automatic saving of traces and screenshots via fixtures (#1560) 2024-08-28 13:52:07 -07:00
Chris Kocel b81b144680 fix: null check in ListenerCollection notify method (#1661) 2024-08-28 13:50:55 -07:00
Yury Semikhatsky 256e41a505 docs: add SUPPORT.md (#1662) 2024-08-28 11:09:38 -07:00
Yury Semikhatsky 3054364101 devops(dependabot): update all deps in single PR monthly (#1656) 2024-08-19 13:21:31 -07:00
dependabot[bot] 40b8802874 chore(deps): bump org.apache.maven.plugins:maven-deploy-plugin from 3.1.2 to 3.1.3 (#1654) 2024-08-19 12:11:29 -07:00
dependabot[bot] 49f53fceaf chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin from 3.3.1 to 3.4.0 (#1653) 2024-08-19 12:11:13 -07:00
dependabot[bot] 291c12a54c chore(deps): bump org.apache.maven.plugins:maven-install-plugin from 3.1.2 to 3.1.3 (#1655) 2024-08-19 12:11:01 -07:00
dependabot[bot] 2b3413fad4 chore(deps): bump junit.version from 5.10.3 to 5.11.0 (#1652) 2024-08-19 11:16:59 -07:00
dependabot[bot] 3eab530e95 chore(deps): bump org.apache.maven.plugins:maven-gpg-plugin from 3.2.4 to 3.2.5 (#1650) 2024-08-19 11:16:40 -07:00
Max Schmitt 7d35be4f89 devops: publish Ubuntu 24.04 Docker image (#1649) 2024-08-12 19:02:17 +02:00
Yury Semikhatsky 800c2e9c71 fix: support ControlOrMeta action modifier (#1644)
Fixes: https://github.com/microsoft/playwright-java/issues/1643
2024-08-07 17:08:33 -07:00
Meir Blachman edf8174581 docs: add discord link in readme (#1642) 2024-08-06 15:54:40 -07:00
Yury Semikhatsky 8ae67204eb test: disable failing certificate tests on webkit mac (#1641) 2024-08-06 13:08:26 -07:00
Yury Semikhatsky 5f2540e556 chore: roll driver to 1.46.0 (#1640) 2024-08-05 17:46:01 -07:00
Yury Semikhatsky 776e3f26ef chore: serizlize java Exception <==> javascript Error (#1639) 2024-08-02 10:32:18 -07:00
Yury Semikhatsky 46f4ac1f33 chore: roll driver to 1.46.0-beta (#1638) 2024-07-31 13:58:01 -07:00
dependabot[bot] 73d22552e6 chore(deps): bump org.apache.maven.plugins:maven-javadoc-plugin from 3.7.0 to 3.8.0 (#1631) 2024-07-23 15:03:57 -07:00
Thomas Fowler 650419c952 fix: Replaced println with logMessage in DriverJar (#1627) 2024-07-23 10:29:15 -07:00
dependabot[bot] 1e8adde480 chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin from 3.3.0 to 3.3.1 (#1625) 2024-07-15 13:45:23 -07:00
dependabot[bot] a9e1242aef chore(deps-dev): bump org.java-websocket:Java-WebSocket from 1.5.6 to 1.5.7 (#1626) 2024-07-15 13:45:11 -07:00
dependabot[bot] a222edee5a chore(deps): bump junit.version from 5.10.2 to 5.10.3 (#1616) 2024-07-11 08:59:14 -07:00
Yury Semikhatsky 7a12897be4 feat: support java.time.OffsetDateTime in post data (#1624)
Fixes https://github.com/microsoft/playwright-java/issues/1623
2024-07-11 08:58:46 -07:00
Yury Semikhatsky 7fa8081032 devops: test on java 21 which is latest lts (#1613) 2024-06-27 14:37:55 -07:00
Yury Semikhatsky 212bf981f7 chore: bump dev version to 1.46.0-SNAPSHOT (#1612) 2024-06-27 13:28:56 -07:00
Yury Semikhatsky d9ac70c66b chore: roll driver to 1.45.0-beta (#1610) 2024-06-27 13:22:47 -07:00
dependabot[bot] 4279a4ef3e chore(deps): bump org.apache.maven.plugins:maven-jar-plugin from 3.4.1 to 3.4.2 (#1604) 2024-06-27 10:15:05 -07:00
dependabot[bot] 141afb1f09 chore(deps): bump org.apache.maven.plugins:maven-clean-plugin from 3.3.2 to 3.4.0 (#1603) 2024-06-27 10:09:04 -07:00
dependabot[bot] 2eaae58659 chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin from 3.2.5 to 3.3.0 (#1599) 2024-06-27 10:08:52 -07:00
Yury Semikhatsky e4828d00b6 chore: roll 1.45.0 (#1609) 2024-06-25 09:18:12 -07:00
Yury Semikhatsky a08ab2dcae devops: roll_driver script (#1605) 2024-06-25 08:34:20 -07:00
Jason Wu 626050d988 fix: Update README.md to fix wrong demo code (#1601)
Update README.md to fix wrong demo code

In Mobile and geolocation demo, code `page.click("a[data-original-title=\"Show My Location\"]");` will cause error while running.Because the website already change the attribute.
2024-06-19 09:24:45 -07:00
Yury Semikhatsky 4cc3fa3012 chore: roll driver to 1.45.0 beta, implement new features (#1600) 2024-06-18 17:08:45 -07:00
dependabot[bot] 226d075355 chore(deps): bump org.apache.maven.plugins:maven-javadoc-plugin from 3.6.3 to 3.7.0 (#1589) 2024-06-03 15:42:10 -07:00
Yury Semikhatsky 0a759e699e fix(fetch): support json objects with null values (#1587)
Fixes https://github.com/microsoft/playwright-java/issues/1585
2024-05-30 14:46:17 -07:00
Yury Semikhatsky f2a17b6255 devops: install msedge on macosx (#1581) 2024-05-20 16:21:27 -07:00
dependabot[bot] 202bc80d76 chore(deps): bump com.google.code.gson:gson from 2.10.1 to 2.11.0 (#1580) 2024-05-20 16:07:03 -07:00
Yury Semikhatsky 731d8e8dc2 chore: bump dev version to 1.45.0-SNAPSHOT (#1579) 2024-05-17 09:12:49 -07:00
130 changed files with 4682 additions and 1075 deletions
+1 -1
View File
@@ -47,7 +47,7 @@ extends:
GPG_PRIVATE_KEY_BASE64: $(GPG_PRIVATE_KEY_BASE64) # secret variable has to be mapped to an env variable
displayName: "Import gpg key"
- bash: ./scripts/download_driver_for_all_platforms.sh
- bash: ./scripts/download_driver.sh
displayName: 'Download driver'
- bash: mvn -B deploy -D skipTests --no-transfer-progress --activate-profiles release -D gpg.passphrase=$GPG_PASSPHRASE -DaltDeploymentRepository=snapshot-repo::default::file:$(pwd)/local-build
+10 -1
View File
@@ -3,8 +3,17 @@ updates:
- package-ecosystem: "maven"
directory: "/" # Location of the pom.xml file
schedule:
interval: "weekly"
interval: "monthly"
open-pull-requests-limit: 10
groups:
# Create a group of dependencies to be updated together in one pull request
all:
applies-to: version-updates
patterns:
- "*"
update-types:
- "minor"
- "patch"
allow:
- dependency-type: "direct" # Optional: Only update direct dependencies
- dependency-type: "indirect" # Optional: Only update indirect (transitive) dependencies
-8
View File
@@ -3,11 +3,6 @@ on:
release:
types: [published]
workflow_dispatch:
inputs:
is_release:
required: true
type: boolean
description: "Is this a release image?"
jobs:
publish-canary-docker:
name: publish to DockerHub
@@ -33,6 +28,3 @@ jobs:
platforms: arm64
- uses: actions/checkout@v4
- run: ./utils/docker/publish_docker.sh stable
if: (github.event_name != 'workflow_dispatch' && !github.event.release.prerelease) || (github.event_name == 'workflow_dispatch' && github.event.inputs.is_release == 'true')
- run: ./utils/docker/publish_docker.sh canary
if: (github.event_name != 'workflow_dispatch' && github.event.release.prerelease) || (github.event_name == 'workflow_dispatch' && github.event.inputs.is_release != 'true')
+10 -6
View File
@@ -27,7 +27,7 @@ jobs:
java-version: 8
- name: Download drivers
shell: bash
run: scripts/download_driver_for_all_platforms.sh
run: scripts/download_driver.sh
- name: Build & Install
run: mvn -B install -D skipTests --no-transfer-progress
- name: Run tests
@@ -75,16 +75,20 @@ jobs:
java-version: 8
- name: Download drivers
shell: bash
run: scripts/download_driver_for_all_platforms.sh
run: scripts/download_driver.sh
- name: Build & Install
run: mvn -B install -D skipTests --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
- 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:
BROWSER: chromium
BROWSER_CHANNEL: ${{ matrix.browser-channel }}
Java_17:
Java_21:
timeout-minutes: 30
strategy:
fail-fast: false
@@ -94,14 +98,14 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: microsoft/playwright-github-action@v1
- name: Set up JDK 17
- name: Set up JDK 21
uses: actions/setup-java@v2
with:
distribution: adopt
java-version: 17
java-version: 21
- name: Download drivers
shell: bash
run: scripts/download_driver_for_all_platforms.sh
run: scripts/download_driver.sh
- name: Build & Install
run: mvn -B install -D skipTests --no-transfer-progress
- name: Run tests
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: Download drivers
run: scripts/download_driver_for_all_platforms.sh
run: scripts/download_driver.sh
- name: Intall Playwright
run: mvn install -D skipTests --no-transfer-progress
- name: Test CLI
+2 -2
View File
@@ -11,7 +11,7 @@ on:
paths:
- .github/workflows/test_docker.yml
- '**/Dockerfile*'
- scripts/CLI_VERSION
- scripts/DRIVER_VERSION
- '**/pom.xml'
branches:
- main
@@ -24,7 +24,7 @@ jobs:
strategy:
fail-fast: false
matrix:
flavor: [focal, jammy]
flavor: [focal, jammy, noble]
steps:
- uses: actions/checkout@v3
- name: Build Docker image
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
- uses: actions/checkout@v2
- uses: microsoft/playwright-github-action@v1
- name: Download drivers
run: scripts/download_driver_for_all_platforms.sh
run: scripts/download_driver.sh
- name: Regenerate APIs
run: scripts/generate_api.sh
- name: Update browser versions in README
+6 -14
View File
@@ -20,14 +20,12 @@ git clone https://github.com/microsoft/playwright-java
cd playwright-java
```
2. Run the following script to download playwright-cli binaries for all platforms into `driver-bundle/src/main/resources/driver/` directory (browser binaries for Chromium, Firefox and WebKit will be automatically downloaded later on first Playwright run).
2. Run the following script to download Playwright driver for all platforms into `driver-bundle/src/main/resources/driver/` directory (browser binaries for Chromium, Firefox and WebKit will be automatically downloaded later on first Playwright run).
```bash
scripts/download_driver_for_all_platforms.sh
scripts/download_driver.sh
```
Names of published driver archives can be found at https://github.com/microsoft/playwright-cli/actions
### Building and running the tests with Maven
```bash
@@ -41,25 +39,19 @@ BROWSER=chromium mvn test --projects=playwright -Dtest=TestPageNetworkSizes
### Generating API
Public Java API is generated from api.json which is produced by `playwright-cli print-api-json`. To regenerate
Java interfaces for the current driver run the following commands:
Public Java API is generated from api.json which is produced by `print-api-json` command of playwright CLI. To regenerate Java interfaces for the current driver run the following commands:
```bash
./scripts/download_driver_for_all_platforms.sh
./scripts/download_driver.sh
./scripts/generate_api.sh
```
#### Updating driver version
Driver version is read from [scripts/CLI_VERSION](https://github.com/microsoft/playwright-java/blob/main/scripts/CLI_VERSION) and can be found in the upstream [GHA build](https://github.com/microsoft/playwright/actions/workflows/publish_canary.yml) logs. To update the driver to a particular version run the following commands:
Versions of published driver archives can be found in [publish canary](https://github.com/microsoft/playwright/actions/workflows/publish_canary.yml) and [publish release](https://github.com/microsoft/playwright/actions/workflows/publish_release_driver.yml) actions logs. To update the driver to a particular version run the following command:
```bash
cat > scripts/CLI_VERSION
<paste new version>
^D
./scripts/download_driver_for_all_platforms.sh -f
./scripts/generate_api.sh
./scripts/update_readme.sh
scripts/roll_driver.sh [version]
```
### Code Style
+5 -6
View File
@@ -2,8 +2,7 @@
[![javadoc](https://javadoc.io/badge2/com.microsoft.playwright/playwright/javadoc.svg)](https://javadoc.io/doc/com.microsoft.playwright/playwright)
[![maven version](https://img.shields.io/maven-central/v/com.microsoft.playwright/playwright)](https://search.maven.org/search?q=com.microsoft.playwright)
[![Sonatype Nexus (Snapshots)](https://img.shields.io/nexus/s/https/oss.sonatype.org/com.microsoft.playwright/playwright.svg)](https://oss.sonatype.org/content/repositories/snapshots/com/microsoft/playwright/playwright/)
[![Join Slack](https://img.shields.io/badge/join-slack-infomational)](https://aka.ms/playwright-slack)
[![Join Discord](https://img.shields.io/badge/join-discord-infomational)](https://aka.ms/playwright/discord)
#### [Website](https://playwright.dev/java/) | [API reference](https://www.javadoc.io/doc/com.microsoft.playwright/playwright/latest/index.html)
@@ -11,9 +10,9 @@ Playwright is a Java library to automate [Chromium](https://www.chromium.org/Hom
| | Linux | macOS | Windows |
| :--- | :---: | :---: | :---: |
| Chromium <!-- GEN:chromium-version -->125.0.6422.26<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| WebKit <!-- GEN:webkit-version -->17.4<!-- GEN:stop --> | ✅ | ✅ | ✅ |
| Firefox <!-- GEN:firefox-version -->125.0.1<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Chromium <!-- GEN:chromium-version -->130.0.6723.31<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| WebKit <!-- GEN:webkit-version -->18.0<!-- GEN:stop --> | ✅ | ✅ | ✅ |
| Firefox <!-- GEN:firefox-version -->131.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Headless execution is supported for all the browsers on all platforms. Check out [system requirements](https://playwright.dev/java/docs/intro#system-requirements) for details.
@@ -122,7 +121,7 @@ public class MobileAndGeolocation {
.setPermissions(asList("geolocation")));
Page page = context.newPage();
page.navigate("https://www.openstreetmap.org/");
page.click("a[data-original-title=\"Show My Location\"]");
page.click("a[data-bs-original-title=\"Show My Location\"]");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("colosseum-pixel2.png")));
}
}
+2 -3
View File
@@ -2,11 +2,10 @@
* make sure to have at least Java 8 and Maven 3.6.3
* clone playwright for java: http://github.com/microsoft/playwright-java
* set new driver version in `scripts/CLI_VERSION`
* regenerate API: `./scripts/download_driver_for_all_platforms.sh -f && ./scripts/generate_api.sh && ./scripts/update_readme.sh`
* `./scripts/roll_driver.sh 1.47.0-beta-1726138322000`
* commit & send PR with the roll
### Finding driver version
## Finding driver version
For development versions of Playwright, you can find the latest version by looking at [publish_canary](https://github.com/microsoft/playwright/actions/workflows/publish_canary.yml) workflow -> `publish canary NPM & Publish canary Docker` -> `build & publish driver` step -> `PACKAGE_VERSION`
<img width="960" alt="image" src="https://github.com/microsoft/playwright-java/assets/9798949/4f33a7f1-b39a-4179-8ae7-fb1d84094c75">
+17
View File
@@ -0,0 +1,17 @@
# Support
## How to file issues and get help
This project uses GitHub issues to track bugs and feature requests. Please search the [existing issues][gh-issues] before filing new ones to avoid duplicates. For new issues, file your bug or feature request as a new issue using corresponding template.
For help and questions about using this project, please see the [docs site for Playwright for Java][docs].
Join our community [Discord Server][discord-server] to connect with other developers using Playwright and ask questions in our 'help-playwright' forum.
## Microsoft Support Policy
Support for Playwright for Java is limited to the resources listed above.
[gh-issues]: https://github.com/microsoft/playwright-java/issues/
[docs]: https://playwright.dev/java/
[discord-server]: https://aka.ms/playwright/discord
+1 -1
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>com.microsoft.playwright</groupId>
<artifactId>parent-pom</artifactId>
<version>1.44.0</version>
<version>1.48.0</version>
</parent>
<artifactId>driver-bundle</artifactId>
@@ -74,7 +74,7 @@ public class DriverJar extends Driver {
skip = System.getenv(PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD);
}
if (skip != null && !"0".equals(skip) && !"false".equals(skip)) {
System.out.println("Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set");
logMessage("Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set");
return;
}
if (env.get(SELENIUM_REMOTE_URL) != null || System.getenv(SELENIUM_REMOTE_URL) != null) {
+1 -1
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>com.microsoft.playwright</groupId>
<artifactId>parent-pom</artifactId>
<version>1.44.0</version>
<version>1.48.0</version>
</parent>
<artifactId>driver</artifactId>
+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>org.example</groupId>
<artifactId>examples</artifactId>
<version>1.44.0</version>
<version>1.48.0</version>
<name>Playwright Client Examples</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+5 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>com.microsoft.playwright</groupId>
<artifactId>parent-pom</artifactId>
<version>1.44.0</version>
<version>1.48.0</version>
</parent>
<artifactId>playwright</artifactId>
@@ -61,6 +61,10 @@
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
</dependency>
<dependency>
<groupId>org.opentest4j</groupId>
<artifactId>opentest4j</artifactId>
@@ -41,6 +41,20 @@ public interface APIRequest {
* </ul>
*/
public String baseURL;
/**
* TLS Client Authentication allows the server to request a client certificate and verify it.
*
* <p> <strong>Details</strong>
*
* <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;
/**
* An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
@@ -100,6 +114,23 @@ public interface APIRequest {
this.baseURL = baseURL;
return this;
}
/**
* TLS Client Authentication allows the server to request a client certificate and verify it.
*
* <p> <strong>Details</strong>
*
* <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 NewContextOptions setClientCertificates(List<ClientCertificate> clientCertificates) {
this.clientCertificates = clientCertificates;
return this;
}
/**
* An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
@@ -43,6 +43,20 @@ import java.nio.file.Path;
* object will have its own isolated cookie storage.
*/
public interface APIRequestContext {
class DisposeOptions {
/**
* The reason to be reported to the operations interrupted by the context disposal.
*/
public String reason;
/**
* The reason to be reported to the operations interrupted by the context disposal.
*/
public DisposeOptions setReason(String reason) {
this.reason = reason;
return this;
}
}
class StorageStateOptions {
/**
* The file path to save the storage state to. If {@code path} is a relative path, then it is resolved relative to current
@@ -88,7 +102,18 @@ public interface APIRequestContext {
*
* @since v1.16
*/
void dispose();
default void dispose() {
dispose(null);
}
/**
* All responses returned by {@link com.microsoft.playwright.APIRequestContext#get APIRequestContext.get()} and similar
* methods are stored in the memory, so that you can later call {@link com.microsoft.playwright.APIResponse#body
* APIResponse.body()}.This method discards all its resources, calling any method on disposed {@code APIRequestContext}
* will throw an exception.
*
* @since v1.16
*/
void dispose(DisposeOptions options);
/**
* Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update
* context cookies from the response. The method will automatically follow redirects.
@@ -104,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");
@@ -142,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");
@@ -179,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");
@@ -217,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
*/
@@ -96,6 +96,20 @@ public interface Browser extends AutoCloseable {
* Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}.
*/
public Boolean bypassCSP;
/**
* TLS Client Authentication allows the server to request a client certificate and verify it.
*
* <p> <strong>Details</strong>
*
* <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
@@ -163,10 +177,6 @@ public interface Browser extends AutoCloseable {
public List<String> permissions;
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public Proxy proxy;
/**
@@ -295,6 +305,23 @@ public interface Browser extends AutoCloseable {
this.bypassCSP = bypassCSP;
return this;
}
/**
* TLS Client Authentication allows the server to request a client certificate and verify it.
*
* <p> <strong>Details</strong>
*
* <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 NewContextOptions setClientCertificates(List<ClientCertificate> clientCertificates) {
this.clientCertificates = clientCertificates;
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
@@ -411,20 +438,12 @@ public interface Browser extends AutoCloseable {
}
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public NewContextOptions setProxy(String server) {
return setProxy(new Proxy(server));
}
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public NewContextOptions setProxy(Proxy proxy) {
this.proxy = proxy;
@@ -626,6 +645,20 @@ public interface Browser extends AutoCloseable {
* Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}.
*/
public Boolean bypassCSP;
/**
* TLS Client Authentication allows the server to request a client certificate and verify it.
*
* <p> <strong>Details</strong>
*
* <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
@@ -693,10 +726,6 @@ public interface Browser extends AutoCloseable {
public List<String> permissions;
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public Proxy proxy;
/**
@@ -825,6 +854,23 @@ public interface Browser extends AutoCloseable {
this.bypassCSP = bypassCSP;
return this;
}
/**
* TLS Client Authentication allows the server to request a client certificate and verify it.
*
* <p> <strong>Details</strong>
*
* <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 NewPageOptions setClientCertificates(List<ClientCertificate> clientCertificates) {
this.clientCertificates = clientCertificates;
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
@@ -941,20 +987,12 @@ public interface Browser extends AutoCloseable {
}
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public NewPageOptions setProxy(String server) {
return setProxy(new Proxy(server));
}
/**
* Network proxy settings to use with this context. Defaults to none.
*
* <p> <strong>NOTE:</strong> For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts
* override the proxy, global proxy will be never used and can be any string, for example {@code launch({ proxy: { server:
* 'http://per-context' } })}.
*/
public NewPageOptions setProxy(Proxy proxy) {
this.proxy = proxy;
@@ -30,8 +30,9 @@ import java.util.regex.Pattern;
* <p> If a page opens another page, e.g. with a {@code window.open} call, the popup will belong to the parent page's browser
* context.
*
* <p> Playwright allows creating "incognito" browser contexts with {@link com.microsoft.playwright.Browser#newContext
* Browser.newContext()} method. "Incognito" browser contexts don't write any browsing data to disk.
* <p> Playwright allows creating isolated non-persistent browser contexts with {@link
* com.microsoft.playwright.Browser#newContext Browser.newContext()} method. Non-persistent browser contexts don't write
* any browsing data to disk.
* <pre>{@code
* // Create a new incognito browser context
* BrowserContext context = browser.newContext();
@@ -279,14 +280,12 @@ public interface BrowserContext extends AutoCloseable {
}
class ExposeBindingOptions {
/**
* Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
* supported. When passing by value, multiple arguments are supported.
* @deprecated This option will be removed in the future.
*/
public Boolean handle;
/**
* Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
* supported. When passing by value, multiple arguments are supported.
* @deprecated This option will be removed in the future.
*/
public ExposeBindingOptions setHandle(boolean handle) {
this.handle = handle;
@@ -501,6 +500,12 @@ public interface BrowserContext extends AutoCloseable {
return this;
}
}
/**
* Playwright has ability to mock clock and passage of time.
*
* @since v1.45
*/
Clock clock();
/**
* Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be
* obtained via {@link com.microsoft.playwright.BrowserContext#cookies BrowserContext.cookies()}.
@@ -510,9 +515,6 @@ public interface BrowserContext extends AutoCloseable {
* browserContext.addCookies(Arrays.asList(cookieObject1, cookieObject2));
* }</pre>
*
* @param cookies Adds cookies to the browser context.
*
* <p> For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com".
* @since v1.8
*/
void addCookies(List<Cookie> cookies);
@@ -717,21 +719,6 @@ public interface BrowserContext extends AutoCloseable {
* }
* }</pre>
*
* <p> An example of passing an element handle:
* <pre>{@code
* context.exposeBinding("clicked", (source, args) -> {
* ElementHandle element = (ElementHandle) args[0];
* System.out.println(element.textContent());
* return null;
* }, new BrowserContext.ExposeBindingOptions().setHandle(true));
* page.setContent("" +
* "<script>\n" +
* " document.addEventListener('click', event => window.clicked(event.target));\n" +
* "</script>\n" +
* "<div>Click me</div>\n" +
* "<div>Or click me</div>\n");
* }</pre>
*
* @param name Name of the function on the window object.
* @param callback Callback function that will be called in the Playwright's context.
* @since v1.8
@@ -779,21 +766,6 @@ public interface BrowserContext extends AutoCloseable {
* }
* }</pre>
*
* <p> An example of passing an element handle:
* <pre>{@code
* context.exposeBinding("clicked", (source, args) -> {
* ElementHandle element = (ElementHandle) args[0];
* System.out.println(element.textContent());
* return null;
* }, new BrowserContext.ExposeBindingOptions().setHandle(true));
* page.setContent("" +
* "<script>\n" +
* " document.addEventListener('click', event => window.clicked(event.target));\n" +
* "</script>\n" +
* "<div>Click me</div>\n" +
* "<div>Or click me</div>\n");
* }</pre>
*
* @param name Name of the function on the window object.
* @param callback Callback function that will be called in the Playwright's context.
* @since v1.8
@@ -863,21 +835,22 @@ public interface BrowserContext extends AutoCloseable {
*
* @param permissions A permission or an array of permissions to grant. Permissions can be one of the following values:
* <ul>
* <li> {@code "geolocation"}</li>
* <li> {@code "midi"}</li>
* <li> {@code "midi-sysex"} (system-exclusive midi)</li>
* <li> {@code "notifications"}</li>
* <li> {@code "camera"}</li>
* <li> {@code "microphone"}</li>
* <li> {@code "background-sync"}</li>
* <li> {@code "ambient-light-sensor"}</li>
* <li> {@code "accelerometer"}</li>
* <li> {@code "gyroscope"}</li>
* <li> {@code "magnetometer"}</li>
* <li> {@code "accessibility-events"}</li>
* <li> {@code "ambient-light-sensor"}</li>
* <li> {@code "background-sync"}</li>
* <li> {@code "camera"}</li>
* <li> {@code "clipboard-read"}</li>
* <li> {@code "clipboard-write"}</li>
* <li> {@code "geolocation"}</li>
* <li> {@code "gyroscope"}</li>
* <li> {@code "magnetometer"}</li>
* <li> {@code "microphone"}</li>
* <li> {@code "midi-sysex"} (system-exclusive midi)</li>
* <li> {@code "midi"}</li>
* <li> {@code "notifications"}</li>
* <li> {@code "payment-handler"}</li>
* <li> {@code "storage-access"}</li>
* </ul>
* @since v1.8
*/
@@ -890,21 +863,22 @@ public interface BrowserContext extends AutoCloseable {
*
* @param permissions A permission or an array of permissions to grant. Permissions can be one of the following values:
* <ul>
* <li> {@code "geolocation"}</li>
* <li> {@code "midi"}</li>
* <li> {@code "midi-sysex"} (system-exclusive midi)</li>
* <li> {@code "notifications"}</li>
* <li> {@code "camera"}</li>
* <li> {@code "microphone"}</li>
* <li> {@code "background-sync"}</li>
* <li> {@code "ambient-light-sensor"}</li>
* <li> {@code "accelerometer"}</li>
* <li> {@code "gyroscope"}</li>
* <li> {@code "magnetometer"}</li>
* <li> {@code "accessibility-events"}</li>
* <li> {@code "ambient-light-sensor"}</li>
* <li> {@code "background-sync"}</li>
* <li> {@code "camera"}</li>
* <li> {@code "clipboard-read"}</li>
* <li> {@code "clipboard-write"}</li>
* <li> {@code "geolocation"}</li>
* <li> {@code "gyroscope"}</li>
* <li> {@code "magnetometer"}</li>
* <li> {@code "microphone"}</li>
* <li> {@code "midi-sysex"} (system-exclusive midi)</li>
* <li> {@code "midi"}</li>
* <li> {@code "notifications"}</li>
* <li> {@code "payment-handler"}</li>
* <li> {@code "storage-access"}</li>
* </ul>
* @since v1.8
*/
@@ -953,7 +927,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1009,7 +983,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1063,7 +1037,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1119,7 +1093,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1173,7 +1147,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1229,7 +1203,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by
* Service Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling
* Service Workers when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* Service Workers when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>Usage</strong>
*
@@ -1283,7 +1257,7 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <a
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code
* path} is a relative path, then it is resolved relative to the current working directory.
@@ -1298,13 +1272,94 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <a
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code
* path} is a relative path, then it is resolved relative to the current working directory.
* @since v1.23
*/
void routeFromHAR(Path har, RouteFromHAROptions options);
/**
* This method allows to modify websocket connections that are made by any page in the browser context.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before creating any pages.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple handler that blocks some websocket messages. See {@code WebSocketRoute} for more details
* and examples.
* <pre>{@code
* context.routeWebSocket("/ws", ws -> {
* ws.routeSend(message -> {
* if ("to-be-blocked".equals(message))
* return;
* ws.send(message);
* });
* ws.connect();
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(String url, Consumer<WebSocketRoute> handler);
/**
* This method allows to modify websocket connections that are made by any page in the browser context.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before creating any pages.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple handler that blocks some websocket messages. See {@code WebSocketRoute} for more details
* and examples.
* <pre>{@code
* context.routeWebSocket("/ws", ws -> {
* ws.routeSend(message -> {
* if ("to-be-blocked".equals(message))
* return;
* ws.send(message);
* });
* ws.connect();
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(Pattern url, Consumer<WebSocketRoute> handler);
/**
* This method allows to modify websocket connections that are made by any page in the browser context.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before creating any pages.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple handler that blocks some websocket messages. See {@code WebSocketRoute} for more details
* and examples.
* <pre>{@code
* context.routeWebSocket("/ws", ws -> {
* ws.routeSend(message -> {
* if ("to-be-blocked".equals(message))
* return;
* ws.send(message);
* });
* ws.connect();
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(Predicate<String> url, Consumer<WebSocketRoute> handler);
/**
* This setting will change the default maximum navigation time for the following methods and related shortcuts:
* <ul>
@@ -455,6 +455,20 @@ public interface BrowserType {
* Enable Chromium sandboxing. Defaults to {@code false}.
*/
public Boolean chromiumSandbox;
/**
* TLS Client Authentication allows the server to request a client certificate and verify it.
*
* <p> <strong>Details</strong>
*
* <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
@@ -742,6 +756,23 @@ public interface BrowserType {
this.chromiumSandbox = chromiumSandbox;
return this;
}
/**
* TLS Client Authentication allows the server to request a client certificate and verify it.
*
* <p> <strong>Details</strong>
*
* <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 LaunchPersistentContextOptions setClientCertificates(List<ClientCertificate> clientCertificates) {
this.clientCertificates = clientCertificates;
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
@@ -0,0 +1,312 @@
/*
* 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.Date;
/**
* Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn more
* about <a href="https://playwright.dev/java/docs/clock">clock emulation</a>.
*
* <p> Note that clock is installed for the entire {@code BrowserContext}, so the time in all the pages and iframes is
* controlled by the same clock.
*/
public interface Clock {
class InstallOptions {
/**
* Time to initialize with, current system time by default.
*/
public Object time;
/**
* Time to initialize with, current system time by default.
*/
public InstallOptions setTime(long time) {
this.time = time;
return this;
}
/**
* Time to initialize with, current system time by default.
*/
public InstallOptions setTime(String time) {
this.time = time;
return this;
}
/**
* Time to initialize with, current system time by default.
*/
public InstallOptions setTime(Date time) {
this.time = time;
return this;
}
}
/**
* Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user closing the
* laptop lid for a while and reopening it later, after given time.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().fastForward(1000);
* page.clock().fastForward("30:00");
* }</pre>
*
* @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are "08"
* for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
* @since v1.45
*/
void fastForward(long ticks);
/**
* Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user closing the
* laptop lid for a while and reopening it later, after given time.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().fastForward(1000);
* page.clock().fastForward("30:00");
* }</pre>
*
* @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are "08"
* for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
* @since v1.45
*/
void fastForward(String ticks);
/**
* Install fake implementations for the following time-related functions:
* <ul>
* <li> {@code Date}</li>
* <li> {@code setTimeout}</li>
* <li> {@code clearTimeout}</li>
* <li> {@code setInterval}</li>
* <li> {@code clearInterval}</li>
* <li> {@code requestAnimationFrame}</li>
* <li> {@code cancelAnimationFrame}</li>
* <li> {@code requestIdleCallback}</li>
* <li> {@code cancelIdleCallback}</li>
* <li> {@code performance}</li>
* </ul>
*
* <p> Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers, and
* control the behavior of time-dependent functions. See {@link com.microsoft.playwright.Clock#runFor Clock.runFor()} and
* {@link com.microsoft.playwright.Clock#fastForward Clock.fastForward()} for more information.
*
* @since v1.45
*/
default void install() {
install(null);
}
/**
* Install fake implementations for the following time-related functions:
* <ul>
* <li> {@code Date}</li>
* <li> {@code setTimeout}</li>
* <li> {@code clearTimeout}</li>
* <li> {@code setInterval}</li>
* <li> {@code clearInterval}</li>
* <li> {@code requestAnimationFrame}</li>
* <li> {@code cancelAnimationFrame}</li>
* <li> {@code requestIdleCallback}</li>
* <li> {@code cancelIdleCallback}</li>
* <li> {@code performance}</li>
* </ul>
*
* <p> Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers, and
* control the behavior of time-dependent functions. See {@link com.microsoft.playwright.Clock#runFor Clock.runFor()} and
* {@link com.microsoft.playwright.Clock#fastForward Clock.fastForward()} for more information.
*
* @since v1.45
*/
void install(InstallOptions options);
/**
* Advance the clock, firing all the time-related callbacks.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().runFor(1000);
* page.clock().runFor("30:00");
* }</pre>
*
* @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are "08"
* for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
* @since v1.45
*/
void runFor(long ticks);
/**
* Advance the clock, firing all the time-related callbacks.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().runFor(1000);
* page.clock().runFor("30:00");
* }</pre>
*
* @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are "08"
* for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
* @since v1.45
*/
void runFor(String ticks);
/**
* Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired unless
* {@link com.microsoft.playwright.Clock#runFor Clock.runFor()}, {@link com.microsoft.playwright.Clock#fastForward
* Clock.fastForward()}, {@link com.microsoft.playwright.Clock#pauseAt Clock.pauseAt()} or {@link
* com.microsoft.playwright.Clock#resume Clock.resume()} is called.
*
* <p> Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it at
* the specified time and pausing.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
* page.clock().pauseAt(format.parse("2020-02-02"));
* page.clock().pauseAt("2020-02-02");
* }</pre>
*
* @param time Time to pause at.
* @since v1.45
*/
void pauseAt(long time);
/**
* Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired unless
* {@link com.microsoft.playwright.Clock#runFor Clock.runFor()}, {@link com.microsoft.playwright.Clock#fastForward
* Clock.fastForward()}, {@link com.microsoft.playwright.Clock#pauseAt Clock.pauseAt()} or {@link
* com.microsoft.playwright.Clock#resume Clock.resume()} is called.
*
* <p> Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it at
* the specified time and pausing.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
* page.clock().pauseAt(format.parse("2020-02-02"));
* page.clock().pauseAt("2020-02-02");
* }</pre>
*
* @param time Time to pause at.
* @since v1.45
*/
void pauseAt(String time);
/**
* Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired unless
* {@link com.microsoft.playwright.Clock#runFor Clock.runFor()}, {@link com.microsoft.playwright.Clock#fastForward
* Clock.fastForward()}, {@link com.microsoft.playwright.Clock#pauseAt Clock.pauseAt()} or {@link
* com.microsoft.playwright.Clock#resume Clock.resume()} is called.
*
* <p> Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it at
* the specified time and pausing.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
* page.clock().pauseAt(format.parse("2020-02-02"));
* page.clock().pauseAt("2020-02-02");
* }</pre>
*
* @param time Time to pause at.
* @since v1.45
*/
void pauseAt(Date time);
/**
* Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.
*
* @since v1.45
*/
void resume();
/**
* Makes {@code Date.now} and {@code new Date()} return fixed fake time at all times, keeps all the timers running.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().setFixedTime(new Date());
* page.clock().setFixedTime(new SimpleDateFormat("yyy-MM-dd").parse("2020-02-02"));
* page.clock().setFixedTime("2020-02-02");
* }</pre>
*
* @param time Time to be set in milliseconds.
* @since v1.45
*/
void setFixedTime(long time);
/**
* Makes {@code Date.now} and {@code new Date()} return fixed fake time at all times, keeps all the timers running.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().setFixedTime(new Date());
* page.clock().setFixedTime(new SimpleDateFormat("yyy-MM-dd").parse("2020-02-02"));
* page.clock().setFixedTime("2020-02-02");
* }</pre>
*
* @param time Time to be set in milliseconds.
* @since v1.45
*/
void setFixedTime(String time);
/**
* Makes {@code Date.now} and {@code new Date()} return fixed fake time at all times, keeps all the timers running.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().setFixedTime(new Date());
* page.clock().setFixedTime(new SimpleDateFormat("yyy-MM-dd").parse("2020-02-02"));
* page.clock().setFixedTime("2020-02-02");
* }</pre>
*
* @param time Time to be set in milliseconds.
* @since v1.45
*/
void setFixedTime(Date time);
/**
* Sets current system time but does not trigger any timers.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().setSystemTime(new Date());
* page.clock().setSystemTime(new SimpleDateFormat("yyy-MM-dd").parse("2020-02-02"));
* page.clock().setSystemTime("2020-02-02");
* }</pre>
*
* @param time Time to be set in milliseconds.
* @since v1.45
*/
void setSystemTime(long time);
/**
* Sets current system time but does not trigger any timers.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().setSystemTime(new Date());
* page.clock().setSystemTime(new SimpleDateFormat("yyy-MM-dd").parse("2020-02-02"));
* page.clock().setSystemTime("2020-02-02");
* }</pre>
*
* @param time Time to be set in milliseconds.
* @since v1.45
*/
void setSystemTime(String time);
/**
* Sets current system time but does not trigger any timers.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.clock().setSystemTime(new Date());
* page.clock().setSystemTime(new SimpleDateFormat("yyy-MM-dd").parse("2020-02-02"));
* page.clock().setSystemTime("2020-02-02");
* }</pre>
*
* @param time Time to be set in milliseconds.
* @since v1.45
*/
void setSystemTime(Date time);
}
@@ -20,7 +20,7 @@ import java.util.*;
/**
* {@code ConsoleMessage} objects are dispatched by page via the {@link com.microsoft.playwright.Page#onConsoleMessage
* Page.onConsoleMessage()} event. For each console messages logged in the page there will be corresponding event in the
* Page.onConsoleMessage()} event. For each console message logged in the page there will be corresponding event in the
* Playwright context.
* <pre>{@code
* // Listen for all console messages and print them to the standard output.
@@ -65,9 +65,7 @@ public interface ElementHandle extends JSHandle {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -98,9 +96,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public CheckOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -166,9 +162,7 @@ public interface ElementHandle extends JSHandle {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public Boolean noWaitAfter;
/**
@@ -229,9 +223,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public ClickOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -293,9 +285,7 @@ public interface ElementHandle extends JSHandle {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -349,9 +339,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public DblclickOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -399,9 +387,7 @@ public interface ElementHandle extends JSHandle {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -421,9 +407,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public FillOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -453,9 +437,7 @@ public interface ElementHandle extends JSHandle {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -495,9 +477,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public HoverOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -564,9 +544,7 @@ public interface ElementHandle extends JSHandle {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public Boolean noWaitAfter;
/**
@@ -585,9 +563,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public PressOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -801,9 +777,7 @@ public interface ElementHandle extends JSHandle {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -823,9 +797,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SelectOptionOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -882,9 +854,7 @@ public interface ElementHandle extends JSHandle {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -915,9 +885,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetCheckedOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -960,9 +928,7 @@ public interface ElementHandle extends JSHandle {
}
class SetInputFilesOptions {
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -974,9 +940,7 @@ public interface ElementHandle extends JSHandle {
public Double timeout;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetInputFilesOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1006,9 +970,7 @@ public interface ElementHandle extends JSHandle {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1048,9 +1010,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public TapOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1097,9 +1057,7 @@ public interface ElementHandle extends JSHandle {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1118,9 +1076,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public TypeOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1144,9 +1100,7 @@ public interface ElementHandle extends JSHandle {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1177,9 +1131,7 @@ public interface ElementHandle extends JSHandle {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public UncheckOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1332,7 +1284,6 @@ public interface ElementHandle extends JSHandle {
* force} option is set.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked. If not, this method throws.</li>
* </ol>
*
@@ -1355,7 +1306,6 @@ public interface ElementHandle extends JSHandle {
* force} option is set.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked. If not, this method throws.</li>
* </ol>
*
@@ -1421,8 +1371,6 @@ public interface ElementHandle extends JSHandle {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to double click in the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set. Note that if the
* first click of the {@code dblclick()} triggers a navigation event, this method will throw.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -1445,8 +1393,6 @@ public interface ElementHandle extends JSHandle {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to double click in the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set. Note that if the
* first click of the {@code dblclick()} triggers a navigation event, this method will throw.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -1703,7 +1649,6 @@ public interface ElementHandle extends JSHandle {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to hover over the center of the element, or the specified
* {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -1724,7 +1669,6 @@ public interface ElementHandle extends JSHandle {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to hover over the center of the element, or the specified
* {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -1926,6 +1870,8 @@ public interface ElementHandle extends JSHandle {
* <p> Throws when {@code elementHandle} does not point to an element <a
* href="https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected">connected</a> to a Document or a ShadowRoot.
*
* <p> See <a href="https://playwright.dev/java/docs/input#scrolling">scrolling</a> for alternative ways to scroll.
*
* @since v1.8
*/
default void scrollIntoViewIfNeeded() {
@@ -1940,6 +1886,8 @@ public interface ElementHandle extends JSHandle {
* <p> Throws when {@code elementHandle} does not point to an element <a
* href="https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected">connected</a> to a Document or a ShadowRoot.
*
* <p> See <a href="https://playwright.dev/java/docs/input#scrolling">scrolling</a> for alternative ways to scroll.
*
* @since v1.8
*/
void scrollIntoViewIfNeeded(ScrollIntoViewIfNeededOptions options);
@@ -2336,7 +2284,6 @@ public interface ElementHandle extends JSHandle {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked or unchecked. If not, this method throws.</li>
* </ol>
*
@@ -2358,7 +2305,6 @@ public interface ElementHandle extends JSHandle {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked or unchecked. If not, this method throws.</li>
* </ol>
*
@@ -2371,7 +2317,8 @@ public interface ElementHandle extends JSHandle {
void setChecked(boolean checked, SetCheckedOptions options);
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code ElementHandle} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -2386,7 +2333,8 @@ public interface ElementHandle extends JSHandle {
}
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code ElementHandle} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -2399,7 +2347,8 @@ public interface ElementHandle extends JSHandle {
void setInputFiles(Path files, SetInputFilesOptions options);
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code ElementHandle} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -2414,7 +2363,8 @@ public interface ElementHandle extends JSHandle {
}
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code ElementHandle} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -2427,7 +2377,8 @@ public interface ElementHandle extends JSHandle {
void setInputFiles(Path[] files, SetInputFilesOptions options);
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code ElementHandle} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -2442,7 +2393,8 @@ public interface ElementHandle extends JSHandle {
}
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code ElementHandle} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -2455,7 +2407,8 @@ public interface ElementHandle extends JSHandle {
void setInputFiles(FilePayload files, SetInputFilesOptions options);
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code ElementHandle} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -2470,7 +2423,8 @@ public interface ElementHandle extends JSHandle {
}
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code ElementHandle} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -2489,7 +2443,6 @@ public interface ElementHandle extends JSHandle {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#touchscreen Page.touchscreen()} to tap the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -2512,7 +2465,6 @@ public interface ElementHandle extends JSHandle {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#touchscreen Page.touchscreen()} to tap the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -2560,7 +2512,6 @@ public interface ElementHandle extends JSHandle {
* force} option is set.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now unchecked. If not, this method throws.</li>
* </ol>
*
@@ -2583,7 +2534,6 @@ public interface ElementHandle extends JSHandle {
* force} option is set.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now unchecked. If not, this method throws.</li>
* </ol>
*
@@ -30,9 +30,7 @@ import java.nio.file.Path;
public interface FileChooser {
class SetFilesOptions {
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -44,9 +42,7 @@ public interface FileChooser {
public Double timeout;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetFilesOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -72,7 +72,7 @@ public interface Frame {
*/
public Path path;
/**
* Script type. Use 'module' in order to load a Javascript ES6 module. See <a
* Script type. Use 'module' in order to load a JavaScript ES6 module. See <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script">script</a> for more details.
*/
public String type;
@@ -97,7 +97,7 @@ public interface Frame {
return this;
}
/**
* Script type. Use 'module' in order to load a Javascript ES6 module. See <a
* Script type. Use 'module' in order to load a JavaScript ES6 module. See <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script">script</a> for more details.
*/
public AddScriptTagOptions setType(String type) {
@@ -157,9 +157,7 @@ public interface Frame {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -195,9 +193,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public CheckOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -271,9 +267,7 @@ public interface Frame {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public Boolean noWaitAfter;
/**
@@ -296,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;
@@ -339,9 +334,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public ClickOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -383,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;
@@ -411,9 +405,7 @@ public interface Frame {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -436,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;
@@ -472,9 +465,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public DblclickOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -516,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;
@@ -563,9 +555,7 @@ public interface Frame {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -606,9 +596,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public DragAndDropOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -695,9 +683,7 @@ public interface Frame {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -722,9 +708,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public FillOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1124,9 +1108,7 @@ public interface Frame {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1149,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;
@@ -1171,9 +1154,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public HoverOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1215,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;
@@ -1613,9 +1595,7 @@ public interface Frame {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public Boolean noWaitAfter;
/**
@@ -1639,9 +1619,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public PressOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1689,9 +1667,7 @@ public interface Frame {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1716,9 +1692,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SelectOptionOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1750,9 +1724,7 @@ public interface Frame {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1788,9 +1760,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetCheckedOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1890,9 +1860,7 @@ public interface Frame {
}
class SetInputFilesOptions {
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1909,9 +1877,7 @@ public interface Frame {
public Double timeout;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetInputFilesOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1949,9 +1915,7 @@ public interface Frame {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1974,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,9 +1961,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public TapOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2040,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;
@@ -2086,9 +2050,7 @@ public interface Frame {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -2112,9 +2074,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public TypeOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2146,9 +2106,7 @@ public interface Frame {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -2184,9 +2142,7 @@ public interface Frame {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public UncheckOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2531,7 +2487,6 @@ public interface Frame {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked. If not, this method throws.</li>
* </ol>
*
@@ -2554,7 +2509,6 @@ public interface Frame {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked. If not, this method throws.</li>
* </ol>
*
@@ -2625,9 +2579,8 @@ public interface Frame {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to double click in the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set. Note that if the
* first click of the {@code dblclick()} triggers a navigation event, this method will throw.</li>
* specified {@code position}. if the first click of the {@code dblclick()} triggers a navigation event, this method will
* throw.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -2649,9 +2602,8 @@ public interface Frame {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to double click in the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set. Note that if the
* first click of the {@code dblclick()} triggers a navigation event, this method will throw.</li>
* specified {@code position}. if the first click of the {@code dblclick()} triggers a navigation event, this method will
* throw.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -3831,7 +3783,6 @@ public interface Frame {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to hover over the center of the element, or the specified
* {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -3852,7 +3803,6 @@ public interface Frame {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to hover over the center of the element, or the specified
* {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -4568,7 +4518,6 @@ public interface Frame {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked or unchecked. If not, this method throws.</li>
* </ol>
*
@@ -4592,7 +4541,6 @@ public interface Frame {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked or unchecked. If not, this method throws.</li>
* </ol>
*
@@ -4753,7 +4701,6 @@ public interface Frame {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#touchscreen Page.touchscreen()} to tap the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -4776,7 +4723,6 @@ public interface Frame {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#touchscreen Page.touchscreen()} to tap the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -4842,7 +4788,6 @@ public interface Frame {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now unchecked. If not, this method throws.</li>
* </ol>
*
@@ -4865,7 +4810,6 @@ public interface Frame {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now unchecked. If not, this method throws.</li>
* </ol>
*
@@ -22,10 +22,10 @@ import java.util.regex.Pattern;
/**
* FrameLocator represents a view to the {@code iframe} on the page. It captures the logic sufficient to retrieve the
* {@code iframe} and locate elements in that iframe. FrameLocator can be created with either {@link
* com.microsoft.playwright.Page#frameLocator Page.frameLocator()} or {@link com.microsoft.playwright.Locator#frameLocator
* Locator.frameLocator()} method.
* com.microsoft.playwright.Locator#contentFrame Locator.contentFrame()}, {@link com.microsoft.playwright.Page#frameLocator
* Page.frameLocator()} or {@link com.microsoft.playwright.Locator#frameLocator Locator.frameLocator()} method.
* <pre>{@code
* Locator locator = page.frameLocator("#my-frame").getByText("Submit");
* Locator locator = page.locator("#my-frame").contentFrame().getByText("Submit");
* locator.click();
* }</pre>
*
@@ -35,10 +35,10 @@ import java.util.regex.Pattern;
* a given selector.
* <pre>{@code
* // Throws if there are several frames in DOM:
* page.frame_locator(".result-frame").getByRole(AriaRole.BUTTON).click();
* page.locator(".result-frame").contentFrame().getByRole(AriaRole.BUTTON).click();
*
* // Works because we explicitly tell locator to pick the first frame:
* page.frame_locator(".result-frame").first().getByRole(AriaRole.BUTTON).click();
* page.locator(".result-frame").first().contentFrame().getByRole(AriaRole.BUTTON).click();
* }</pre>
*
* <p> <strong>Converting Locator to FrameLocator</strong>
@@ -383,7 +383,8 @@ public interface FrameLocator {
}
}
/**
* Returns locator to the first matching frame.
* @deprecated Use {@link com.microsoft.playwright.Locator#first Locator.first()} followed by {@link
* com.microsoft.playwright.Locator#contentFrame Locator.contentFrame()} instead.
*
* @since v1.17
*/
@@ -953,7 +954,8 @@ public interface FrameLocator {
*/
Locator getByTitle(Pattern text, GetByTitleOptions options);
/**
* Returns locator to the last matching frame.
* @deprecated Use {@link com.microsoft.playwright.Locator#last Locator.last()} followed by {@link
* com.microsoft.playwright.Locator#contentFrame Locator.contentFrame()} instead.
*
* @since v1.17
*/
@@ -1003,7 +1005,8 @@ public interface FrameLocator {
*/
Locator locator(Locator selectorOrLocator, LocatorOptions options);
/**
* Returns locator to the n-th matching frame. It's zero based, {@code nth(0)} selects the first frame.
* @deprecated Use {@link com.microsoft.playwright.Locator#nth Locator.nth()} followed by {@link
* com.microsoft.playwright.Locator#contentFrame Locator.contentFrame()} instead.
*
* @since v1.17
*/
@@ -1018,7 +1021,7 @@ public interface FrameLocator {
*
* <p> <strong>Usage</strong>
* <pre>{@code
* FrameLocator frameLocator = page.frameLocator("iframe[name=\"embedded\"]");
* FrameLocator frameLocator = page.locator("iframe[name=\"embedded\"]").contentFrame();
* // ...
* Locator locator = frameLocator.owner();
* assertThat(locator).isVisible();
@@ -76,9 +76,7 @@ public interface Locator {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -109,9 +107,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public CheckOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -159,9 +155,7 @@ public interface Locator {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -181,9 +175,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public ClearOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -225,9 +217,7 @@ public interface Locator {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public Boolean noWaitAfter;
/**
@@ -245,7 +235,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -288,9 +279,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public ClickOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -324,7 +313,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public ClickOptions setTrial(boolean trial) {
this.trial = trial;
@@ -352,9 +342,7 @@ public interface Locator {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -372,7 +360,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -408,9 +397,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public DblclickOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -444,7 +431,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public DblclickOptions setTrial(boolean trial) {
this.trial = trial;
@@ -478,9 +466,7 @@ public interface Locator {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -516,9 +502,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public DragToOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -641,9 +625,7 @@ public interface Locator {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -663,9 +645,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public FillOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1065,9 +1045,7 @@ public interface Locator {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1085,7 +1063,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -1107,9 +1086,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public HoverOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1143,7 +1120,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public HoverOptions setTrial(boolean trial) {
this.trial = trial;
@@ -1424,9 +1402,7 @@ public interface Locator {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public Boolean noWaitAfter;
/**
@@ -1445,9 +1421,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public PressOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1470,9 +1444,7 @@ public interface Locator {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1491,9 +1463,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public PressSequentiallyOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1707,9 +1677,7 @@ public interface Locator {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1729,9 +1697,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SelectOptionOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1788,9 +1754,7 @@ public interface Locator {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1821,9 +1785,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetCheckedOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1866,9 +1828,7 @@ public interface Locator {
}
class SetInputFilesOptions {
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1880,9 +1840,7 @@ public interface Locator {
public Double timeout;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetInputFilesOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1912,9 +1870,7 @@ public interface Locator {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1932,7 +1888,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -1954,9 +1911,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public TapOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1990,7 +1945,8 @@ public interface Locator {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public TapOptions setTrial(boolean trial) {
this.trial = trial;
@@ -2023,9 +1979,7 @@ public interface Locator {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -2044,9 +1998,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public TypeOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2070,9 +2022,7 @@ public interface Locator {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -2103,9 +2053,7 @@ public interface Locator {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public UncheckOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2197,10 +2145,9 @@ public interface Locator {
* When the locator points to a list of elements, this returns an array of locators, pointing to their respective elements.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Locator#all Locator.all()} does not wait for elements to match the locator, and instead
* immediately returns whatever is present in the page. When the list of elements changes dynamically, {@link
* com.microsoft.playwright.Locator#all Locator.all()} will produce unpredictable and flaky results. When the list of
* elements is stable, but loaded dynamically, wait for the full list to finish loading before calling {@link
* com.microsoft.playwright.Locator#all Locator.all()}.
* immediately returns whatever is present in the page.When the list of elements changes dynamically, {@link com.microsoft.playwright.Locator#all Locator.all()} will produce
* unpredictable and flaky results.When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before calling
* {@link com.microsoft.playwright.Locator#all Locator.all()}.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -2334,7 +2281,6 @@ public interface Locator {
* force} option is set.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked. If not, this method throws.</li>
* </ol>
*
@@ -2366,7 +2312,6 @@ public interface Locator {
* force} option is set.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked. If not, this method throws.</li>
* </ol>
*
@@ -2532,8 +2477,6 @@ public interface Locator {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to double click in the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set. Note that if the
* first click of the {@code dblclick()} triggers a navigation event, this method will throw.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -2560,8 +2503,6 @@ public interface Locator {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to double click in the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set. Note that if the
* first click of the {@code dblclick()} triggers a navigation event, this method will throw.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -3757,7 +3698,6 @@ public interface Locator {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to hover over the center of the element, or the specified
* {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -3787,7 +3727,6 @@ public interface Locator {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to hover over the center of the element, or the specified
* {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -4145,7 +4084,10 @@ public interface Locator {
*/
Locator nth(int index);
/**
* Creates a locator that matches either of the two locators.
* Creates a locator matching all elements that match one or both of the two locators.
*
* <p> Note that when both locators match something, the resulting locator will have multiple matches and violate <a
* href="https://playwright.dev/java/docs/locators#strictness">locator strictness</a> guidelines.
*
* <p> <strong>Usage</strong>
*
@@ -4372,6 +4314,8 @@ public interface Locator {
* href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">IntersectionObserver</a>'s {@code
* ratio}.
*
* <p> See <a href="https://playwright.dev/java/docs/input#scrolling">scrolling</a> for alternative ways to scroll.
*
* @since v1.14
*/
default void scrollIntoViewIfNeeded() {
@@ -4383,6 +4327,8 @@ public interface Locator {
* href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">IntersectionObserver</a>'s {@code
* ratio}.
*
* <p> See <a href="https://playwright.dev/java/docs/input#scrolling">scrolling</a> for alternative ways to scroll.
*
* @since v1.14
*/
void scrollIntoViewIfNeeded(ScrollIntoViewIfNeededOptions options);
@@ -4836,7 +4782,6 @@ public interface Locator {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked or unchecked. If not, this method throws.</li>
* </ol>
*
@@ -4867,7 +4812,6 @@ public interface Locator {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked or unchecked. If not, this method throws.</li>
* </ol>
*
@@ -4879,7 +4823,8 @@ public interface Locator {
*/
void setChecked(boolean checked, SetCheckedOptions options);
/**
* Upload file or multiple files into {@code <input type=file>}.
* Upload file or multiple files into {@code <input type=file>}. For inputs with a {@code [webkitdirectory]} attribute,
* only a single directory path is supported.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -4889,6 +4834,9 @@ public interface Locator {
* // Select multiple files
* page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
*
* // Select a directory
* page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
*
* // Remove all the selected files
* page.getByLabel("Upload file").setInputFiles(new Path[0]);
*
@@ -4914,7 +4862,8 @@ public interface Locator {
setInputFiles(files, null);
}
/**
* Upload file or multiple files into {@code <input type=file>}.
* Upload file or multiple files into {@code <input type=file>}. For inputs with a {@code [webkitdirectory]} attribute,
* only a single directory path is supported.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -4924,6 +4873,9 @@ public interface Locator {
* // Select multiple files
* page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
*
* // Select a directory
* page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
*
* // Remove all the selected files
* page.getByLabel("Upload file").setInputFiles(new Path[0]);
*
@@ -4947,7 +4899,8 @@ public interface Locator {
*/
void setInputFiles(Path files, SetInputFilesOptions options);
/**
* Upload file or multiple files into {@code <input type=file>}.
* Upload file or multiple files into {@code <input type=file>}. For inputs with a {@code [webkitdirectory]} attribute,
* only a single directory path is supported.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -4957,6 +4910,9 @@ public interface Locator {
* // Select multiple files
* page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
*
* // Select a directory
* page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
*
* // Remove all the selected files
* page.getByLabel("Upload file").setInputFiles(new Path[0]);
*
@@ -4982,7 +4938,8 @@ public interface Locator {
setInputFiles(files, null);
}
/**
* Upload file or multiple files into {@code <input type=file>}.
* Upload file or multiple files into {@code <input type=file>}. For inputs with a {@code [webkitdirectory]} attribute,
* only a single directory path is supported.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -4992,6 +4949,9 @@ public interface Locator {
* // Select multiple files
* page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
*
* // Select a directory
* page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
*
* // Remove all the selected files
* page.getByLabel("Upload file").setInputFiles(new Path[0]);
*
@@ -5015,7 +4975,8 @@ public interface Locator {
*/
void setInputFiles(Path[] files, SetInputFilesOptions options);
/**
* Upload file or multiple files into {@code <input type=file>}.
* Upload file or multiple files into {@code <input type=file>}. For inputs with a {@code [webkitdirectory]} attribute,
* only a single directory path is supported.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -5025,6 +4986,9 @@ public interface Locator {
* // Select multiple files
* page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
*
* // Select a directory
* page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
*
* // Remove all the selected files
* page.getByLabel("Upload file").setInputFiles(new Path[0]);
*
@@ -5050,7 +5014,8 @@ public interface Locator {
setInputFiles(files, null);
}
/**
* Upload file or multiple files into {@code <input type=file>}.
* Upload file or multiple files into {@code <input type=file>}. For inputs with a {@code [webkitdirectory]} attribute,
* only a single directory path is supported.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -5060,6 +5025,9 @@ public interface Locator {
* // Select multiple files
* page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
*
* // Select a directory
* page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
*
* // Remove all the selected files
* page.getByLabel("Upload file").setInputFiles(new Path[0]);
*
@@ -5083,7 +5051,8 @@ public interface Locator {
*/
void setInputFiles(FilePayload files, SetInputFilesOptions options);
/**
* Upload file or multiple files into {@code <input type=file>}.
* Upload file or multiple files into {@code <input type=file>}. For inputs with a {@code [webkitdirectory]} attribute,
* only a single directory path is supported.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -5093,6 +5062,9 @@ public interface Locator {
* // Select multiple files
* page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
*
* // Select a directory
* page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
*
* // Remove all the selected files
* page.getByLabel("Upload file").setInputFiles(new Path[0]);
*
@@ -5118,7 +5090,8 @@ public interface Locator {
setInputFiles(files, null);
}
/**
* Upload file or multiple files into {@code <input type=file>}.
* Upload file or multiple files into {@code <input type=file>}. For inputs with a {@code [webkitdirectory]} attribute,
* only a single directory path is supported.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -5128,6 +5101,9 @@ public interface Locator {
* // Select multiple files
* page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
*
* // Select a directory
* page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
*
* // Remove all the selected files
* page.getByLabel("Upload file").setInputFiles(new Path[0]);
*
@@ -5162,7 +5138,6 @@ public interface Locator {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#touchscreen Page.touchscreen()} to tap the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -5189,7 +5164,6 @@ public interface Locator {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#touchscreen Page.touchscreen()} to tap the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> If the element is detached from the DOM at any moment during the action, this method throws.
@@ -5262,7 +5236,6 @@ public interface Locator {
* force} option is set.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now unchecked. If not, this method throws.</li>
* </ol>
*
@@ -5294,7 +5267,6 @@ public interface Locator {
* force} option is set.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now unchecked. If not, this method throws.</li>
* </ol>
*
@@ -163,6 +163,8 @@ public interface Mouse {
* Shortcut for {@link com.microsoft.playwright.Mouse#move Mouse.move()}, {@link com.microsoft.playwright.Mouse#down
* Mouse.down()}, {@link com.microsoft.playwright.Mouse#up Mouse.up()}.
*
* @param x X coordinate relative to the main frame's viewport in CSS pixels.
* @param y Y coordinate relative to the main frame's viewport in CSS pixels.
* @since v1.8
*/
default void click(double x, double y) {
@@ -172,6 +174,8 @@ public interface Mouse {
* Shortcut for {@link com.microsoft.playwright.Mouse#move Mouse.move()}, {@link com.microsoft.playwright.Mouse#down
* Mouse.down()}, {@link com.microsoft.playwright.Mouse#up Mouse.up()}.
*
* @param x X coordinate relative to the main frame's viewport in CSS pixels.
* @param y Y coordinate relative to the main frame's viewport in CSS pixels.
* @since v1.8
*/
void click(double x, double y, ClickOptions options);
@@ -180,6 +184,8 @@ public interface Mouse {
* Mouse.down()}, {@link com.microsoft.playwright.Mouse#up Mouse.up()}, {@link com.microsoft.playwright.Mouse#down
* Mouse.down()} and {@link com.microsoft.playwright.Mouse#up Mouse.up()}.
*
* @param x X coordinate relative to the main frame's viewport in CSS pixels.
* @param y Y coordinate relative to the main frame's viewport in CSS pixels.
* @since v1.8
*/
default void dblclick(double x, double y) {
@@ -190,6 +196,8 @@ public interface Mouse {
* Mouse.down()}, {@link com.microsoft.playwright.Mouse#up Mouse.up()}, {@link com.microsoft.playwright.Mouse#down
* Mouse.down()} and {@link com.microsoft.playwright.Mouse#up Mouse.up()}.
*
* @param x X coordinate relative to the main frame's viewport in CSS pixels.
* @param y Y coordinate relative to the main frame's viewport in CSS pixels.
* @since v1.8
*/
void dblclick(double x, double y, DblclickOptions options);
@@ -210,6 +218,8 @@ public interface Mouse {
/**
* Dispatches a {@code mousemove} event.
*
* @param x X coordinate relative to the main frame's viewport in CSS pixels.
* @param y Y coordinate relative to the main frame's viewport in CSS pixels.
* @since v1.8
*/
default void move(double x, double y) {
@@ -218,6 +228,8 @@ public interface Mouse {
/**
* Dispatches a {@code mousemove} event.
*
* @param x X coordinate relative to the main frame's viewport in CSS pixels.
* @param y Y coordinate relative to the main frame's viewport in CSS pixels.
* @since v1.8
*/
void move(double x, double y, MoveOptions options);
@@ -236,7 +248,8 @@ public interface Mouse {
*/
void up(UpOptions options);
/**
* Dispatches a {@code wheel} event.
* Dispatches a {@code wheel} event. This method is usually used to manually scroll the page. See <a
* href="https://playwright.dev/java/docs/input#scrolling">scrolling</a> for alternative ways to scroll.
*
* <p> <strong>NOTE:</strong> Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling to finish
* before returning.
@@ -342,7 +342,7 @@ public interface Page extends AutoCloseable {
*/
public Path path;
/**
* Script type. Use 'module' in order to load a Javascript ES6 module. See <a
* Script type. Use 'module' in order to load a JavaScript ES6 module. See <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script">script</a> for more details.
*/
public String type;
@@ -367,7 +367,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Script type. Use 'module' in order to load a Javascript ES6 module. See <a
* Script type. Use 'module' in order to load a JavaScript ES6 module. See <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script">script</a> for more details.
*/
public AddScriptTagOptions setType(String type) {
@@ -427,9 +427,7 @@ public interface Page extends AutoCloseable {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -465,9 +463,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public CheckOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -541,9 +537,7 @@ public interface Page extends AutoCloseable {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public Boolean noWaitAfter;
/**
@@ -566,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;
@@ -609,9 +604,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public ClickOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -653,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;
@@ -708,9 +702,7 @@ public interface Page extends AutoCloseable {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -733,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;
@@ -769,9 +762,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public DblclickOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -813,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;
@@ -860,9 +852,7 @@ public interface Page extends AutoCloseable {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -903,9 +893,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public DragAndDropOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1042,14 +1030,12 @@ public interface Page extends AutoCloseable {
}
class ExposeBindingOptions {
/**
* Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
* supported. When passing by value, multiple arguments are supported.
* @deprecated This option will be removed in the future.
*/
public Boolean handle;
/**
* Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
* supported. When passing by value, multiple arguments are supported.
* @deprecated This option will be removed in the future.
*/
public ExposeBindingOptions setHandle(boolean handle) {
this.handle = handle;
@@ -1063,9 +1049,7 @@ public interface Page extends AutoCloseable {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1090,9 +1074,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public FillOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1590,9 +1572,7 @@ public interface Page extends AutoCloseable {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -1615,7 +1595,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -1637,9 +1618,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public HoverOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -1681,7 +1660,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public HoverOptions setTrial(boolean trial) {
this.trial = trial;
@@ -2267,9 +2247,7 @@ public interface Page extends AutoCloseable {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public Boolean noWaitAfter;
/**
@@ -2293,9 +2271,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option will default to {@code true} in the future.
*/
public PressOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2451,7 +2427,7 @@ public interface Page extends AutoCloseable {
/**
* When set to {@code minimal}, only record information necessary for routing from HAR. This omits sizes, timing, page,
* cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to {@code
* full}.
* minimal}.
*/
public HarMode updateMode;
/**
@@ -2491,7 +2467,7 @@ public interface Page extends AutoCloseable {
/**
* When set to {@code minimal}, only record information necessary for routing from HAR. This omits sizes, timing, page,
* cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to {@code
* full}.
* minimal}.
*/
public RouteFromHAROptions setUpdateMode(HarMode updateMode) {
this.updateMode = updateMode;
@@ -2721,9 +2697,7 @@ public interface Page extends AutoCloseable {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -2748,9 +2722,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SelectOptionOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2782,9 +2754,7 @@ public interface Page extends AutoCloseable {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -2820,9 +2790,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetCheckedOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2922,9 +2890,7 @@ public interface Page extends AutoCloseable {
}
class SetInputFilesOptions {
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -2941,9 +2907,7 @@ public interface Page extends AutoCloseable {
public Double timeout;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public SetInputFilesOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -2981,9 +2945,7 @@ public interface Page extends AutoCloseable {
*/
public List<KeyboardModifier> modifiers;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -3006,7 +2968,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public Boolean trial;
@@ -3028,9 +2991,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public TapOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -3072,7 +3033,8 @@ public interface Page extends AutoCloseable {
/**
* When set, this method only performs the <a href="https://playwright.dev/java/docs/actionability">actionability</a>
* checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without
* performing it.
* performing it. Note that keyboard {@code modifiers} will be pressed regardless of {@code trial} to allow testing
* elements which are only visible when those keys are pressed.
*/
public TapOptions setTrial(boolean trial) {
this.trial = trial;
@@ -3118,9 +3080,7 @@ public interface Page extends AutoCloseable {
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -3144,9 +3104,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public TypeOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -3178,9 +3136,7 @@ public interface Page extends AutoCloseable {
*/
public Boolean force;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public Boolean noWaitAfter;
/**
@@ -3216,9 +3172,7 @@ public interface Page extends AutoCloseable {
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
* @deprecated This option has no effect.
*/
public UncheckOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
@@ -3792,6 +3746,12 @@ public interface Page extends AutoCloseable {
return this;
}
}
/**
* Playwright has ability to mock clock and passage of time.
*
* @since v1.45
*/
Clock clock();
/**
* Adds a script which would be evaluated in one of the following scenarios:
* <ul>
@@ -3896,7 +3856,6 @@ public interface Page extends AutoCloseable {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked. If not, this method throws.</li>
* </ol>
*
@@ -3919,7 +3878,6 @@ public interface Page extends AutoCloseable {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked. If not, this method throws.</li>
* </ol>
*
@@ -4019,8 +3977,6 @@ public interface Page extends AutoCloseable {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to double click in the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set. Note that if the
* first click of the {@code dblclick()} triggers a navigation event, this method will throw.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -4043,8 +3999,6 @@ public interface Page extends AutoCloseable {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to double click in the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set. Note that if the
* first click of the {@code dblclick()} triggers a navigation event, this method will throw.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -4623,21 +4577,6 @@ public interface Page extends AutoCloseable {
* }
* }</pre>
*
* <p> An example of passing an element handle:
* <pre>{@code
* page.exposeBinding("clicked", (source, args) -> {
* ElementHandle element = (ElementHandle) args[0];
* System.out.println(element.textContent());
* return null;
* }, new Page.ExposeBindingOptions().setHandle(true));
* page.setContent("" +
* "<script>\n" +
* " document.addEventListener('click', event => window.clicked(event.target));\n" +
* "</script>\n" +
* "<div>Click me</div>\n" +
* "<div>Or click me</div>\n");
* }</pre>
*
* @param name Name of the function on the window object.
* @param callback Callback function that will be called in the Playwright's context.
* @since v1.8
@@ -4688,21 +4627,6 @@ public interface Page extends AutoCloseable {
* }
* }</pre>
*
* <p> An example of passing an element handle:
* <pre>{@code
* page.exposeBinding("clicked", (source, args) -> {
* ElementHandle element = (ElementHandle) args[0];
* System.out.println(element.textContent());
* return null;
* }, new Page.ExposeBindingOptions().setHandle(true));
* page.setContent("" +
* "<script>\n" +
* " document.addEventListener('click', event => window.clicked(event.target));\n" +
* "</script>\n" +
* "<div>Click me</div>\n" +
* "<div>Or click me</div>\n");
* }</pre>
*
* @param name Name of the function on the window object.
* @param callback Callback function that will be called in the Playwright's context.
* @since v1.8
@@ -5460,7 +5384,7 @@ public interface Page extends AutoCloseable {
Locator getByTitle(Pattern text, GetByTitleOptions options);
/**
* Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the
* last redirect. If can not go back, returns {@code null}.
* last redirect. If cannot go back, returns {@code null}.
*
* <p> Navigate to the previous page in history.
*
@@ -5471,7 +5395,7 @@ public interface Page extends AutoCloseable {
}
/**
* Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the
* last redirect. If can not go back, returns {@code null}.
* last redirect. If cannot go back, returns {@code null}.
*
* <p> Navigate to the previous page in history.
*
@@ -5480,7 +5404,7 @@ public interface Page extends AutoCloseable {
Response goBack(GoBackOptions options);
/**
* Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the
* last redirect. If can not go forward, returns {@code null}.
* last redirect. If cannot go forward, returns {@code null}.
*
* <p> Navigate to the next page in history.
*
@@ -5491,13 +5415,32 @@ public interface Page extends AutoCloseable {
}
/**
* Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the
* last redirect. If can not go forward, returns {@code null}.
* last redirect. If cannot go forward, returns {@code null}.
*
* <p> Navigate to the next page in history.
*
* @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.
@@ -5567,7 +5510,6 @@ public interface Page extends AutoCloseable {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to hover over the center of the element, or the specified
* {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -5588,7 +5530,6 @@ public interface Page extends AutoCloseable {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to hover over the center of the element, or the specified
* {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -5859,8 +5800,7 @@ public interface Page extends AutoCloseable {
* <p> User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from
* the place it was paused.
*
* <p> <strong>NOTE:</strong> This method requires Playwright to be started in a headed mode, with a falsy {@code headless} value in the {@link
* com.microsoft.playwright.BrowserType#launch BrowserType.launch()}.
* <p> <strong>NOTE:</strong> This method requires Playwright to be started in a headed mode, with a falsy {@code headless} option.
*
* @since v1.9
*/
@@ -6127,15 +6067,13 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> Running the handler will alter your page state mid-test. For example it will change the currently focused element and
* move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and
* mouse state being unchanged. <br /> <br /> For example, consider a test that calls {@link
* com.microsoft.playwright.Locator#focus Locator.focus()} followed by {@link com.microsoft.playwright.Keyboard#press
* Keyboard.press()}. If your handler clicks a button between these two actions, the focused element most likely will be
* wrong, and key press will happen on the unexpected element. Use {@link com.microsoft.playwright.Locator#press
* Locator.press()} instead to avoid this problem. <br /> <br /> Another example is a series of mouse actions, where {@link
* com.microsoft.playwright.Mouse#move Mouse.move()} is followed by {@link com.microsoft.playwright.Mouse#down
* Mouse.down()}. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse
* down. Prefer self-contained actions like {@link com.microsoft.playwright.Locator#click Locator.click()} that do not rely
* on the state being unchanged by a handler.
* mouse state being unchanged.For example, consider a test that calls {@link com.microsoft.playwright.Locator#focus Locator.focus()} followed by
* {@link com.microsoft.playwright.Keyboard#press Keyboard.press()}. If your handler clicks a button between these two
* actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use {@link
* com.microsoft.playwright.Locator#press Locator.press()} instead to avoid this problem.Another example is a series of mouse actions, where {@link com.microsoft.playwright.Mouse#move Mouse.move()} is followed
* by {@link com.microsoft.playwright.Mouse#down Mouse.down()}. Again, when the handler runs between these two actions, the
* mouse position will be wrong during the mouse down. Prefer self-contained actions like {@link
* com.microsoft.playwright.Locator#click Locator.click()} that do not rely on the state being unchanged by a handler.
*
* <p> <strong>Usage</strong>
*
@@ -6221,15 +6159,13 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> Running the handler will alter your page state mid-test. For example it will change the currently focused element and
* move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and
* mouse state being unchanged. <br /> <br /> For example, consider a test that calls {@link
* com.microsoft.playwright.Locator#focus Locator.focus()} followed by {@link com.microsoft.playwright.Keyboard#press
* Keyboard.press()}. If your handler clicks a button between these two actions, the focused element most likely will be
* wrong, and key press will happen on the unexpected element. Use {@link com.microsoft.playwright.Locator#press
* Locator.press()} instead to avoid this problem. <br /> <br /> Another example is a series of mouse actions, where {@link
* com.microsoft.playwright.Mouse#move Mouse.move()} is followed by {@link com.microsoft.playwright.Mouse#down
* Mouse.down()}. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse
* down. Prefer self-contained actions like {@link com.microsoft.playwright.Locator#click Locator.click()} that do not rely
* on the state being unchanged by a handler.
* mouse state being unchanged.For example, consider a test that calls {@link com.microsoft.playwright.Locator#focus Locator.focus()} followed by
* {@link com.microsoft.playwright.Keyboard#press Keyboard.press()}. If your handler clicks a button between these two
* actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use {@link
* com.microsoft.playwright.Locator#press Locator.press()} instead to avoid this problem.Another example is a series of mouse actions, where {@link com.microsoft.playwright.Mouse#move Mouse.move()} is followed
* by {@link com.microsoft.playwright.Mouse#down Mouse.down()}. Again, when the handler runs between these two actions, the
* mouse position will be wrong during the mouse down. Prefer self-contained actions like {@link
* com.microsoft.playwright.Locator#click Locator.click()} that do not rely on the state being unchanged by a handler.
*
* <p> <strong>Usage</strong>
*
@@ -6326,7 +6262,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6385,7 +6321,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6442,7 +6378,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6501,7 +6437,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6558,7 +6494,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6617,7 +6553,7 @@ public interface Page extends AutoCloseable {
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept requests intercepted by Service Worker. See
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* when using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
@@ -6671,7 +6607,7 @@ public interface Page extends AutoCloseable {
*
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <a
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code
* path} is a relative path, then it is resolved relative to the current working directory.
@@ -6686,13 +6622,88 @@ public interface Page extends AutoCloseable {
*
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <a
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
* using request interception by setting {@code serviceWorkers} to {@code "block"}.
*
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code
* path} is a relative path, then it is resolved relative to the current working directory.
* @since v1.23
*/
void routeFromHAR(Path har, RouteFromHAROptions options);
/**
* This method allows to modify websocket connections that are made by the page.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before navigating the page.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple mock that responds to a single message. See {@code WebSocketRoute} for more details and
* examples.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* ws.onMessage(message -> {
* if ("request".equals(message))
* ws.send("response");
* });
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(String url, Consumer<WebSocketRoute> handler);
/**
* This method allows to modify websocket connections that are made by the page.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before navigating the page.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple mock that responds to a single message. See {@code WebSocketRoute} for more details and
* examples.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* ws.onMessage(message -> {
* if ("request".equals(message))
* ws.send("response");
* });
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(Pattern url, Consumer<WebSocketRoute> handler);
/**
* This method allows to modify websocket connections that are made by the page.
*
* <p> Note that only {@code WebSocket}s created after this method was called will be routed. It is recommended to call this
* method before navigating the page.
*
* <p> <strong>Usage</strong>
*
* <p> Below is an example of a simple mock that responds to a single message. See {@code WebSocketRoute} for more details and
* examples.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* ws.onMessage(message -> {
* if ("request".equals(message))
* ws.send("response");
* });
* });
* }</pre>
*
* @param url Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the {@code
* baseURL} context option.
* @param handler Handler function to route the WebSocket.
* @since v1.48
*/
void routeWebSocket(Predicate<String> url, Consumer<WebSocketRoute> handler);
/**
* Returns the buffer with the captured screenshot.
*
@@ -7101,7 +7112,6 @@ public interface Page extends AutoCloseable {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked or unchecked. If not, this method throws.</li>
* </ol>
*
@@ -7125,7 +7135,6 @@ public interface Page extends AutoCloseable {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now checked or unchecked. If not, this method throws.</li>
* </ol>
*
@@ -7200,7 +7209,8 @@ public interface Page extends AutoCloseable {
void setExtraHTTPHeaders(Map<String, String> headers);
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code selector} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -7216,7 +7226,8 @@ public interface Page extends AutoCloseable {
}
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code selector} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -7230,7 +7241,8 @@ public interface Page extends AutoCloseable {
void setInputFiles(String selector, Path files, SetInputFilesOptions options);
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code selector} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -7246,7 +7258,8 @@ public interface Page extends AutoCloseable {
}
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code selector} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -7260,7 +7273,8 @@ public interface Page extends AutoCloseable {
void setInputFiles(String selector, Path[] files, SetInputFilesOptions options);
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code selector} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -7276,7 +7290,8 @@ public interface Page extends AutoCloseable {
}
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code selector} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -7290,7 +7305,8 @@ public interface Page extends AutoCloseable {
void setInputFiles(String selector, FilePayload files, SetInputFilesOptions options);
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code selector} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -7306,7 +7322,8 @@ public interface Page extends AutoCloseable {
}
/**
* Sets the value of the file input to these file paths or files. If some of the {@code filePaths} are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
* they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with
* a {@code [webkitdirectory]} attribute, only a single directory path is supported.
*
* <p> This method expects {@code selector} to point to an <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input element</a>. However, if the element is
@@ -7336,6 +7353,8 @@ public interface Page extends AutoCloseable {
* page.navigate("https://example.com");
* }</pre>
*
* @param width Page width in pixels.
* @param height Page height in pixels.
* @since v1.8
*/
void setViewportSize(int width, int height);
@@ -7348,7 +7367,6 @@ public interface Page extends AutoCloseable {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#touchscreen Page.touchscreen()} to tap the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -7372,7 +7390,6 @@ public interface Page extends AutoCloseable {
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#touchscreen Page.touchscreen()} to tap the center of the element, or the
* specified {@code position}.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* </ol>
*
* <p> When all steps combined have not finished during the specified {@code timeout}, this method throws a {@code
@@ -7445,7 +7462,6 @@ public interface Page extends AutoCloseable {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now unchecked. If not, this method throws.</li>
* </ol>
*
@@ -7468,7 +7484,6 @@ public interface Page extends AutoCloseable {
* unless {@code force} option is set. If the element is detached during the checks, the whole action is retried.</li>
* <li> Scroll the element into view if needed.</li>
* <li> Use {@link com.microsoft.playwright.Page#mouse Page.mouse()} to click in the center of the element.</li>
* <li> Wait for initiated navigations to either succeed or fail, unless {@code noWaitAfter} option is set.</li>
* <li> Ensure that the element is now unchecked. If not, this method throws.</li>
* </ol>
*
@@ -8084,7 +8099,7 @@ public interface Page extends AutoCloseable {
* });
*
* // Waits for the next response matching some conditions
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> {
* // Triggers the response
* page.getByText("trigger response").click();
* });
@@ -8112,7 +8127,7 @@ public interface Page extends AutoCloseable {
* });
*
* // Waits for the next response matching some conditions
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> {
* // Triggers the response
* page.getByText("trigger response").click();
* });
@@ -8138,7 +8153,7 @@ public interface Page extends AutoCloseable {
* });
*
* // Waits for the next response matching some conditions
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> {
* // Triggers the response
* page.getByText("trigger response").click();
* });
@@ -8166,7 +8181,7 @@ public interface Page extends AutoCloseable {
* });
*
* // Waits for the next response matching some conditions
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> {
* // Triggers the response
* page.getByText("trigger response").click();
* });
@@ -8192,7 +8207,7 @@ public interface Page extends AutoCloseable {
* });
*
* // Waits for the next response matching some conditions
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> {
* // Triggers the response
* page.getByText("trigger response").click();
* });
@@ -8220,7 +8235,7 @@ public interface Page extends AutoCloseable {
* });
*
* // Waits for the next response matching some conditions
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
* Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> {
* // Triggers the response
* page.getByText("trigger response").click();
* });
@@ -99,7 +99,7 @@ public interface Request {
*/
List<HttpHeader> headersArray();
/**
* Returns the value of the header matching the name. The name is case insensitive.
* Returns the value of the header matching the name. The name is case-insensitive.
*
* @param name Name of the header.
* @since v1.15
@@ -71,7 +71,7 @@ public interface Response {
*/
List<HttpHeader> headersArray();
/**
* Returns the value of the header matching the name. The name is case insensitive. If multiple headers have the same name
* Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same name
* (except {@code set-cookie}), they are returned as a list separated by {@code , }. For {@code set-cookie}, the {@code \n}
* separator is used. If no headers are found, {@code null} is returned.
*
@@ -80,7 +80,7 @@ public interface Response {
*/
String headerValue(String name);
/**
* Returns all values of the headers matching the name, for example {@code set-cookie}. The name is case insensitive.
* Returns all values of the headers matching the name, for example {@code set-cookie}. The name is case-insensitive.
*
* @param name Name of the header.
* @since v1.15
@@ -147,6 +147,12 @@ public interface Route {
* exceeded. Defaults to {@code 20}. Pass {@code 0} to not follow redirects.
*/
public Integer maxRedirects;
/**
* Maximum number of times network errors should be retried. Currently only {@code ECONNRESET} error is retried. Does not
* retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to {@code 0} - no
* retries.
*/
public Integer maxRetries;
/**
* If set changes the request method (e.g. GET or POST).
*/
@@ -179,6 +185,15 @@ public interface Route {
this.maxRedirects = maxRedirects;
return this;
}
/**
* Maximum number of times network errors should be retried. Currently only {@code ECONNRESET} error is retried. Does not
* retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to {@code 0} - no
* retries.
*/
public FetchOptions setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
return this;
}
/**
* If set changes the request method (e.g. GET or POST).
*/
@@ -333,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
@@ -353,13 +368,17 @@ public interface Route {
* through redirects, use the combination of {@link com.microsoft.playwright.Route#fetch Route.fetch()} and {@link
* com.microsoft.playwright.Route#fulfill Route.fulfill()} instead.
*
* <p> {@link com.microsoft.playwright.Route#resume Route.resume()} will immediately send the request to the network, other
* matching handlers won't be invoked. Use {@link com.microsoft.playwright.Route#fallback Route.fallback()} If you want
* next matching handler in the chain to be invoked.
*
* @since v1.8
*/
default void resume() {
resume(null);
}
/**
* Continues route's request with optional overrides.
* Sends route's request to the network with optional overrides.
*
* <p> <strong>Usage</strong>
* <pre>{@code
@@ -379,16 +398,23 @@ public interface Route {
* through redirects, use the combination of {@link com.microsoft.playwright.Route#fetch Route.fetch()} and {@link
* com.microsoft.playwright.Route#fulfill Route.fulfill()} instead.
*
* <p> {@link com.microsoft.playwright.Route#resume Route.resume()} will immediately send the request to the network, other
* matching handlers won't be invoked. Use {@link com.microsoft.playwright.Route#fallback Route.fallback()} If you want
* next matching handler in the chain to be invoked.
*
* @since v1.8
*/
void resume(ResumeOptions options);
/**
* When several routes match the given pattern, they run in the order opposite to their registration. That way the last
* Continues route's request with optional overrides. The method is similar to {@link com.microsoft.playwright.Route#resume
* Route.resume()} with the difference that other matching handlers will be invoked before sending the request.
*
* <p> <strong>Usage</strong>
*
* <p> When several routes match the given pattern, they run in the order opposite to their registration. That way the last
* registered route can always override all the previous ones. In the example below, request will be handled by the
* bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
* registered route.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.route("**\/*", route -> {
* // Runs last.
@@ -442,18 +468,24 @@ public interface Route {
* });
* }</pre>
*
* <p> Use {@link com.microsoft.playwright.Route#resume Route.resume()} to immediately send the request to the network, other
* matching handlers won't be invoked in that case.
*
* @since v1.23
*/
default void fallback() {
fallback(null);
}
/**
* When several routes match the given pattern, they run in the order opposite to their registration. That way the last
* Continues route's request with optional overrides. The method is similar to {@link com.microsoft.playwright.Route#resume
* Route.resume()} with the difference that other matching handlers will be invoked before sending the request.
*
* <p> <strong>Usage</strong>
*
* <p> When several routes match the given pattern, they run in the order opposite to their registration. That way the last
* registered route can always override all the previous ones. In the example below, request will be handled by the
* bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
* registered route.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.route("**\/*", route -> {
* // Runs last.
@@ -507,6 +539,9 @@ public interface Route {
* });
* }</pre>
*
* <p> Use {@link com.microsoft.playwright.Route#resume Route.resume()} to immediately send the request to the network, other
* matching handlers won't be invoked in that case.
*
* @since v1.23
*/
void fallback(FallbackOptions options);
@@ -28,6 +28,8 @@ public interface Touchscreen {
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#tap Page.tap()} the method will throw if {@code hasTouch} option of the browser
* context is false.
*
* @param x X coordinate relative to the main frame's viewport in CSS pixels.
* @param y Y coordinate relative to the main frame's viewport in CSS pixels.
* @since v1.8
*/
void tap(double x, double y);
@@ -39,8 +39,8 @@ public interface Tracing {
class StartOptions {
/**
* If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the {@code
* tracesDir} folder specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify the
* final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stop
* tracesDir} directory specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify
* the final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stop
* Tracing.stop()} instead.
*/
public String name;
@@ -69,8 +69,8 @@ public interface Tracing {
/**
* If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the {@code
* tracesDir} folder specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify the
* final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stop
* tracesDir} directory specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify
* the final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stop
* Tracing.stop()} instead.
*/
public StartOptions setName(String name) {
@@ -115,8 +115,8 @@ public interface Tracing {
class StartChunkOptions {
/**
* If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the {@code
* tracesDir} folder specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify the
* final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stopChunk
* tracesDir} directory specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify
* the final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stopChunk
* Tracing.stopChunk()} instead.
*/
public String name;
@@ -127,8 +127,8 @@ public interface Tracing {
/**
* If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the {@code
* tracesDir} folder specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify the
* final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stopChunk
* tracesDir} directory specified in {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. To specify
* the final trace zip file name, you need to pass {@code path} option to {@link com.microsoft.playwright.Tracing#stopChunk
* Tracing.stopChunk()} instead.
*/
public StartChunkOptions setName(String name) {
@@ -0,0 +1,223 @@
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.playwright;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Whenever a <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket">{@code WebSocket}</a> route is set up
* with {@link com.microsoft.playwright.Page#routeWebSocket Page.routeWebSocket()} or {@link
* com.microsoft.playwright.BrowserContext#routeWebSocket BrowserContext.routeWebSocket()}, the {@code WebSocketRoute}
* object allows to handle the WebSocket, like an actual server would do.
*
* <p> <strong>Mocking</strong>
*
* <p> By default, the routed WebSocket will not connect to the server. This way, you can mock entire communcation over the
* WebSocket. Here is an example that responds to a {@code "request"} with a {@code "response"}.
* <pre>{@code
* page.routeWebSocket("wss://example.com/ws", ws -> {
* ws.onMessage(message -> {
* if ("request".equals(message))
* ws.send("response");
* });
* });
* }</pre>
*
* <p> Since we do not call {@link com.microsoft.playwright.WebSocketRoute#connectToServer WebSocketRoute.connectToServer()}
* inside the WebSocket route handler, Playwright assumes that WebSocket will be mocked, and opens the WebSocket inside the
* page automatically.
*
* <p> Here is another example that handles JSON messages:
* <pre>{@code
* page.routeWebSocket("wss://example.com/ws", ws -> {
* ws.onMessage(message -> {
* JsonObject json = new JsonParser().parse(message).getAsJsonObject();
* if ("question".equals(json.get("request").getAsString())) {
* Map<String, String> result = new HashMap();
* result.put("response", "answer");
* ws.send(gson.toJson(result));
* }
* });
* });
* }</pre>
*
* <p> <strong>Intercepting</strong>
*
* <p> Alternatively, you may want to connect to the actual server, but intercept messages in-between and modify or block them.
* Calling {@link com.microsoft.playwright.WebSocketRoute#connectToServer WebSocketRoute.connectToServer()} returns a
* server-side {@code WebSocketRoute} instance that you can send messages to, or handle incoming messages.
*
* <p> Below is an example that modifies some messages sent by the page to the server. Messages sent from the server to the
* page are left intact, relying on the default forwarding.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* WebSocketRoute server = ws.connectToServer();
* ws.onMessage(message -> {
* if ("request".equals(message))
* server.send("request2");
* else
* server.send(message);
* });
* });
* }</pre>
*
* <p> After connecting to the server, all **messages are forwarded** between the page and the server by default.
*
* <p> However, if you call {@link com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} on the
* original route, messages from the page to the server **will not be forwarded** anymore, but should instead be handled by
* the {@code handler}.
*
* <p> Similarly, calling {@link com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} on the
* server-side WebSocket will **stop forwarding messages** from the server to the page, and {@code handler} should take
* care of them.
*
* <p> The following example blocks some messages in both directions. Since it calls {@link
* com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} in both directions, there is no automatic
* forwarding at all.
* <pre>{@code
* page.routeWebSocket("/ws", ws -> {
* WebSocketRoute server = ws.connectToServer();
* ws.onMessage(message -> {
* if (!"blocked-from-the-page".equals(message))
* server.send(message);
* });
* server.onMessage(message -> {
* if (!"blocked-from-the-server".equals(message))
* ws.send(message);
* });
* });
* }</pre>
*/
public interface WebSocketRoute {
class CloseOptions {
/**
* Optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code">close code</a>.
*/
public Integer code;
/**
* Optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason">close reason</a>.
*/
public String reason;
/**
* Optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code">close code</a>.
*/
public CloseOptions setCode(int code) {
this.code = code;
return this;
}
/**
* Optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason">close reason</a>.
*/
public CloseOptions setReason(String reason) {
this.reason = reason;
return this;
}
}
/**
* Closes one side of the WebSocket connection.
*
* @since v1.48
*/
default void close() {
close(null);
}
/**
* Closes one side of the WebSocket connection.
*
* @since v1.48
*/
void close(CloseOptions options);
/**
* By default, routed WebSocket does not connect to the server, so you can mock entire WebSocket communication. This method
* connects to the actual WebSocket server, and returns the server-side {@code WebSocketRoute} instance, giving the ability
* to send and receive messages from the server.
*
* <p> Once connected to the server:
* <ul>
* <li> Messages received from the server will be **automatically forwarded** to the WebSocket in the page, unless {@link
* com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} is called on the server-side {@code
* WebSocketRoute}.</li>
* <li> Messages sent by the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send">{@code
* WebSocket.send()}</a> call in the page will be **automatically forwarded** to the server, unless {@link
* com.microsoft.playwright.WebSocketRoute#onMessage WebSocketRoute.onMessage()} is called on the original {@code
* WebSocketRoute}.</li>
* </ul>
*
* <p> See examples at the top for more details.
*
* @since v1.48
*/
WebSocketRoute connectToServer();
/**
* Allows to handle <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close">{@code WebSocket.close}</a>.
*
* <p> By default, closing one side of the connection, either in the page or on the server, will close the other side. However,
* when {@link com.microsoft.playwright.WebSocketRoute#onClose WebSocketRoute.onClose()} handler is set up, the default
* forwarding of closure is disabled, and handler should take care of it.
*
* @param handler Function that will handle WebSocket closure. Received an optional <a
* href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code">close code</a> and an optional <a
* href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason">close reason</a>.
* @since v1.48
*/
void onClose(BiConsumer<Integer, String> handler);
/**
* This method allows to handle messages that are sent by the WebSocket, either from the page or from the server.
*
* <p> When called on the original WebSocket route, this method handles messages sent from the page. You can handle this
* messages by responding to them with {@link com.microsoft.playwright.WebSocketRoute#send WebSocketRoute.send()},
* forwarding them to the server-side connection returned by {@link com.microsoft.playwright.WebSocketRoute#connectToServer
* WebSocketRoute.connectToServer()} or do something else.
*
* <p> Once this method is called, messages are not automatically forwarded to the server or to the page - you should do that
* manually by calling {@link com.microsoft.playwright.WebSocketRoute#send WebSocketRoute.send()}. See examples at the top
* for more details.
*
* <p> Calling this method again will override the handler with a new one.
*
* @param handler Function that will handle messages.
* @since v1.48
*/
void onMessage(Consumer<WebSocketFrame> handler);
/**
* Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called on
* the result of {@link com.microsoft.playwright.WebSocketRoute#connectToServer WebSocketRoute.connectToServer()}, sends
* the message to the server. See examples at the top for more details.
*
* @param message Message to send.
* @since v1.48
*/
void send(String message);
/**
* Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called on
* the result of {@link com.microsoft.playwright.WebSocketRoute#connectToServer WebSocketRoute.connectToServer()}, sends
* the message to the server. See examples at the top for more details.
*
* @param message Message to send.
* @since v1.48
*/
void send(byte[] message);
/**
* URL of the WebSocket created in the page.
*
* @since v1.48
*/
String url();
}
@@ -752,10 +752,10 @@ public interface LocatorAssertions {
* assertThat(page.getByText("Welcome")).isVisible();
*
* // At least one item in the list is visible.
* asserThat(page.getByTestId("todo-item").first()).isVisible();
* assertThat(page.getByTestId("todo-item").first()).isVisible();
*
* // At least one of the two elements is visible, possibly both.
* asserThat(
* assertThat(
* page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in"))
* .or(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign up")))
* .first()
@@ -780,10 +780,10 @@ public interface LocatorAssertions {
* assertThat(page.getByText("Welcome")).isVisible();
*
* // At least one item in the list is visible.
* asserThat(page.getByTestId("todo-item").first()).isVisible();
* assertThat(page.getByTestId("todo-item").first()).isVisible();
*
* // At least one of the two elements is visible, possibly both.
* asserThat(
* assertThat(
* page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in"))
* .or(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign up")))
* .first()
@@ -37,6 +37,7 @@ import static com.microsoft.playwright.impl.Utils.toFilePayload;
class APIRequestContextImpl extends ChannelOwner implements APIRequestContext {
private final TracingImpl tracing;
private String disposeReason;
APIRequestContextImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
@@ -49,8 +50,17 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext {
}
@Override
public void dispose() {
withLogging("APIRequestContext.dispose", () -> sendMessage("dispose"));
public void dispose(DisposeOptions options) {
withLogging("APIRequestContext.dispose", () -> disposeImpl(options));
}
private void disposeImpl(DisposeOptions options) {
if (options == null) {
options = new DisposeOptions();
}
disposeReason = options.reason;
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
sendMessage("dispose", params);
}
@Override
@@ -77,6 +87,9 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext {
}
private APIResponse fetchImpl(String url, RequestOptionsImpl options) {
if (disposeReason != null) {
throw new PlaywrightException(disposeReason);
}
if (options == null) {
options = new RequestOptionsImpl();
}
@@ -107,7 +120,7 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext {
}
}
if (bytes == null) {
params.addProperty("jsonData", gson().toJson(options.data));
params.addProperty("jsonData", jsonDataSerializer.toJson(options.data));
} else {
String base64 = Base64.getEncoder().encodeToString(bytes);
params.addProperty("postData", base64);
@@ -134,6 +147,12 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext {
}
params.addProperty("maxRedirects", options.maxRedirects);
}
if (options.maxRetries != null) {
if (options.maxRetries < 0) {
throw new PlaywrightException("'maxRetries' must be greater than or equal to '0'");
}
params.addProperty("maxRetries", options.maxRetries);
}
JsonObject json = sendMessage("fetch", params).getAsJsonObject();
return new APIResponseImpl(this, json.getAsJsonObject("response"));
}
@@ -17,15 +17,21 @@
package com.microsoft.playwright.impl;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.microsoft.playwright.APIRequest;
import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.options.ClientCertificate;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Base64;
import java.util.List;
import static com.microsoft.playwright.impl.Serialization.gson;
import static com.microsoft.playwright.impl.Utils.addToProtocol;
import static java.nio.file.Files.readAllBytes;
class APIRequestImpl implements APIRequest {
private final PlaywrightImpl playwright;
@@ -42,6 +48,8 @@ class APIRequestImpl implements APIRequest {
private APIRequestContextImpl newContextImpl(NewContextOptions options) {
if (options == null) {
options = new NewContextOptions();
} else {
options = Utils.clone(options);
}
if (options.storageStatePath != null) {
try {
@@ -57,11 +65,13 @@ class APIRequestImpl implements APIRequest {
storageState = new Gson().fromJson(options.storageState, JsonObject.class);
options.storageState = null;
}
List<ClientCertificate> clientCertificateList = options.clientCertificates;
options.clientCertificates = null;
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
if (storageState != null) {
params.add("storageState", storageState);
}
addToProtocol(params, clientCertificateList);
JsonObject result = playwright.sendMessage("newRequest", params).getAsJsonObject();
APIRequestContextImpl context = playwright.connection.getExistingObject(result.getAsJsonObject("request").get("guid").getAsString());
return context;
@@ -36,8 +36,7 @@ import java.util.regex.Pattern;
import static com.microsoft.playwright.impl.Serialization.addHarUrlFilter;
import static com.microsoft.playwright.impl.Serialization.gson;
import static com.microsoft.playwright.impl.Utils.isSafeCloseError;
import static com.microsoft.playwright.impl.Utils.toJsRegexFlags;
import static com.microsoft.playwright.impl.Utils.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.readAllBytes;
import static java.util.Arrays.asList;
@@ -46,10 +45,12 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
private final BrowserImpl browser;
private final TracingImpl tracing;
private final APIRequestContextImpl request;
private final ClockImpl clock;
final List<PageImpl> pages = new ArrayList<>();
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<>();
@@ -104,6 +105,7 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
}
tracing = connection.getExistingObject(initializer.getAsJsonObject("tracing").get("guid").getAsString());
request = connection.getExistingObject(initializer.getAsJsonObject("requestContext").get("guid").getAsString());
clock = new ClockImpl(this);
closePromise = new WaitableEvent<>(listeners, EventType.CLOSE);
}
@@ -231,6 +233,11 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
listeners.remove(EventType.RESPONSE, handler);
}
@Override
public ClockImpl clock() {
return clock;
}
private <T> T waitForEventWithTimeout(EventType eventType, Runnable code, Predicate<T> predicate, Double timeout) {
List<Waitable<T>> waitables = new ArrayList<>();
waitables.add(new WaitableEvent<>(listeners, eventType, predicate));
@@ -284,6 +291,7 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
options = new CloseOptions();
}
closeReason = options.reason;
request.dispose(convertType(options, APIRequestContext.DisposeOptions.class));
for (Map.Entry<String, HarRecorder> entry : harRecorders.entrySet()) {
JsonObject params = new JsonObject();
params.addProperty("harId", entry.getKey());
@@ -507,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) {
@@ -674,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) {
@@ -684,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());
}
@@ -723,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);
@@ -208,6 +208,7 @@ class BrowserImpl extends ChannelOwner implements Browser {
params.addProperty("noDefaultViewport", true);
}
}
addToProtocol(params, options.clientCertificates);
params.remove("acceptDownloads");
if (options.acceptDownloads != null) {
params.addProperty("acceptDownloads", options.acceptDownloads ? "accept" : "deny");
@@ -30,6 +30,7 @@ import java.util.function.Consumer;
import static com.microsoft.playwright.impl.Serialization.addHarUrlFilter;
import static com.microsoft.playwright.impl.Serialization.gson;
import static com.microsoft.playwright.impl.Utils.addToProtocol;
import static com.microsoft.playwright.impl.Utils.convertType;
class BrowserTypeImpl extends ChannelOwner implements BrowserType {
@@ -221,6 +222,7 @@ class BrowserTypeImpl extends ChannelOwner implements BrowserType {
params.addProperty("noDefaultViewport", true);
}
}
addToProtocol(params, options.clientCertificates);
params.remove("acceptDownloads");
if (options.acceptDownloads != null) {
params.addProperty("acceptDownloads", options.acceptDownloads ? "accept" : "deny");
@@ -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);
@@ -0,0 +1,129 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonObject;
import com.microsoft.playwright.Clock;
import java.util.Date;
class ClockImpl implements Clock {
private final ChannelOwner browserContext;
ClockImpl(BrowserContextImpl browserContext) {
this.browserContext = browserContext;
}
@Override
public void fastForward(long ticks) {
JsonObject params = new JsonObject();
params.addProperty("ticksNumber", ticks);
browserContext.sendMessage("clockFastForward", params);
}
@Override
public void fastForward(String ticks) {
JsonObject params = new JsonObject();
params.addProperty("ticksString", ticks);
browserContext.sendMessage("clockFastForward", params);
}
@Override
public void install(InstallOptions options) {
JsonObject params = new JsonObject();
if (options != null) {
parseTime(options.time, params);
}
browserContext.sendMessage("clockInstall", params);
}
@Override
public void runFor(long ticks) {
JsonObject params = new JsonObject();
params.addProperty("ticksNumber", ticks);
browserContext.sendMessage("clockRunFor", params);
}
@Override
public void runFor(String ticks) {
JsonObject params = new JsonObject();
params.addProperty("ticksString", ticks);
browserContext.sendMessage("clockRunFor", params);
}
@Override
public void pauseAt(long time) {
JsonObject params = new JsonObject();
params.addProperty("timeNumber", time);
browserContext.sendMessage("clockPauseAt", params);
}
@Override
public void pauseAt(String time) {
JsonObject params = new JsonObject();
params.addProperty("timeString", time);
browserContext.sendMessage("clockPauseAt", params);
}
@Override
public void pauseAt(Date time) {
JsonObject params = new JsonObject();
params.addProperty("timeNumber", time.getTime());
browserContext.sendMessage("clockPauseAt", params);
}
@Override
public void resume() {
browserContext.sendMessage("clockResume");
}
@Override
public void setFixedTime(long time) {
JsonObject params = new JsonObject();
params.addProperty("timeNumber", time);
browserContext.sendMessage("clockSetFixedTime", params);
}
@Override
public void setFixedTime(String time) {
JsonObject params = new JsonObject();
params.addProperty("timeString", time);
browserContext.sendMessage("clockSetFixedTime", params);
}
@Override
public void setFixedTime(Date time) {
JsonObject params = new JsonObject();
params.addProperty("timeNumber", time.getTime());
browserContext.sendMessage("clockSetFixedTime", params);
}
@Override
public void setSystemTime(long time) {
JsonObject params = new JsonObject();
params.addProperty("timeNumber", time);
browserContext.sendMessage("clockSetSystemTime", params);
}
@Override
public void setSystemTime(String time) {
JsonObject params = new JsonObject();
params.addProperty("timeString", time);
browserContext.sendMessage("clockSetSystemTime", params);
}
@Override
public void setSystemTime(Date time) {
JsonObject params = new JsonObject();
params.addProperty("timeNumber", time.getTime());
browserContext.sendMessage("clockSetSystemTime", params);
}
private static void parseTime(Object time, JsonObject params) {
if (time instanceof Long) {
params.addProperty("timeNumber", (Long) time);
} else if (time instanceof Date) {
params.addProperty("timeNumber", ((Date) time).getTime());
} else if (time instanceof String) {
params.addProperty("timeString", (String) time);
}
}
}
@@ -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;
@@ -21,11 +21,13 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.microsoft.playwright.ElementHandle;
import com.microsoft.playwright.Frame;
import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.options.BoundingBox;
import com.microsoft.playwright.options.ElementState;
import com.microsoft.playwright.options.FilePayload;
import com.microsoft.playwright.options.SelectOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
@@ -17,6 +17,7 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonObject;
import com.microsoft.playwright.PlaywrightException;
import java.util.*;
import java.util.function.Consumer;
@@ -46,6 +47,9 @@ class ListenerCollection <EventType> {
}
void add(EventType type, Consumer<?> listener) {
if (listener == null) {
throw new PlaywrightException("Can't add a null listener");
}
List<Consumer<?>> list = listeners.get(type);
if (list == null) {
list = new ArrayList<>();
@@ -27,6 +27,7 @@ import static com.microsoft.playwright.impl.Serialization.gson;
class LocalUtils extends ChannelOwner {
LocalUtils(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
markAsInternalType();
}
JsonArray deviceDescriptors() {
@@ -48,6 +48,7 @@ public class PageImpl extends ChannelOwner implements Page {
final Waitable<?> waitableClosedOrCrashed;
private ViewportSize viewport;
private final Router routes = new Router();
private final WebSocketRouter webSocketRoutes = new WebSocketRouter();
private final Set<FrameImpl> frames = new LinkedHashSet<>();
private final Map<Integer, LocatorHandler> locatorHandlers = new HashMap<>();
@@ -212,6 +213,11 @@ public class PageImpl extends ChannelOwner implements Page {
if (handled == Router.HandleResult.NoMatchingHandler || handled == Router.HandleResult.Fallback) {
browserContext.handleRoute(route);
}
} else if ("webSocketRoute".equals(event)) {
WebSocketRouteImpl route = connection.getExistingObject(params.getAsJsonObject("webSocketRoute").get("guid").getAsString());
if (!webSocketRoutes.handle(route)) {
browserContext.handleWebSocketRoute(route);
}
} else if ("video".equals(event)) {
String artifactGuid = params.getAsJsonObject("artifact").get("guid").getAsString();
ArtifactImpl artifact = connection.getExistingObject(artifactGuid);
@@ -431,6 +437,11 @@ public class PageImpl extends ChannelOwner implements Page {
listeners.remove(EventType.WORKER, handler);
}
@Override
public ClockImpl clock() {
return browserContext.clock();
}
@Override
public Page waitForClose(WaitForCloseOptions options, Runnable code) {
return withWaitLogging("Page.waitForClose", logger -> waitForCloseImpl(options, code));
@@ -922,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)));
@@ -1124,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));
@@ -1351,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();
@@ -33,6 +33,12 @@ class SerializedValue{
String d;
String u;
String bi;
public static class E {
String m;
String n;
String s;
}
E e;
public static class R {
String p;
String f;
@@ -33,6 +33,7 @@ public class RequestOptionsImpl implements RequestOptions {
Boolean ignoreHTTPSErrors;
Double timeout;
Integer maxRedirects;
Integer maxRetries;
@Override
public RequestOptions setHeader(String name, String value) {
@@ -125,4 +126,10 @@ public class RequestOptionsImpl implements RequestOptions {
this.maxRedirects = maxRedirects;
return this;
}
@Override
public RequestOptions setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
return this;
}
}
@@ -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);
}
}
@@ -24,9 +24,7 @@ import com.microsoft.playwright.ElementHandle;
import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.options.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.*;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.net.MalformedURLException;
@@ -35,11 +33,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.*;
import java.util.*;
import java.util.regex.Pattern;
@@ -55,6 +49,7 @@ class Serialization {
.registerTypeAdapter(ColorScheme.class, new ToLowerCaseAndDashSerializer<ColorScheme>())
.registerTypeAdapter(Media.class, new ToLowerCaseSerializer<Media>())
.registerTypeAdapter(ForcedColors.class, new ToLowerCaseSerializer<ForcedColors>())
.registerTypeAdapter(HttpCredentialsSend.class, new ToLowerCaseSerializer<HttpCredentialsSend>())
.registerTypeAdapter(ReducedMotion.class, new ToLowerCaseAndDashSerializer<ReducedMotion>())
.registerTypeAdapter(ScreenshotAnimations.class, new ToLowerCaseSerializer<ScreenshotAnimations>())
.registerTypeAdapter(ScreenshotType.class, new ToLowerCaseSerializer<ScreenshotType>())
@@ -76,6 +71,12 @@ class Serialization {
return gson;
}
static final Gson jsonDataSerializer = new GsonBuilder().disableHtmlEscaping()
.registerTypeAdapter(Date.class, new DateSerializer())
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer())
.registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeSerializer())
.serializeNulls().create();
static SerializedError serializeError(Throwable e) {
SerializedError result = new SerializedError();
result.error = new SerializedError.Error();
@@ -169,6 +170,14 @@ class Serialization {
result.r = new SerializedValue.R();
result.r.p = ((Pattern)value).pattern();
result.r.f = toJsRegexFlags(((Pattern)value));
} else if (value instanceof Exception) {
Exception exception = (Exception) value;
result.e = new SerializedValue.E();
result.e.m = exception.getMessage();
result.e.n = exception.getClass().getSimpleName();
StringWriter sw = new StringWriter();
exception.printStackTrace(new PrintWriter(sw));
result.e.s = sw.toString();
} else {
HashableValue mapKey = new HashableValue(value);
Integer id = valueToId.get(mapKey);
@@ -246,6 +255,9 @@ class Serialization {
return (T)(Date.from(Instant.parse(value.d)));
if (value.r != null)
return (T)(Pattern.compile(value.r.p, fromJsRegexFlags(value.r.f)));
if (value.e != null) {
return (T)new Exception(value.e.s);
}
if (value.v != null) {
switch (value.v) {
case "undefined":
@@ -303,6 +315,9 @@ class Serialization {
if (modifiers.contains(KeyboardModifier.CONTROL)) {
result.add("Control");
}
if (modifiers.contains(KeyboardModifier.CONTROLORMETA)) {
result.add("ControlOrMeta");
}
if (modifiers.contains(KeyboardModifier.META)) {
result.add("Meta");
}
@@ -514,6 +529,13 @@ class Serialization {
}
}
private static class OffsetDateTimeSerializer implements JsonSerializer<OffsetDateTime> {
@Override
public JsonElement serialize(OffsetDateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(dateFormat.format(Date.from(src.toInstant())));
}
}
private static class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime> {
@Override
public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
@@ -33,6 +33,7 @@ class TracingImpl extends ChannelOwner implements Tracing {
TracingImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
markAsInternalType();
}
private void stopChunkImpl(Path path) {
@@ -16,6 +16,8 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.microsoft.playwright.PlaywrightException;
import java.net.MalformedURLException;
@@ -25,6 +27,7 @@ import java.util.function.Predicate;
import java.util.regex.Pattern;
import static com.microsoft.playwright.impl.Utils.globToRegex;
import static com.microsoft.playwright.impl.Utils.toJsRegexFlags;
class UrlMatcher {
final Object rawSource;
@@ -17,8 +17,10 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.options.ClientCertificate;
import com.microsoft.playwright.options.FilePayload;
import com.microsoft.playwright.options.HttpHeader;
@@ -33,8 +35,10 @@ import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.microsoft.playwright.impl.Serialization.toJsonArray;
import static java.nio.file.Files.readAllBytes;
public class Utils {
static <F, T> T convertType(F f, Class<T> t) {
@@ -173,42 +177,107 @@ public class Utils {
return mimeType;
}
static void addFilePathUploadParams(Path[] files, JsonObject params, BrowserContextImpl context) {
if (files.length == 0) {
static void addFilePathUploadParams(Path[] items, JsonObject params, BrowserContextImpl context) {
List<Path> localPaths = new ArrayList<>();
Path localDirectory = resolvePathsAndDirectoryForInputFiles(items, localPaths);
if (items.length == 0) {
// FIXME: shouldBeAbleToResetSelectedFilesWithEmptyFileList tesst hangs in Chromium if we pass empty paths list.
params.add("payloads", new JsonArray());
} else if (context.connection.isRemote) {
List<WritableStream> streams = new ArrayList<>();
JsonArray jsonStreams = new JsonArray();
for (Path path : files) {
long lastModifiedMs;
try {
lastModifiedMs = Files.getLastModifiedTime(path).toMillis();
} catch (IOException e) {
throw new PlaywrightException("Cannot read file timestamp: " + path, e);
}
WritableStream temp = context.createTempFile(path.getFileName().toString(), lastModifiedMs);
streams.add(temp);
try (OutputStream out = temp.stream()) {
Files.copy(path, out);
} catch (IOException e) {
throw new PlaywrightException("Failed to copy file to remote server.", e);
}
jsonStreams.add(temp.toProtocolRef());
if (localDirectory != null) {
localPaths = collectFiles(localDirectory);
}
JsonObject json = createTempFiles(context, localDirectory, localPaths);
JsonArray writableStreams = json.getAsJsonArray("writableStreams");
JsonArray jsonStreams = copyLocalToTempFiles(context, localPaths, writableStreams);
if (json.has("rootDir")) {
params.add("directoryStream", json.get("rootDir"));
} else {
params.add("streams", jsonStreams);
}
params.add("streams", jsonStreams);
} else {
Path[] absolute = Arrays.stream(files).map(f -> {
try {
return f.toRealPath();
} catch (IOException e) {
throw new PlaywrightException("Cannot get absolute file path", e);
}
}).toArray(Path[]::new);
params.add("localPaths", toJsonArray(absolute));
if (!localPaths.isEmpty()) {
params.add("localPaths", toJsonArray(localPaths.toArray(new Path[0])));
}
if (localDirectory != null) {
params.addProperty("localDirectory", localDirectory.toString());
}
}
}
private static Path resolvePathsAndDirectoryForInputFiles(Path[] items, List<Path> outLocalPaths) {
Path localDirectory = null;
try {
for (Path item : items) {
if (Files.isDirectory(item)) {
if (localDirectory != null) {
throw new PlaywrightException("Multiple directories are not supported");
}
localDirectory = item.toRealPath();
} else {
outLocalPaths.add(item.toRealPath());
}
}
} catch (IOException e) {
throw new PlaywrightException("Cannot get absolute file path", e);
}
if (!outLocalPaths.isEmpty() && localDirectory != null) {
throw new PlaywrightException("File paths must be all files or a single directory");
}
return localDirectory;
}
private static List<Path> collectFiles(Path localDirectory) {
try {
return Files.walk(localDirectory).filter(e -> Files.isRegularFile(e)).collect(Collectors.toList());
} catch (IOException e) {
throw new PlaywrightException("Failed to traverse directory", e);
}
}
private static JsonArray copyLocalToTempFiles(BrowserContextImpl context, List<Path> localPaths, JsonArray writableStreams) {
JsonArray jsonStreams = new JsonArray();
for (int i = 0; i < localPaths.size(); i++) {
JsonObject jsonStream = writableStreams.get(i).getAsJsonObject();
WritableStream temp = context.connection.getExistingObject(jsonStream.get("guid").getAsString());
try (OutputStream out = temp.stream()) {
Files.copy(localPaths.get(i), out);
} catch (IOException e) {
throw new PlaywrightException("Failed to copy file to remote server.", e);
}
jsonStreams.add(temp.toProtocolRef());
}
return jsonStreams;
}
private static JsonObject createTempFiles(BrowserContextImpl context, Path localDirectory, List<Path> localPaths) {
JsonObject tempFilesParams = new JsonObject();
if (localDirectory != null) {
tempFilesParams.addProperty("rootDirName", localDirectory.getFileName().toString());
}
JsonArray items = new JsonArray();
for (Path path : localPaths) {
long lastModifiedMs;
try {
lastModifiedMs = Files.getLastModifiedTime(path).toMillis();
} catch (IOException e) {
throw new PlaywrightException("Cannot read file timestamp: " + path, e);
}
Path name;
if (localDirectory == null) {
name = path.getFileName();
} else {
name = localDirectory.relativize(path);
}
JsonObject item = new JsonObject();
item.addProperty("name", name.toString());
item.addProperty("lastModifiedMs", lastModifiedMs);
items.add(item);
}
tempFilesParams.add("items", items);
return context.sendMessage("createTempFiles", tempFilesParams).getAsJsonObject();
}
static void checkFilePayloadSize(FilePayload[] files) {
long totalSize = 0;
for (FilePayload file: files) {
@@ -345,4 +414,72 @@ public class Utils {
static String addSourceUrlToScript(String source, Path path) {
return source + "\n//# sourceURL=" + path.toString().replace("\n", "");
}
static void addToProtocol(JsonObject params, List<ClientCertificate> clientCertificateList) {
if (clientCertificateList == null) {
return;
}
JsonArray clientCertificates = new JsonArray();
for (ClientCertificate cert: clientCertificateList) {
JsonObject jsonCert = new JsonObject();
jsonCert.addProperty("origin", cert.origin);
try {
String certBase64 = base64Buffer(cert.cert, cert.certPath);
if (certBase64 != null) {
jsonCert.addProperty("cert", certBase64);
}
String keyBase64 = base64Buffer(cert.key, cert.keyPath);
if (keyBase64 != null) {
jsonCert.addProperty("key", keyBase64);
}
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);
}
if (cert.passphrase != null) {
jsonCert.addProperty("passphrase", cert.passphrase);
}
clientCertificates.add(jsonCert);
}
params.remove("clientCertificates");
params.add("clientCertificates", clientCertificates);
}
private static String base64Buffer(byte[] bytes, Path path) throws IOException {
if (path != null) {
bytes = readAllBytes(path);
}
if (bytes == null) {
return null;
}
return Base64.getEncoder().encodeToString(bytes);
}
static JsonObject interceptionPatterns(List<UrlMatcher> matchers) {
JsonArray jsonPatterns = new JsonArray();
for (UrlMatcher matcher: matchers) {
JsonObject jsonPattern = new JsonObject();
Object urlFilter = matcher.rawSource;
if (urlFilter instanceof String) {
jsonPattern.addProperty("glob", (String) urlFilter);
} else if (urlFilter instanceof Pattern) {
Pattern pattern = (Pattern) urlFilter;
jsonPattern.addProperty("regexSource", pattern.pattern());
jsonPattern.addProperty("regexFlags", toJsRegexFlags(pattern));
} else {
// Match all requests.
jsonPattern.addProperty("glob", "**/*");
jsonPatterns = new JsonArray();
jsonPatterns.add(jsonPattern);
break;
}
jsonPatterns.add(jsonPattern);
}
JsonObject result = new JsonObject();
result.add("patterns", jsonPatterns);
return result;
}
}
@@ -0,0 +1,29 @@
package com.microsoft.playwright.impl;
import com.microsoft.playwright.WebSocketFrame;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
class WebSocketFrameImpl implements WebSocketFrame {
private byte[] bytes;
private String text;
WebSocketFrameImpl(String payload, boolean isBase64) {
if (isBase64) {
bytes = Base64.getDecoder().decode(payload);
} else {
text = payload;
}
}
@Override
public byte[] binary() {
return bytes;
}
@Override
public String text() {
return text;
}
}
@@ -21,9 +21,7 @@ import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.WebSocket;
import com.microsoft.playwright.WebSocketFrame;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
@@ -151,28 +149,6 @@ class WebSocketImpl extends ChannelOwner implements WebSocket {
return runUntil(code, new WaitableRace<>(waitables));
}
private static class WebSocketFrameImpl implements WebSocketFrame {
private final byte[] bytes;
WebSocketFrameImpl(String payload, boolean isBase64) {
if (isBase64) {
bytes = Base64.getDecoder().decode(payload);
} else {
bytes = payload.getBytes();
}
}
@Override
public byte[] binary() {
return bytes;
}
@Override
public String text() {
return new String(bytes, StandardCharsets.UTF_8);
}
}
@Override
void handleEvent(String event, JsonObject parameters) {
switch (event) {
@@ -0,0 +1,186 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonObject;
import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.WebSocketFrame;
import com.microsoft.playwright.WebSocketRoute;
import java.util.Base64;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import static com.microsoft.playwright.impl.Serialization.gson;
class WebSocketRouteImpl extends ChannelOwner implements WebSocketRoute {
private Consumer<WebSocketFrame> onPageMessage;
private BiConsumer<Integer, String> onPageClose;
private Consumer<WebSocketFrame> onServerMessage;
private BiConsumer<Integer, String> onServerClose;
private boolean connected;
private WebSocketRoute server = new WebSocketRoute() {
@Override
public void close(CloseOptions options) {
if (options == null) {
options = new CloseOptions();
}
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
params.addProperty("wasClean", true);
sendMessageAsync("closeServer", params);
}
@Override
public WebSocketRoute connectToServer() {
throw new PlaywrightException("connectToServer must be called on the page-side WebSocketRoute");
}
@Override
public void onClose(BiConsumer<Integer, String> handler) {
onServerClose = handler;
}
@Override
public void onMessage(Consumer<WebSocketFrame> handler) {
onServerMessage = handler;
}
@Override
public void send(String message) {
JsonObject params = new JsonObject();
params.addProperty("message", message);
params.addProperty("isBase64", false);
sendMessageAsync("sendToServer", params);
}
@Override
public void send(byte[] message) {
JsonObject params = new JsonObject();
String base64 = Base64.getEncoder().encodeToString(message);
params.addProperty("message", base64);
params.addProperty("isBase64", true);
sendMessageAsync("sendToServer", params);
}
@Override
public String url() {
return initializer.get("url").getAsString();
}
};
WebSocketRouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
}
@Override
public void close(CloseOptions options) {
if (options == null) {
options = new CloseOptions();
}
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
params.addProperty("wasClean", true);
sendMessageAsync("closePage", params);
}
@Override
public WebSocketRoute connectToServer() {
if (connected) {
throw new PlaywrightException("Already connected to the server");
}
connected = true;
sendMessageAsync("connect");
return server;
}
@Override
public void onClose(BiConsumer<Integer, String> handler) {
onPageClose = handler;
}
@Override
public void onMessage(Consumer<WebSocketFrame> handler) {
onPageMessage = handler;
}
@Override
public void send(String message) {
JsonObject params = new JsonObject();
params.addProperty("message", message);
params.addProperty("isBase64", false);
sendMessageAsync("sendToPage", params);
}
@Override
public void send(byte[] message) {
JsonObject params = new JsonObject();
String base64 = Base64.getEncoder().encodeToString(message);
params.addProperty("message", base64);
params.addProperty("isBase64", true);
sendMessageAsync("sendToPage", params);
}
@Override
public String url() {
return initializer.get("url").getAsString();
}
void afterHandle() {
if (this.connected) {
return;
}
// Ensure that websocket is "open" and can send messages without an actual server connection.
sendMessageAsync("ensureOpened");
}
@Override
protected void handleEvent(String event, JsonObject params) {
if ("messageFromPage".equals(event)) {
String message = params.get("message").getAsString();
boolean isBase64 = params.get("isBase64").getAsBoolean();
if (onPageMessage != null) {
onPageMessage.accept(new WebSocketFrameImpl(message, isBase64));
} else if (connected) {
JsonObject messageParams = new JsonObject();
messageParams.addProperty("message", message);
messageParams.addProperty("isBase64", isBase64);
sendMessageAsync("sendToServer", messageParams);
}
} else if ("messageFromServer".equals(event)) {
String message = params.get("message").getAsString();
boolean isBase64 = params.get("isBase64").getAsBoolean();
if (onServerMessage != null) {
onServerMessage.accept(new WebSocketFrameImpl(message, isBase64));
} else {
JsonObject messageParams = new JsonObject();
messageParams.addProperty("message", message);
messageParams.addProperty("isBase64", isBase64);
sendMessageAsync("sendToPage", messageParams);
}
} else if ("closePage".equals(event)) {
int code = params.get("code").getAsInt();
String reason = params.get("reason").getAsString();
boolean wasClean = params.get("wasClean").getAsBoolean();
if (onPageClose != null) {
onPageClose.accept(code, reason);
} else {
JsonObject closeParams = new JsonObject();
closeParams.addProperty("code", code);
closeParams.addProperty("reason", reason);
closeParams.addProperty("wasClean", wasClean);
sendMessageAsync("closeServer", closeParams);
}
} else if ("closeServer".equals(event)) {
int code = params.get("code").getAsInt();
String reason = params.get("reason").getAsString();
boolean wasClean = params.get("wasClean").getAsBoolean();
if (onServerClose != null) {
onServerClose.accept(code, reason);
} else {
JsonObject closeParams = new JsonObject();
closeParams.addProperty("code", code);
closeParams.addProperty("reason", reason);
closeParams.addProperty("wasClean", wasClean);
sendMessageAsync("closePage", closeParams);
}
}
}
}
@@ -0,0 +1,47 @@
package com.microsoft.playwright.impl;
import com.google.gson.JsonObject;
import com.microsoft.playwright.WebSocketRoute;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class WebSocketRouter {
private List<RouteInfo> routes = new ArrayList<>();
private static class RouteInfo {
final UrlMatcher matcher;
private final Consumer<WebSocketRoute> handler;
RouteInfo(UrlMatcher matcher, Consumer<WebSocketRoute> handler) {
this.matcher = matcher;
this.handler = handler;
}
void handle(WebSocketRouteImpl route) {
handler.accept(route);
route.afterHandle();
}
}
void add(UrlMatcher matcher, Consumer<WebSocketRoute> handler) {
routes.add(0, new RouteInfo(matcher, handler));
}
boolean handle(WebSocketRouteImpl route) {
for (RouteInfo routeInfo: routes) {
if (routeInfo.matcher.test(route.url())) {
routeInfo.handle(route);
return true;
}
}
return false;
}
JsonObject interceptionPatterns() {
List<UrlMatcher> matchers = routes.stream().map(r -> r.matcher).collect(Collectors.toList());
return Utils.interceptionPatterns(matchers);
}
}
@@ -16,28 +16,22 @@
package com.microsoft.playwright.impl.junit;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.PlaywrightException;
import com.microsoft.playwright.*;
import com.microsoft.playwright.impl.Utils;
import com.microsoft.playwright.junit.Options;
import org.junit.jupiter.api.extension.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.microsoft.playwright.impl.junit.ExtensionUtils.*;
import static com.microsoft.playwright.impl.junit.PageExtension.cleanUpPage;
public class BrowserContextExtension implements ParameterResolver, AfterEachCallback {
public class BrowserContextExtension implements ParameterResolver, TestWatcher {
private static final ThreadLocal<BrowserContext> threadLocalBrowserContext = new ThreadLocal<>();
@Override
public void afterEach(ExtensionContext extensionContext) {
BrowserContext browserContext = threadLocalBrowserContext.get();
threadLocalBrowserContext.remove();
if (browserContext != null) {
browserContext.close();
}
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return !isClassHook(extensionContext) && isParameterSupported(parameterContext, extensionContext, BrowserContext.class);
@@ -51,6 +45,7 @@ public class BrowserContextExtension implements ParameterResolver, AfterEachCall
/**
* Returns the BrowserContext that belongs to the current test. Will be created if it doesn't already exist.
* <strong>NOTE:</strong> this method is subject to change.
*
* @param extensionContext the context in which the current test or container is being executed.
* @return The BrowserContext that belongs to the current test.
*/
@@ -66,10 +61,97 @@ public class BrowserContextExtension implements ParameterResolver, AfterEachCall
Browser browser = BrowserExtension.getOrCreateBrowser(extensionContext);
Browser.NewContextOptions contextOptions = getContextOptions(playwright, options);
browserContext = browser.newContext(contextOptions);
if (shouldRecordTrace(options)) {
Tracing.StartOptions startOptions = new Tracing.StartOptions().setSnapshots(true).setScreenshots(true).setTitle(extensionContext.getDisplayName());
if (System.getenv("PLAYWRIGHT_JAVA_SRC") != null) {
startOptions.setSources(true);
}
browserContext.tracing().start(startOptions);
}
threadLocalBrowserContext.set(browserContext);
return browserContext;
}
@Override
public void testSuccessful(ExtensionContext extensionContext) {
saveTraceWhenOn(extensionContext);
closeBrowserContext();
}
@Override
public void testAborted(ExtensionContext extensionContext, Throwable cause) {
saveTraceWhenOn(extensionContext);
closeBrowserContext();
}
@Override
public void testFailed(ExtensionContext extensionContext, Throwable cause) {
Options options = OptionsExtension.getOptions(extensionContext);
if (shouldRecordTrace(options)) {
saveTrace(extensionContext);
}
closeBrowserContext();
}
private static void saveTraceWhenOn(ExtensionContext extensionContext) {
Options options = OptionsExtension.getOptions(extensionContext);
if (options.trace.equals(Options.Trace.ON)) {
saveTrace(extensionContext);
}
}
private static void saveTrace(ExtensionContext extensionContext) {
BrowserContext browserContext = threadLocalBrowserContext.get();
if (browserContext == null) {
return;
}
Path outputPath = getOutputPath(extensionContext);
createOutputPath(outputPath);
Tracing.StopOptions stopOptions = new Tracing.StopOptions().setPath(outputPath.resolve("trace.zip"));
browserContext.tracing().stop(stopOptions);
}
private static void createOutputPath(Path outputPath) {
if (!Files.exists(outputPath)) {
try {
Files.createDirectories(outputPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private static Path getOutputPath(ExtensionContext extensionContext) {
BrowserType browserType = BrowserExtension.getBrowser().browserType();
Path defaultOutputPath = getDefaultOutputPath(extensionContext);
String outputDirName = extensionContext.getRequiredTestClass().getName() + "." +
extensionContext.getRequiredTestMethod().getName() + "-" +
browserType.name();
return defaultOutputPath.resolve(outputDirName);
}
private static Path getDefaultOutputPath(ExtensionContext extensionContext) {
Options options = OptionsExtension.getOptions(extensionContext);
Path outputPath = options.outputDir;
if (outputPath == null) {
outputPath = Paths.get(System.getProperty("user.dir")).resolve("test-results");
}
return outputPath;
}
private void closeBrowserContext() {
cleanUpPage();
BrowserContext browserContext = threadLocalBrowserContext.get();
threadLocalBrowserContext.remove();
if (browserContext != null) {
browserContext.close();
}
}
private static boolean shouldRecordTrace(Options options) {
return options.trace.equals(Options.Trace.ON) || options.trace.equals(Options.Trace.RETAIN_ON_FAILURE);
}
private static Browser.NewContextOptions getContextOptions(Playwright playwright, Options options) {
Browser.NewContextOptions contextOptions = Utils.clone(options.contextOptions);
if (contextOptions == null) {
@@ -94,7 +176,7 @@ public class BrowserContextExtension implements ParameterResolver, AfterEachCall
contextOptions.hasTouch = deviceDescriptor.hasTouch;
}
if(options.ignoreHTTPSErrors != null) {
if (options.ignoreHTTPSErrors != null) {
contextOptions.setIgnoreHTTPSErrors(options.ignoreHTTPSErrors);
}
@@ -86,6 +86,10 @@ public class BrowserExtension implements ParameterResolver, AfterAllCallback {
return browser;
}
static Browser getBrowser() {
return threadLocalBrowser.get();
}
private static BrowserType.ConnectOptions getConnectOptions(Options options) {
BrowserType.ConnectOptions connectOptions = options.connectOptions;
if(connectOptions == null) {
@@ -22,17 +22,8 @@ import org.junit.jupiter.api.extension.*;
import static com.microsoft.playwright.impl.junit.ExtensionUtils.*;
public class PageExtension implements ParameterResolver, AfterEachCallback {
private static final ThreadLocal<Page> threadLocalPage = new ThreadLocal<>();
@Override
public void afterEach(ExtensionContext extensionContext) {
Page page = threadLocalPage.get();
threadLocalPage.remove();
if (page != null) {
page.close();
}
}
public class PageExtension implements ParameterResolver {
private static final ThreadLocal<Page> threadLocalPage = new ThreadLocal<>();
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
@@ -47,6 +38,7 @@ public class PageExtension implements ParameterResolver, AfterEachCallback {
/**
* Returns the Page that belongs to the current test. Will be created if it doesn't already exist.
* <strong>NOTE:</strong> this method is subject to change.
*
* @param extensionContext the context in which the current test or container is being executed.
* @return The Page that belongs to the current test.
*/
@@ -61,4 +53,8 @@ public class PageExtension implements ParameterResolver, AfterEachCallback {
threadLocalPage.set(page);
return page;
}
static void cleanUpPage() {
threadLocalPage.remove();
}
}
@@ -16,10 +16,9 @@
package com.microsoft.playwright.junit;
import com.microsoft.playwright.APIRequest;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.*;
import java.nio.file.Path;
/**
* <strong>NOTE:</strong> this API is experimental and is subject to changes.
@@ -47,6 +46,26 @@ public class Options {
// If this is set, BrowserType.connect will be used. Otherwise, BrowserType.launch will be used.
public String wsEndpoint;
public BrowserType.ConnectOptions connectOptions;
// The dir where test artifacts will be stored
public Path outputDir;
// When to record traces. Default is OFF.
public Trace trace = Trace.OFF;
public enum Trace {
OFF,
ON,
RETAIN_ON_FAILURE;
}
public Options setTrace(Trace trace) {
this.trace = trace;
return this;
}
public Options setOutputDir(Path outputDir) {
this.outputDir = outputDir;
return this;
}
public Options setWsEndpoint(String wsEndpoint) {
this.wsEndpoint = wsEndpoint;
@@ -0,0 +1,108 @@
/*
* 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;
import java.nio.file.Path;
public class ClientCertificate {
/**
* Exact origin that the certificate is valid for. Origin includes {@code https} protocol, a hostname and optionally a
* port.
*/
public String origin;
/**
* 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).
*/
public String passphrase;
public ClientCertificate(String origin) {
this.origin = origin;
}
/**
* Path to the file with the certificate in PEM format.
*/
public ClientCertificate setCertPath(Path certPath) {
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.
*/
public ClientCertificate setKeyPath(Path keyPath) {
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.
*/
public ClientCertificate setPfxPath(Path pfxPath) {
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).
*/
public ClientCertificate setPassphrase(String passphrase) {
this.passphrase = passphrase;
return this;
}
}
@@ -20,15 +20,16 @@ public class Cookie {
public String name;
public String value;
/**
* either url or domain / path are required. Optional.
* Either url or domain / path are required. Optional.
*/
public String url;
/**
* either url or domain / path are required Optional.
* For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either url or
* domain / path are required. Optional.
*/
public String domain;
/**
* either url or domain / path are required Optional.
* Either url or domain / path are required Optional.
*/
public String path;
/**
@@ -53,21 +54,22 @@ public class Cookie {
this.value = value;
}
/**
* either url or domain / path are required. Optional.
* Either url or domain / path are required. Optional.
*/
public Cookie setUrl(String url) {
this.url = url;
return this;
}
/**
* either url or domain / path are required Optional.
* For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either url or
* domain / path are required. Optional.
*/
public Cookie setDomain(String domain) {
this.domain = domain;
return this;
}
/**
* either url or domain / path are required Optional.
* Either url or domain / path are required Optional.
*/
public Cookie setPath(String path) {
this.path = path;
@@ -23,6 +23,13 @@ public class HttpCredentials {
* Restrain sending http credentials on specific origin (scheme://host:port).
*/
public String origin;
/**
* This option only applies to the requests sent from corresponding {@code APIRequestContext} and does not affect requests
* sent from the browser. {@code "always"} - {@code Authorization} header with basic authentication credentials will be
* sent with the each API request. {@code 'unauthorized} - the credentials are only sent when 401 (Unauthorized) response
* with {@code WWW-Authenticate} header is received. Defaults to {@code "unauthorized"}.
*/
public HttpCredentialsSend send;
public HttpCredentials(String username, String password) {
this.username = username;
@@ -35,4 +42,14 @@ public class HttpCredentials {
this.origin = origin;
return this;
}
/**
* This option only applies to the requests sent from corresponding {@code APIRequestContext} and does not affect requests
* sent from the browser. {@code "always"} - {@code Authorization} header with basic authentication credentials will be
* sent with the each API request. {@code 'unauthorized} - the credentials are only sent when 401 (Unauthorized) response
* with {@code WWW-Authenticate} header is received. Defaults to {@code "unauthorized"}.
*/
public HttpCredentials setSend(HttpCredentialsSend send) {
this.send = send;
return this;
}
}
@@ -0,0 +1,22 @@
/*
* 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 enum HttpCredentialsSend {
UNAUTHORIZED,
ALWAYS
}
@@ -133,6 +133,15 @@ public interface RequestOptions {
* @since v1.26
*/
RequestOptions setMaxRedirects(int maxRedirects);
/**
*
*
* @param maxRetries Maximum number of times network errors should be retried. Currently only {@code ECONNRESET} error is retried. Does not
* retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to {@code 0} - no
* retries.
* @since v1.46
*/
RequestOptions setMaxRetries(int maxRetries);
/**
* Changes the request method (e.g. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT">PUT</a> or <a
* href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST</a>).
@@ -19,11 +19,15 @@ package com.microsoft.playwright;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsParameters;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
class HttpsConfiguratorImpl extends HttpsConfigurator {
@@ -31,7 +35,7 @@ class HttpsConfiguratorImpl extends HttpsConfigurator {
return new HttpsConfiguratorImpl(createSSLContext());
}
private HttpsConfiguratorImpl(SSLContext context) {
HttpsConfiguratorImpl(SSLContext context) {
super(context);
}
@@ -39,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);
}
@@ -20,7 +20,6 @@ import com.sun.net.httpserver.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.file.FileSystems;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
@@ -73,11 +72,8 @@ public class Server implements HttpHandler {
} else {
server = HttpServer.create(new InetSocketAddress("localhost", port), 0);
}
server.createContext("/", this);
server.setExecutor(null); // creates a default executor
File cwd = FileSystems.getDefault().getPath(".").toFile();
server.start();
}
@@ -0,0 +1,160 @@
/*
* Copyright (c) Microsoft Corporation.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 com.sun.net.httpserver.*;
import javax.net.ssl.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.*;
import java.util.*;
public class ServerWithClientCertificate implements HttpHandler {
private final HttpServer server;
final String origin;
final String crossOrigin;
final String url;
KeyStore keyStore;
static ServerWithClientCertificate create(int port) throws IOException {
return new ServerWithClientCertificate(port);
}
private ServerWithClientCertificate(int port) throws IOException {
origin = "https://localhost:" + port;
crossOrigin = "https://127.0.0.1:" + port;;
url = origin + "/index.html";
HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress("localhost", port), 0);
httpsServer.setHttpsConfigurator(new HttpsConfiguratorImpl(loadCertificates()));
server = httpsServer;
server.createContext("/", this);
server.setExecutor(null); // creates a default executor
server.start();
}
public void stop() {
server.stop(0);
}
private SSLContext loadCertificates() {
try {
// Create an SSL context
SSLContext sslContext = SSLContext.getInstance("TLS");
// Load the keystore from file
char[] password = "".toCharArray(); // the password you set during the PKCS12 export
keyStore = KeyStore.getInstance("PKCS12");
InputStream fis = HttpsConfiguratorImpl.class.getClassLoader().getResourceAsStream(
"resources/client-certificates/server/server_keystore.p12");
keyStore.load(fis, password);
// Set up the KeyManagerFactory to use the keystore
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, password);
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
List<X509Certificate> certs = new ArrayList<>();
try {
for (String alias : Collections.list(keyStore.aliases())) {
certs.add((X509Certificate) keyStore.getCertificate(alias));
}
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
return certs.toArray(new X509Certificate[0]);
}
public void checkClientTrusted(X509Certificate[] clientCerts, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Initialize the SSL context
sslContext.init(kmf.getKeyManagers(), trustAllCerts, null);
return sslContext;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean validateCertChain(Certificate[] clientCerts) {
try {
// Create CertPath from the provided client certificates
CertificateFactory factory = CertificateFactory.getInstance("X.509");
CertPath certPath = factory.generateCertPath(Arrays.asList(clientCerts));
// Extract Trust Anchors from the trust store
Set<TrustAnchor> trustAnchors = new HashSet<>();
for (String alias : Collections.list(keyStore.aliases())) {
X509Certificate trustedCert = (X509Certificate) keyStore.getCertificate(alias);
if (trustedCert != null) {
trustAnchors.add(new TrustAnchor(trustedCert, null));
}
}
// Initialize PKIX parameters
PKIXParameters params = new PKIXParameters(trustAnchors);
params.setRevocationEnabled(false); // Set to true if you want to enable CRL checking
// Validate the certification path
CertPathValidator certPathValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType());
certPathValidator.validate(certPath, params);
return true;
} catch (Exception e) {
return false;
}
}
private static String div(String testId, String message) {
return "<div data-testid='" + testId + "'>" + message + "</div>";
}
@Override
public void handle(HttpExchange exchange) throws IOException {
SSLSession sslSession = ((HttpsExchange) exchange).getSSLSession();
String response = div("servername", sslSession.getPeerHost());
try {
Certificate[] certs = sslSession.getPeerCertificates();
X509Certificate cert = (X509Certificate) certs[0];
exchange.getResponseHeaders().add("Content-Type", "text/html");
if (validateCertChain(certs)) {
exchange.sendResponseHeaders(200, 0);
response += div("message", String.format("Hello %s, your certificate was issued by %s!",
cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName()));
} else {
response += div("message", String.format("Sorry %s, certificates from %s are not welcome here.",
cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName()));
exchange.sendResponseHeaders(403, 0);
}
} catch (SSLPeerUnverifiedException e) {
response += div("message", "Sorry, but you need to provide a client certificate to continue.");
exchange.sendResponseHeaders(401, 0);
}
try (OutputStreamWriter writer = new OutputStreamWriter(exchange.getResponseBody())) {
writer.write(response);
}
}
}
@@ -22,6 +22,7 @@ import com.microsoft.playwright.options.SameSiteAttribute;
import javax.sql.rowset.Predicate;
import java.io.IOException;
import java.io.InputStream;
import java.security.Provider;
import java.time.Duration;
import java.time.Instant;
@@ -42,9 +43,11 @@ public class TestBase {
Browser browser;
static final boolean isMac = Utils.getOS() == Utils.OS.MAC;
static final boolean isLinux = Utils.getOS() == Utils.OS.LINUX;
static final boolean isWindows = Utils.getOS() == Utils.OS.WINDOWS;
static final boolean headful;
static final SameSiteAttribute defaultSameSiteCookieValue;
static {
String headfulEnv = System.getenv("HEADFUL");
headful = headfulEnv != null && !"0".equals(headfulEnv) && !"false".equals(headfulEnv);
@@ -160,14 +163,28 @@ public class TestBase {
void waitForCondition(BooleanSupplier predicate) {
waitForCondition(predicate, 5_000);
}
void waitForCondition(BooleanSupplier predicate, int timeoutMs) {
page.waitForCondition(predicate, new Page.WaitForConditionOptions().setTimeout(timeoutMs));
}
private static SameSiteAttribute initSameSiteAttribute() {
if (isChromium()) return SameSiteAttribute.LAX;
if (isWebKit()) return SameSiteAttribute.NONE;
if (isWebKit() && isLinux) return SameSiteAttribute.LAX;
if (isWebKit() && !isLinux) return SameSiteAttribute.NONE;
// for firefox version >= 103 'None' is used.
return SameSiteAttribute.NONE;
}
static boolean chromiumVersionLessThan(String a, String b) {
String[] aParts = a.split("\\.");
String[] bParts = b.split("\\.");
for (int i = 0; i < 4; i++) {
int aPart = Integer.parseInt(aParts[i]);
int bPart = Integer.parseInt(bParts[i]);
if (aPart > bPart) return false;
if (aPart < bPart) return true;
}
return false;
}
}
@@ -26,7 +26,7 @@ import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static com.microsoft.playwright.TestOptionsFactories.isChromium;
import static com.microsoft.playwright.TestBase.defaultSameSiteCookieValue;
import static com.microsoft.playwright.TestOptionsFactories.isFirefox;
import static com.microsoft.playwright.Utils.assertJsonEquals;
import static java.util.Arrays.asList;
@@ -227,7 +227,7 @@ public class TestBrowserContextAddCookies {
" expires: -1,\n" +
" httpOnly: false,\n" +
" secure: false,\n" +
" sameSite: '" + (isChromium() ? "LAX" : "NONE") +"'\n" +
" sameSite: '" + defaultSameSiteCookieValue +"'\n" +
"}]", cookies);
}
@@ -246,7 +246,7 @@ public class TestBrowserContextAddCookies {
" expires: -1,\n" +
" httpOnly: false,\n" +
" secure: false,\n" +
" sameSite: '" + (isChromium() ? "LAX" : "NONE") +"'\n" +
" sameSite: '" + defaultSameSiteCookieValue +"'\n" +
"}]", cookies);
assertEquals("gridcookie=GRID", page.evaluate("document.cookie"));
page.navigate(server.EMPTY_PAGE);
@@ -311,7 +311,7 @@ public class TestBrowserContextAddCookies {
" expires: -1,\n" +
" httpOnly: false,\n" +
" secure: true,\n" +
" sameSite: '" + (isChromium() ? "LAX" : "NONE") +"'\n" +
" sameSite: '" + defaultSameSiteCookieValue +"'\n" +
"}]", context.cookies("https://www.example.com"));
}
@@ -48,7 +48,7 @@ public class TestBrowserContextCookies extends TestBase {
" expires: -1,\n" +
" httpOnly: false,\n" +
" secure: false,\n" +
" sameSite: '" + (isChromium() ? "LAX" : "NONE") +"'\n" +
" sameSite: '" + defaultSameSiteCookieValue +"'\n" +
" }]", cookies);
}
@@ -72,6 +72,7 @@ public class TestBrowserContextCookies extends TestBase {
assertFalse(cookies.get(0).httpOnly);
assertFalse(cookies.get(0).secure);
assertEquals(defaultSameSiteCookieValue, cookies.get(0).sameSite);
assertEquals(defaultSameSiteCookieValue, cookies.get(0).sameSite);
// Browsers start to cap cookies with 400 days max expires value.
// See https://github.com/httpwg/http-extensions/pull/1732
@@ -147,7 +148,7 @@ public class TestBrowserContextCookies extends TestBase {
" expires: -1,\n" +
" httpOnly: false,\n" +
" secure: false,\n" +
" sameSite: '" + (isChromium() ? "LAX" : "NONE") +"'\n" +
" sameSite: '" + defaultSameSiteCookieValue +"'\n" +
" },\n" +
" {\n" +
" name: 'username',\n" +
@@ -157,7 +158,7 @@ public class TestBrowserContextCookies extends TestBase {
" expires: -1,\n" +
" httpOnly: false,\n" +
" secure: false,\n" +
" sameSite: '" + (isChromium() ? "LAX" : "NONE") +"'\n" +
" sameSite: '" + defaultSameSiteCookieValue +"'\n" +
" }\n" +
"]", cookies);
}
@@ -178,7 +179,7 @@ public class TestBrowserContextCookies extends TestBase {
" expires: -1.0,\n" +
" httpOnly: false,\n" +
" secure: true,\n" +
" sameSite: '" + (isChromium() ? "LAX" : "NONE") +"'\n" +
" sameSite: '" + defaultSameSiteCookieValue +"'\n" +
"}, {\n" +
" name: 'doggo',\n" +
" value: 'woofs',\n" +
@@ -187,7 +188,7 @@ public class TestBrowserContextCookies extends TestBase {
" expires: -1.0,\n" +
" httpOnly: false,\n" +
" secure: true,\n" +
" sameSite: '" + (isChromium() ? "LAX" : "NONE") +"'\n" +
" sameSite: '" + defaultSameSiteCookieValue +"'\n" +
"}]", cookies);
}
@@ -205,14 +206,14 @@ public class TestBrowserContextCookies extends TestBase {
page.navigate(server.EMPTY_PAGE);
Object documentCookie = page.evaluate("document.cookie.split('; ').sort().join('; ')");
if (isChromium()) {
if (isChromium() || (isLinux && isWebKit())) {
assertEquals("one=uno; two=dos", documentCookie);
} else {
assertEquals("one=uno; three=tres; two=dos", documentCookie);
}
List<SameSiteAttribute> list = context.cookies().stream().map(c -> c.sameSite).sorted().collect(Collectors.toList());
if (isChromium()) {
if (isChromium() || (isLinux && isWebKit())) {
assertEquals(asList(SameSiteAttribute.STRICT, SameSiteAttribute.LAX), list);
} else {
assertEquals(asList(SameSiteAttribute.STRICT, SameSiteAttribute.LAX, SameSiteAttribute.NONE), list);
@@ -23,10 +23,12 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ExecutionException;
@@ -130,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);
}
;
@@ -216,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");
@@ -516,10 +518,20 @@ public class TestBrowserContextFetch extends TestBase {
testData.date = new Date(currentMillis);
testData.localDateTime = testData.date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
context.request().fetch(pageReq, RequestOptions.create().setMethod("POST").setData(testData));
assertEquals("{\"name\":\"foo\",\"localDateTime\":\"2022-12-23T06:14:58.818Z\",\"date\":\"2022-12-23T06:14:58.818Z\"}",
assertEquals("{\"name\":\"foo\",\"localDateTime\":\"2022-12-23T06:14:58.818Z\",\"date\":\"2022-12-23T06:14:58.818Z\",\"nullLocalDateTime\":null,\"nullDate\":null}",
new String(req.get().postBody));
}
@Test
void shouldSupportOffsetDateTimeInData() throws ExecutionException, InterruptedException {
APIRequestContext request = playwright.request().newContext();
OffsetDateTime offsetDateTime = OffsetDateTime.parse("2024-07-10T10:15:30-08:00");
Future<Server.Request> serverRequest = server.futureRequest("/empty.html");
request.get(server.EMPTY_PAGE, RequestOptions.create().setData(mapOf("date", offsetDateTime)));
byte[] body = serverRequest.get().postBody;
assertEquals("{\"date\":\"2024-07-10T18:15:30.000Z\"}", new String(body));
}
@Test
void shouldSupportApplicationXWwwFormUrlencoded() throws ExecutionException, InterruptedException {
Future<Server.Request> req = server.futureRequest("/empty.html");
@@ -796,4 +808,85 @@ public class TestBrowserContextFetch extends TestBase {
assertEquals(401, response.status());
}
}
@Test
void shouldSerializeNullValuesInPostData() throws ExecutionException, InterruptedException {
Future<Server.Request> req = server.futureRequest("/empty.html");
APIResponse response = context.request().post(server.EMPTY_PAGE, RequestOptions.create().setData(mapOf("foo", null)));
assertEquals(200, response.status());
assertEquals("{\"foo\":null}", new String(req.get().postBody));
}
@Test
void shouldSupportHTTPCredentialsSendImmediatelyForNewContext() throws ExecutionException, InterruptedException {
Browser.NewContextOptions options = new Browser.NewContextOptions().setHttpCredentials(
new HttpCredentials("user", "pass")
.setOrigin(server.PREFIX.toUpperCase())
.setSend(HttpCredentialsSend.ALWAYS));
try (BrowserContext context = browser.newContext(options)) {
Future<Server.Request> serverRequest = server.futureRequest("/empty.html");
APIResponse response = context.request().get(server.EMPTY_PAGE);
assertEquals("Basic " + java.util.Base64.getEncoder().encodeToString("user:pass".getBytes()),
serverRequest.get().headers.getFirst("authorization"));
assertEquals(200, response.status());
serverRequest = server.futureRequest("/empty.html");
response = context.request().get(server.CROSS_PROCESS_PREFIX + "/empty.html");
// Not sent to another origin.
assertNull(serverRequest.get().headers.get("authorization"));
assertEquals(200, response.status());
}
}
@Test
void shouldSupportHTTPCredentialsSendImmediatelyForBrowserNewPage() throws ExecutionException, InterruptedException {
Browser.NewPageOptions options = new Browser.NewPageOptions().setHttpCredentials(
new HttpCredentials("user", "pass")
.setOrigin(server.PREFIX.toUpperCase())
.setSend(HttpCredentialsSend.ALWAYS));
try (Page newPage = browser.newPage(options)) {
Future<Server.Request> serverRequest = server.futureRequest("/empty.html");
APIResponse response = newPage.request().get(server.EMPTY_PAGE);
assertEquals("Basic " + java.util.Base64.getEncoder().encodeToString("user:pass".getBytes()),
serverRequest.get().headers.getFirst("authorization"));
assertEquals(200, response.status());
serverRequest = server.futureRequest("/empty.html");
response = newPage.request().get(server.CROSS_PROCESS_PREFIX + "/empty.html");
// Not sent to another origin.
assertNull(serverRequest.get().headers.get("authorization"));
assertEquals(200, response.status());
}
}
@Test
void shouldNotWorkAfterContextDispose() {
context.close(new BrowserContext.CloseOptions().setReason("Test ended."));
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.request().get(server.EMPTY_PAGE));
assertTrue(e.getMessage().contains("Test ended."), e.getMessage());
}
@Test
public void shouldRetryECONNRESET() {
int[] requestCount = {0};
server.setRoute("/test", exchange -> {
if (requestCount[0]++ < 3) {
exchange.close();
return;
}
exchange.getResponseHeaders().add("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, 0);
try (OutputStreamWriter writer = new OutputStreamWriter(exchange.getResponseBody())) {
writer.write("Hello!");
}
});
APIRequestContext requestContext = context.request();
APIResponse response = requestContext.get(server.PREFIX + "/test",
RequestOptions.create().setMaxRetries(3));
assertEquals(200, response.status());
assertEquals("Hello!", response.text());
assertEquals(4, requestCount[0]);
}
}
@@ -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
}
@@ -98,6 +98,20 @@ public class TestBrowserContextStorageState extends TestBase {
"}");
Path path = tempDir.resolve("storage-state.json");
context.storageState(new BrowserContext.StorageStateOptions().setPath(path));
String sameSiteCamelCase = "Lax";
switch (defaultSameSiteCookieValue) {
case STRICT:
sameSiteCamelCase = "Strict";
break;
case LAX:
sameSiteCamelCase = "Lax";
break;
case NONE:
sameSiteCamelCase = "None";
break;
}
JsonObject expected = new Gson().fromJson(
"{\n" +
" 'cookies':[\n" +
@@ -109,7 +123,7 @@ public class TestBrowserContextStorageState extends TestBase {
" 'expires':-1,\n" +
" 'httpOnly':false,\n" +
" 'secure':false,\n" +
" 'sameSite':'" + (isChromium() ? "Lax" : "None") + "'\n" +
" 'sameSite':'" + sameSiteCamelCase + "'\n" +
" }],\n" +
" 'origins':[\n" +
" {\n" +
@@ -506,7 +506,7 @@ public class TestBrowserTypeConnect extends TestBase {
}
@Test
void setInputFilesDhouldPreserveLastModifiedTimestamp() throws IOException {
void setInputFilesShouldPreserveLastModifiedTimestamp() throws IOException {
page.setContent("<input type=file multiple=true/>");
Locator input = page.locator("input");
input.setInputFiles(FILE_TO_UPLOAD);
@@ -0,0 +1,232 @@
package com.microsoft.playwright;
import com.microsoft.playwright.options.ClientCertificate;
import com.microsoft.playwright.options.Proxy;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
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.*;
public class TestClientCertificates extends TestBase {
private ServerWithClientCertificate customServer;
private static Path asset(String path) {
return Paths.get("src/test/resources/" + path).toAbsolutePath();
}
private static String origin(String urlString) {
try {
URL url = new URL(urlString);
String origin = url.getProtocol() + "://" + url.getHost();
if (url.getPort() != -1 && url.getPort() != url.getDefaultPort()) {
origin += ":" + url.getPort();
}
return origin;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@BeforeAll
@Override
void startServer() throws IOException {
super.startServer();
customServer = ServerWithClientCertificate.create(nextFreePort());
}
@AfterAll
@Override
void stopServer() {
if (customServer != null) {
customServer.stop();
customServer = null;
}
super.stopServer();
}
@Test
public void shouldFailWithNoClientCertificatesProvided() {
APIRequestContext request = playwright.request().newContext(
new APIRequest.NewContextOptions().setIgnoreHTTPSErrors(true));
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();
}
@Test
public void shouldKeepSupportingHttp() {
APIRequest.NewContextOptions requestOptions = new APIRequest.NewContextOptions()
.setIgnoreHTTPSErrors(true) // TODO: remove once we can pass a custom CA.
.setClientCertificates(asList(
new ClientCertificate(origin(server.PREFIX))
.setCertPath(asset("client-certificates/client/trusted/cert.pem"))
.setKeyPath(asset("client-certificates/client/trusted/key.pem"))));
APIRequestContext request = playwright.request().newContext(requestOptions);
APIResponse response = request.get(server.PREFIX + "/one-style.html");
assertEquals(server.PREFIX + "/one-style.html", response.url());
assertEquals(200, response.status());
assertTrue(response.text().contains("<div>hello, world!</div>"));
request.dispose();
}
@Test
public void shouldThrowWithUntrustedClientCerts() {
APIRequest.NewContextOptions requestOptions = new APIRequest.NewContextOptions()
.setIgnoreHTTPSErrors(true) // TODO: remove once we can pass a custom CA.
.setClientCertificates(asList(
new ClientCertificate(customServer.origin)
.setCertPath(asset("client-certificates/client/self-signed/cert.pem"))
.setKeyPath(asset("client-certificates/client/self-signed/key.pem"))));
APIRequestContext request = playwright.request().newContext(requestOptions);
APIResponse response = request.get(customServer.url);
assertEquals(customServer.url, response.url());
assertEquals(403, response.status());
assertTrue(response.text().contains("Sorry CN=Bob, certificates from CN=Bob are not welcome here."), response.text());
request.dispose();
}
@Test
public void passWithTrustedClientCertificates() {
APIRequest.NewContextOptions requestOptions = new APIRequest.NewContextOptions()
.setIgnoreHTTPSErrors(true) // TODO: remove once we can pass a custom CA.
.setClientCertificates(asList(
new ClientCertificate(customServer.origin)
.setCertPath(asset("client-certificates/client/trusted/cert.pem"))
.setKeyPath(asset("client-certificates/client/trusted/key.pem"))));
APIRequestContext request = playwright.request().newContext(requestOptions);
APIResponse response = request.get(customServer.url);
assertEquals(customServer.url, response.url());
assertEquals(200, response.status());
assertTrue(response.text().contains("Hello CN=Alice, your certificate was issued by O=Client Certificate Demo,CN=localhost!"), response.text());
request.dispose();
}
static boolean isWebKitMacOS() {
return isWebKit() && isMac;
}
@Test
@DisabledIf(value="com.microsoft.playwright.TestClientCertificates#isWebKitMacOS", disabledReason="The network connection was lost.")
public void shouldWorkWithBrowserNewContext() {
Browser.NewContextOptions options = new Browser.NewContextOptions()
.setIgnoreHTTPSErrors(true) // TODO: remove once we can pass a custom CA.
.setClientCertificates(asList(
new ClientCertificate(customServer.origin)
.setCertPath(asset("client-certificates/client/trusted/cert.pem"))
.setKeyPath(asset("client-certificates/client/trusted/key.pem"))));
try (BrowserContext context = browser.newContext(options)) {
Page page = context.newPage();
{
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);
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 shouldWorkWithBrowserNewPage() {
Browser.NewPageOptions options = new Browser.NewPageOptions()
.setIgnoreHTTPSErrors(true) // TODO: remove once we can pass a custom CA.
.setClientCertificates(asList(
new ClientCertificate(customServer.origin)
.setCertPath(asset("client-certificates/client/trusted/cert.pem"))
.setKeyPath(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);
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);
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 shouldWorkWithBrowserLaunchPersistentContext(@TempDir Path tmpDir) {
BrowserType.LaunchPersistentContextOptions options = new BrowserType.LaunchPersistentContextOptions()
.setIgnoreHTTPSErrors(true) // TODO: remove once we can pass a custom CA.
.setClientCertificates(asList(
new ClientCertificate(customServer.origin)
.setCertPath(asset("client-certificates/client/trusted/cert.pem"))
.setKeyPath(asset("client-certificates/client/trusted/key.pem"))));
try (BrowserContext context = browser.browserType().launchPersistentContext(tmpDir.resolve("profile") , options)) {
Page page = context.pages().get(0);
{
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());
}
}
}
@@ -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();
@@ -43,9 +43,9 @@ public class TestElementHandleConvenience extends TestBase {
String text = String.join("", Collections.nCopies(100, "😛"));
page.setContent("<div title='" + text + "'>" + text + "</div>");
ElementHandle handle = page.querySelector("div");
context.waitForCondition(() -> "JSHandle@<div title=\"😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛>😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛…</div>"
context.waitForCondition(() -> "JSHandle@<div title=\"😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛\">😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛…</div>"
.equals(handle.toString()), new BrowserContext.WaitForConditionOptions().setTimeout(5_000));
assertEquals("JSHandle@<div title=\"😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛>😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛…</div>", handle.toString());
assertEquals("JSHandle@<div title=\"😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛\">😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛…</div>", handle.toString());
}
@Test
@@ -18,6 +18,7 @@ package com.microsoft.playwright;
import com.google.gson.Gson;
import com.microsoft.playwright.options.HttpCredentials;
import com.microsoft.playwright.options.HttpCredentialsSend;
import com.microsoft.playwright.options.HttpHeader;
import com.microsoft.playwright.options.RequestOptions;
import org.junit.jupiter.api.Disabled;
@@ -25,6 +26,7 @@ import org.junit.jupiter.api.Test;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
@@ -490,4 +492,60 @@ public class TestGlobalFetch extends TestBase {
assertEquals(401, response.status());
}
@Test
void shouldSupportHTTPCredentialsSendImmediately() throws InterruptedException, ExecutionException {
APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions()
.setHttpCredentials(new HttpCredentials("user", "pass")
.setOrigin(server.PREFIX.toUpperCase())
.setSend(HttpCredentialsSend.ALWAYS)));
Future<Server.Request> serverRequestFuture = server.futureRequest("/empty.html");
APIResponse response = request.get(server.EMPTY_PAGE);
assertEquals("Basic " + Base64.getEncoder().encodeToString("user:pass".getBytes()),
serverRequestFuture.get().headers.getFirst("authorization"));
assertEquals(200, response.status());
// Second request and response to another origin
serverRequestFuture = server.futureRequest("/empty.html");
response = request.get(server.CROSS_PROCESS_PREFIX + "/empty.html");
// Not sent to another origin
assertNull(serverRequestFuture.get().headers.get("authorization"));
assertEquals(200, response.status());
request.dispose();
}
@Test
void shouldSupportDisposeReason() {
APIRequestContext request = playwright.request().newContext();
request.dispose(new APIRequestContext.DisposeOptions().setReason("My reason"));
PlaywrightException e = assertThrows(PlaywrightException.class, () -> request.get(server.EMPTY_PAGE));
assertTrue(e.getMessage().contains("My reason"), e.getMessage());
}
@Test
public void shouldRetryECONNRESET() {
int[] requestCount = {0};
server.setRoute("/test", exchange -> {
if (requestCount[0]++ < 3) {
exchange.close();
return;
}
exchange.getResponseHeaders().add("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, 0);
try (OutputStreamWriter writer = new OutputStreamWriter(exchange.getResponseBody())) {
writer.write("Hello!");
}
});
APIRequestContext requestContext = playwright.request().newContext();
APIResponse response = requestContext.get(server.PREFIX + "/test",
RequestOptions.create().setMaxRetries(3));
assertEquals(200, response.status());
assertEquals("Hello!", response.text());
assertEquals(4, requestCount[0]);
requestContext.dispose();
}
}
@@ -16,9 +16,12 @@
package com.microsoft.playwright;
import com.microsoft.playwright.options.KeyboardModifier;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestLocatorClick extends TestBase {
@@ -54,4 +57,12 @@ public class TestLocatorClick extends TestBase {
assertEquals(true, page.evaluate("double"));
assertEquals("Clicked", page.evaluate("result"));
}
@Test
void shouldSupportCotrolOrMetaModifier() {
page.setContent("<a href='" + server.PREFIX + "/title.html'>Go</a>");
Page newPage = page.context().waitForPage(() ->
page.getByText("Go").click(new Locator.ClickOptions().setModifiers(asList(KeyboardModifier.CONTROLORMETA))));
assertThat(newPage).hasURL(server.PREFIX + "/title.html");
}
}
@@ -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
@@ -16,14 +16,12 @@
package com.microsoft.playwright;
import com.microsoft.playwright.options.HttpHeader;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
@@ -113,15 +111,50 @@ public class TestNetworkRequest extends TestBase {
assertTrue(response.request().headers().get("user-agent").contains("WebKit"));
}
static boolean isWebKitWindowsOrChromium() {
return (isWebKit() && getOS() == Utils.OS.WINDOWS) || isChromium();
}
static boolean isWebKitWindows() {
return isWebKit() && getOS() == Utils.OS.WINDOWS;
}
// HTTP server in java does not preserve headers order.
static List<HttpHeader> normalizeServerHeaders(Map<String,List<String>> headers) {
List<HttpHeader> serverHeaders = new ArrayList<>();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
for (String value: entry.getValue()) {
HttpHeader header = new HttpHeader();
header.name = entry.getKey().toLowerCase();
header.value = value;
serverHeaders.add(header);
}
}
Comparator<HttpHeader> comparator = Comparator.comparing(h -> h.name);
serverHeaders.sort(comparator);
return serverHeaders;
}
static List<HttpHeader> normalizeAllHeaders(Map<String, String> headers) {
List<HttpHeader> serverHeaders = new ArrayList<>();
for (Map.Entry<String, String> entry : headers.entrySet()) {
HttpHeader header = new HttpHeader();
header.name = entry.getKey().toLowerCase();
header.value = entry.getValue();
serverHeaders.add(header);
}
Comparator<HttpHeader> comparator = Comparator.comparing(h -> h.name);
serverHeaders.sort(comparator);
return serverHeaders;
}
static List<HttpHeader> adjustServerHeaders(List<HttpHeader> headers) {
if (isFirefox()) {
for (Iterator<HttpHeader> it = headers.iterator(); it.hasNext(); ) {
if ("priority".equals(it.next().name)) {
it.remove();
}
}
}
return headers;
}
@Test
@DisabledIf(value="isWebKitWindows", disabledReason="Flaky, see https://github.com/microsoft/playwright/issues/6690")
void shouldGetTheSameHeadersAsTheServer() throws ExecutionException, InterruptedException {
@@ -133,9 +166,10 @@ public class TestNetworkRequest extends TestBase {
}
});
Response response = page.navigate(server.PREFIX + "/empty.html");
Map<String, String> expectedHeaders = serverRequest.get().headers.entrySet().stream().collect(
Collectors.toMap(e -> e.getKey().toLowerCase(), e -> e.getValue().get(0)));
assertEquals(expectedHeaders, response.request().allHeaders());
List<HttpHeader> expectedHeaders = adjustServerHeaders(normalizeServerHeaders(serverRequest.get().headers));
List<HttpHeader> allHeaders = normalizeAllHeaders(response.request().allHeaders());
assertJsonEquals(expectedHeaders, allHeaders);
}
@Test
@@ -157,9 +191,9 @@ public class TestNetworkRequest extends TestBase {
"}", server.CROSS_PROCESS_PREFIX + "/something");
assertEquals("done", text);
});
Map<String, String> expectedHeaders = serverRequest.get().headers.entrySet().stream().collect(
Collectors.toMap(e -> e.getKey().toLowerCase(), e -> e.getValue().get(0)));
assertEquals(expectedHeaders, response.request().allHeaders());
List<HttpHeader> expectedHeaders = adjustServerHeaders(normalizeServerHeaders(serverRequest.get().headers));
List<HttpHeader> allHeaders = normalizeAllHeaders(response.request().allHeaders());
assertJsonEquals(expectedHeaders, allHeaders);
}
@Test
@@ -44,7 +44,7 @@ public class TestOptionsFactories {
return headfulEnv != null && !"0".equals(headfulEnv) && !"false".equals(headfulEnv);
}
private static String getBrowserName() {
public static String getBrowserName() {
String browserName = System.getenv("BROWSER");
if (browserName == null) {
browserName = "chromium";
@@ -347,4 +347,13 @@ public class TestPageBasic extends TestBase {
}));
assertTrue(e.getMessage().contains("The reason."), e.getMessage());
}
@Test
void shouldProhibitNullListeners() {
Page newPage = context.newPage();
PlaywrightException e = assertThrows(PlaywrightException.class, () -> newPage.onClose(null));
assertTrue(e.getMessage().contains("Can't add a null listener"));
}
}
@@ -0,0 +1,464 @@
package com.microsoft.playwright;
import com.microsoft.playwright.junit.FixtureTest;
import com.microsoft.playwright.junit.UsePlaywright;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import static com.microsoft.playwright.Utils.assertJsonEquals;
import static org.junit.jupiter.api.Assertions.*;
@FixtureTest
@UsePlaywright
public class TestPageClock {
private ArrayList<Object> calls;
@BeforeEach
void exposeStubFunction(Page page) {
calls = new ArrayList();
page.exposeFunction("stub", (Object... params) -> {
calls.add(params);
return null;
});
}
private void setupRunForTest(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.clock().pauseAt(1000);
}
@Test
void runForTriggersImmediatelyWithoutSpecifiedDelay(Page page) {
setupRunForTest(page);
page.evaluate("() => setTimeout(window.stub)");
page.clock().runFor(0);
assertEquals(1, calls.size());
}
@Test
void runForDoesNotTriggerWithoutSufficientDelay(Page page) {
setupRunForTest(page);
// Trigger the stub with a delay
page.evaluate("() => setTimeout(window.stub, 100)");
page.clock().runFor(11);
assertEquals(0, calls.size());
}
@Test
void runForTriggersAfterSufficientDelay(Page page) {
setupRunForTest(page);
page.evaluate("() => setTimeout(window.stub, 100)");
page.clock().runFor(100);
assertEquals(1, calls.size());
}
@Test
void runForTriggersSimultaneousTimers(Page page) {
setupRunForTest(page);
page.evaluate("() => { setTimeout(window.stub, 100);" +
"setTimeout(window.stub, 100); }");
page.clock().runFor(100);
assertEquals(2, calls.size());
}
@Test
void runForTriggersMultipleSimultaneousTimers(Page page) {
setupRunForTest(page);
page.evaluate("() => { setTimeout(window.stub, 100);" +
"setTimeout(window.stub, 100);" +
"setTimeout(window.stub, 99);" +
"setTimeout(window.stub, 100); }");
page.clock().runFor(100);
assertEquals(4, calls.size());
}
@Test
void runForWaitsAfterSetTimeoutWasCalled(Page page) {
setupRunForTest(page);
page.evaluate("() => setTimeout(window.stub, 150)");
page.clock().runFor(50);
assertEquals(0, calls.size());
page.clock().runFor(100);
assertEquals(1, calls.size());
}
@Test
void runForTriggersEventWhenSomeThrow(Page page) {
setupRunForTest(page);
page.evaluate("() => {\n" +
" setTimeout(() => {throw new Error(); }, 100);\n" +
" setTimeout(window.stub, 120);\n" +
"}");
assertThrows(PlaywrightException.class, () -> page.clock().runFor(120));
assertEquals(1, calls.size());
}
@Test
void runForCreatesUpdatedDateWhileTicking(Page page) {
setupRunForTest(page);
page.clock().setSystemTime(0);
page.evaluate("() => setInterval(() => { window.stub(new Date().getTime()); }, 10)");
page.clock().runFor(100);
assertJsonEquals("[[10],[20],[30],[40],[50],[60],[70],[80],[90],[100]]", calls);
}
@Test
void runForPasses8Seconds(Page page) {
setupRunForTest(page);
page.evaluate("() => setInterval(window.stub, 4000)");
page.clock().runFor("08");
assertEquals(2, calls.size());
}
@Test
void runForPasses1Minute(Page page) {
setupRunForTest(page);
page.evaluate("() => setInterval(window.stub, 6000)");
page.clock().runFor("01:00");
assertEquals(10, calls.size());
}
@Test
void runForPasses2Hours34MinutesAnd10Seconds(Page page) {
setupRunForTest(page);
page.evaluate("() => setInterval(window.stub, 10000)");
page.clock().runFor("02:34:10");
assertEquals(925, calls.size());
}
@Test
void runForThrowsForInvalidFormat(Page page) {
setupRunForTest(page);
page.evaluate("() => setInterval(window.stub, 10000)");
assertThrows(PlaywrightException.class, () -> page.clock().runFor("12:02:34:10"));
assertEquals(0, calls.size());
}
@Test
void runForReturnsTheCurrentNowValue(Page page) {
setupRunForTest(page);
page.clock().setSystemTime(0);
final int value = 200;
page.clock().runFor(value);
assertEquals(value, page.evaluate("() => Date.now()"));
}
private void setupFastForwardTest(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.clock().pauseAt(1000);
}
@Test
void fastForwardIgnoresTimersWhichWouldntBeRun(Page page) {
setupFastForwardTest(page);
page.evaluate("() => setTimeout(() => { window.stub('should not be logged'); }, 1000)");
page.clock().fastForward(500);
assertEquals(0, calls.size());
}
@Test
void fastForwardPushesBackExecutionTimeForSkippedTimers(Page page) {
setupFastForwardTest(page);
page.evaluate("() => setTimeout(() => { window.stub(Date.now()); }, 1000)");
page.clock().fastForward(2000);
assertEquals(1, calls.size());
assertEquals(1000 + 2000, ((Object[])calls.get(0))[0]);
}
@Test
void fastForwardSupportsStringTimeArguments(Page page) {
setupFastForwardTest(page);
page.evaluate("() => setTimeout(() => { window.stub(Date.now()); }, 100000)");
page.clock().fastForward("01:50");
assertEquals(1, calls.size());
assertEquals(1000 + 110000, ((Object[])calls.get(0))[0]);
}
private void setupStubTimers(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.clock().pauseAt(1000);
}
@Test
void setsInitialTimestamp(Page page) {
setupStubTimers(page);
page.clock().setSystemTime(1400);
assertEquals(1400, page.evaluate("() => Date.now()"));
}
@Test
void replacesGlobalSetTimeout(Page page) {
setupStubTimers(page);
page.evaluate("() => setTimeout(window.stub, 1000)");
page.clock().runFor(1000);
assertEquals(1, calls.size());
}
@Test
void globalFakeSetTimeoutShouldReturnId(Page page) {
setupStubTimers(page);
Double to = (Double) page.evaluate("() => setTimeout(window.stub, 1000)");
assertTrue(to > 0);
}
@Test
void replacesGlobalClearTimeout(Page page) {
setupStubTimers(page);
page.evaluate("() => { const to = setTimeout(window.stub, 1000); clearTimeout(to); }");
page.clock().runFor(1000);
assertEquals(0, calls.size());
}
@Test
void replacesGlobalSetInterval(Page page) {
setupStubTimers(page);
page.evaluate("() => setInterval(window.stub, 500)");
page.clock().runFor(1000);
assertEquals(2, calls.size());
}
@Test
void replacesGlobalClearInterval(Page page) {
setupStubTimers(page);
page.evaluate("() => { const to = setInterval(window.stub, 500); clearInterval(to); }");
page.clock().runFor(1000);
assertEquals(0, calls.size());
}
@Test
void replacesGlobalPerformanceNow(Page page) {
}
@Test
void fakesDateConstructor(Page page) {
setupStubTimers(page);
Integer now = (Integer) page.evaluate("() => new Date().getTime()");
assertEquals(1000, now);
}
@Test
void replacesGlobalPerformanceTimeOrigin(Page page) {
}
@Test
void shouldTickAfterPopup(Page page) throws ParseException {
page.clock().install(new Clock.InstallOptions().setTime(0));
Date now = new SimpleDateFormat("yyyy-MM-dd").parse("2015-09-25");
page.clock().pauseAt(now.getTime());
Page popup = page.waitForPopup(() -> {
page.evaluate("() => window.open('about:blank')");
});
Double popupTime = (Double) popup.evaluate("() => Date.now()");
assertEquals(now.getTime(), popupTime);
page.clock().runFor(1000);
Double popupTimeAfter = (Double) popup.evaluate("() => Date.now()");
assertEquals(now.getTime() + 1000, popupTimeAfter);
}
@Test
void shouldTickBeforePopup(Page page) throws ParseException {
page.clock().install(new Clock.InstallOptions().setTime(0));
Date now = new SimpleDateFormat("yyyy-MM-dd").parse("2015-09-25");
page.clock().pauseAt(now.getTime());
page.clock().runFor(1000);
Page popup = page.waitForPopup(() -> {
page.evaluate("() => window.open('about:blank')");
});
Double popupTime = (Double) popup.evaluate("() => Date.now()");
assertEquals(now.getTime() + 1000, popupTime);
}
@Test
void shouldRunTimeBeforePopup(Page page, Server server) {
server.setRoute("/popup.html", exchange -> {
exchange.getResponseHeaders().set("Content-type", "text/html");
exchange.sendResponseHeaders(200, 0);
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
writer.write("<script>window.time = Date.now()</script>");
}
});
page.navigate(server.EMPTY_PAGE);
page.waitForTimeout(2000);
Page popup = page.waitForPopup(() -> {
page.evaluate("url => window.open(url)", server.PREFIX + "/popup.html");
});
Double popupTime = (Double) popup.evaluate("time");
assertTrue(popupTime >= 2000);
}
@Test
void shouldNotRunTimeBeforePopupOnPause(Page page, Server server) {
server.setRoute("/popup.html", exchange -> {
exchange.getResponseHeaders().set("Content-type", "text/html");
exchange.sendResponseHeaders(200, 0);
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
writer.write("<script>window.time = Date.now()</script>");
}
});
page.clock().install(new Clock.InstallOptions().setTime(0));
page.clock().pauseAt(1000);
page.navigate(server.EMPTY_PAGE);
page.waitForTimeout(2000);
Page popup = page.waitForPopup(() -> {
page.evaluate("url => window.open(url)", server.PREFIX + "/popup.html");
});
Object popupTime = popup.evaluate("time");
assertEquals(1000, popupTime);
}
@Test
void setFixedTimeDoesNotFakeMethods(Page page) {
page.clock().setFixedTime(0);
// Should not stall.
page.evaluate("() => new Promise(f => setTimeout(f, 1))");
}
@Test
void setFixedTimeAllowsSettingTimeMultipleTimes(Page page) {
page.clock().setFixedTime(100);
assertEquals(100, page.evaluate("() => Date.now()"));
page.clock().setFixedTime(200);
assertEquals(200, page.evaluate("() => Date.now()"));
}
@Test
void setFixedTimeFixedTimeIsNotAffectedByClockManipulation(Page page) {
page.clock().setFixedTime(100);
assertEquals(100, page.evaluate("() => Date.now()"));
page.clock().fastForward(20);
assertEquals(100, page.evaluate("() => Date.now()"));
}
@Test
void setFixedTimeAllowsInstallingFakeTimersAfterSettingTime(Page page) {
page.clock().setFixedTime(100);
assertEquals(100, page.evaluate("() => Date.now()"));
page.clock().setFixedTime(200);
page.evaluate("async () => { setTimeout(() => window.stub(Date.now()), 0); }");
page.clock().runFor(0);
assertEquals(1, calls.size());
assertEquals(200, ((Object[]) calls.get(0))[0]);
}
@Test
void whileRunningShouldProgressTime(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.waitForTimeout(1000);
int now = (int) page.evaluate("() => Date.now()");
assertTrue(now >= 1000 && now <= 2000);
}
@Test
void whileRunningShouldRunFor(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().runFor(10000);
int now = (int) page.evaluate("() => Date.now()");
assertTrue(now >= 10000 && now <= 11000);
}
@Test
void whileRunningShouldFastForward(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().fastForward(10000);
int now = (int) page.evaluate("() => Date.now()");
assertTrue(now >= 10000 && now <= 11000);
}
@Test
void whileRunningShouldFastForwardTo(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().fastForward(10000);
int now = (int) page.evaluate("() => Date.now()");
assertTrue(now >= 10000 && now <= 11000);
}
@Test
void whileRunningShouldPause(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().pauseAt(1000);
page.waitForTimeout(1000);
page.clock().resume();
int now = (int) page.evaluate("() => Date.now()");
assertTrue(now >= 0 && now <= 1000);
}
@Test
void whileRunningShouldPauseAndFastForward(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().pauseAt(1000);
page.clock().fastForward(1000);
int now = (int) page.evaluate("() => Date.now()");
assertEquals(2000, now);
}
@Test
void whileRunningShouldSetSystemTimeOnPause(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().pauseAt(1000);
int now = (int) page.evaluate("() => Date.now()");
assertEquals(1000, now);
}
@Test
void whileOnPauseFastForwardShouldNotRunNestedImmediate(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().pauseAt(1000);
page.evaluate("() => { setTimeout(() => { window.stub('outer'); setTimeout(() => window.stub('inner'), 0); }, 1000); }");
page.clock().fastForward(1000);
assertEquals(1, calls.size());
assertEquals("outer", ((Object[]) calls.get(0))[0]);
page.clock().fastForward(1);
assertEquals(2, calls.size());
assertEquals("inner", ((Object[]) calls.get(1))[0]);
}
@Test
void whileOnPauseRunForShouldNotRunNestedImmediate(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().pauseAt(1000);
page.evaluate("() => { setTimeout(() => { window.stub('outer'); setTimeout(() => window.stub('inner'), 0); }, 1000); }");
page.clock().runFor(1000);
assertEquals(1, calls.size());
assertEquals("outer", ((Object[]) calls.get(0))[0]);
page.clock().runFor(1);
assertEquals(2, calls.size());
assertEquals("inner", ((Object[]) calls.get(1))[0]);
}
@Test
void whileOnPauseRunForShouldNotRunNestedImmediateFromMicrotask(Page page) {
page.clock().install(new Clock.InstallOptions().setTime(0));
page.navigate("data:text/html,");
page.clock().pauseAt(1000);
page.evaluate("() => { setTimeout(() => { window.stub('outer'); void Promise.resolve().then(() => setTimeout(() => window.stub('inner'), 0)); }, 1000); }");
page.clock().runFor(1000);
assertEquals(1, calls.size());
assertEquals("outer", ((Object[]) calls.get(0))[0]);
page.clock().runFor(1);
assertEquals(2, calls.size());
assertEquals("inner", ((Object[]) calls.get(1))[0]);
}
@Test
void shouldThrowForInvalidDate(Page page) {
Exception exception1 = assertThrows(PlaywrightException.class, () -> page.clock().setSystemTime("invalid"));
assertTrue(exception1.getMessage().contains("Invalid date: invalid"), exception1.getMessage());
}
}
@@ -539,19 +539,30 @@ public class TestPageEvaluate extends TestBase {
@Test
void shouldEvaluateException() {
String result = (String) page.evaluate("() => {\n" +
Exception result = (Exception) page.evaluate("() => {\n" +
" return (function functionOnStack() {\n" +
" return new Error('error message');\n" +
" })();\n" +
"}");
assertTrue(result.contains("Error: error message"));
assertTrue(result.contains("functionOnStack"));
assertTrue(result.getMessage().contains("Error: error message"), result.getMessage());
assertTrue(result.getMessage().contains("functionOnStack"), result.getMessage());
}
@Test
void shouldEvaluateException2() {
Object error = page.evaluate("new Error('error message')");
assertTrue(((String) error).contains("Error: error message"));
Exception error = (Exception) page.evaluate("new Error('error message')");
assertTrue(error.getMessage().contains("Error: error message"), error.getMessage());
}
@Test
void shouldPassExceptionArgument() {
Exception e = new Exception("error message");
Map<String, Object> received = (Map<String, Object>) page.evaluate("e => { return { message: e.message, name: e.name, stack: e.stack }; }", e);
assertEquals("error message", received.get("message"));
assertEquals("Exception", received.get("name"));
assertNotNull(received.get("stack"));
assertTrue(received.get("stack").toString().contains("shouldPassExceptionArgument"), received.get("stack").toString());
}
@Test
@@ -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");
@@ -62,12 +62,18 @@ public class TestPageNetworkRequest extends TestBase {
});
responseWritten.acquire();
List<HttpHeader> expectedHeaders = serverHeaders;
if (isWebKit() && isWindows) {
expectedHeaders = expectedHeaders.stream()
.filter(h -> !"accept-encoding".equals(h.name.toLowerCase()) && !"accept-language".equals(h.name.toLowerCase()))
.collect(Collectors.toList());
}
if (isFirefox()) {
expectedHeaders = expectedHeaders.stream()
.filter(h -> !"priority".equals(h.name.toLowerCase()))
.collect(Collectors.toList());
}
List<HttpHeader> headers = request.headersArray();
// Java HTTP server normalizes header names, work around that:
@@ -21,7 +21,6 @@ import com.microsoft.playwright.options.FilePayload;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.platform.commons.support.AnnotationSupport;
import java.io.*;
import java.nio.file.Files;
@@ -429,5 +428,85 @@ public class TestPageSetInputFiles extends TestBase {
// rounds it to seconds in WebKit: 1696272058110 -> 1696272058000.
assertTrue(Math.abs(timestamps.get(0) - expected.toMillis()) < 1000, "expected: " + expected.toMillis() + "; actual: " + timestamps.get(0));
}
static void writeFile(Path file, String content) throws IOException {
try (Writer stream = new OutputStreamWriter(Files.newOutputStream(file))) {
stream.write(content);
}
}
@Test
void shouldUploadAFolder(@TempDir Path tmpDir) throws IOException {
page.navigate(server.PREFIX + "/input/folderupload.html");
Locator input = page.locator("input[name=\"file1\"]");
Path dir = tmpDir.resolve("file-upload-test");
Files.createDirectories(dir);
writeFile(dir.resolve("file1.txt"), "file1 content");
writeFile(dir.resolve("file2"), "file2 content");
Files.createDirectories(dir.resolve("sub-dir"));
writeFile(dir.resolve("sub-dir").resolve("really.txt"), "sub-dir file content");
input.setInputFiles(dir);
List<String> webkitRelativePaths = (List<String>) input.evaluate("e => [...e.files].map(f => f.webkitRelativePath)");
List<String> relativePathsSorted = new ArrayList<>(webkitRelativePaths);
relativePathsSorted.sort(String::compareTo);
// https://issues.chromium.org/issues/345393164
if (isChromium() && !isHeadful() && chromiumVersionLessThan(browser.version(), "127.0.6533.0")) {
assertEquals(asList("file-upload-test/file1.txt", "file-upload-test/file2"), relativePathsSorted);
} else {
assertEquals(asList("file-upload-test/file1.txt", "file-upload-test/file2", "file-upload-test/sub-dir/really.txt"), relativePathsSorted);
}
for (int i = 0; i < webkitRelativePaths.size(); i++) {
String relativePath = webkitRelativePaths.get(i);
Object content = input.evaluate("(e, i) => {\n" +
" const reader = new FileReader();\n" +
" const promise = new Promise(fulfill => reader.onload = fulfill);\n" +
" reader.readAsText(e.files[i]);\n" +
" return promise.then(() => reader.result);\n" +
" }", i);
String expectedContent = new String(Files.readAllBytes(tmpDir.resolve(relativePath)));
assertEquals(expectedContent, content);
}
}
@Test
void shouldUploadAFolderAndThrowForMultipleDirectories() throws IOException {
page.navigate(server.PREFIX + "/input/folderupload.html");
Locator input = page.locator("input[name=\"file1\"]");
Path dir = Paths.get("file-upload-test"); // Adjust path as necessary
Files.createDirectories(dir.resolve("folder1"));
writeFile(dir.resolve("folder1").resolve("file1.txt"), "file1 content");
Files.createDirectories(dir.resolve("folder2"));
writeFile(dir.resolve("folder2").resolve("file2.txt"), "file2 content");
PlaywrightException e = assertThrows(PlaywrightException.class,
() -> input.setInputFiles(new Path[]{dir.resolve("folder1"), dir.resolve("folder2")}));
assertTrue(e.getMessage().contains("Multiple directories are not supported"), e.getMessage());
}
@Test
void shouldThrowIfADirectoryAndFilesArePassed() throws IOException {
// Skipping conditions based on environment not directly translatable to Java; needs custom implementation
page.navigate(server.PREFIX + "/input/folderupload.html");
Locator input = page.locator("input[name=\"file1\"]");
Path dir = Paths.get("file-upload-test"); // Adjust path as necessary
Files.createDirectories(dir.resolve("folder1"));
writeFile(dir.resolve("folder1").resolve("file1.txt"), "file1 content");
PlaywrightException e = assertThrows(PlaywrightException.class,
() -> input.setInputFiles(new Path[]{ dir.resolve("folder1"), dir.resolve("folder1").resolve("file1.txt") }));
assertTrue(e.getMessage().contains("File paths must be all files or a single directory"), e.getMessage());
}
@Test
void shouldThrowWhenUploadingAFolderInANormalFileUploadInput() throws IOException {
page.navigate(server.PREFIX + "/input/fileupload.html");
Locator input = page.locator("input[name=\"file1\"]");
Path dir = Paths.get("file-upload-test"); // Adjust path as necessary
Files.createDirectories(dir);
writeFile(dir.resolve("file1.txt"), "file1 content");
PlaywrightException e = assertThrows(PlaywrightException.class,
() -> input.setInputFiles(dir));
assertTrue(e.getMessage().contains("File input does not support directories, pass individual files instead"), e.getMessage());
}
}
@@ -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"));
}
}
@@ -18,16 +18,13 @@ package com.microsoft.playwright;
import org.junit.jupiter.api.Test;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static com.microsoft.playwright.options.KeyboardModifier.ALT;
import static com.microsoft.playwright.Utils.mapOf;
import static com.microsoft.playwright.options.KeyboardModifier.ALT;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestTap extends TestBase {
@@ -97,26 +94,13 @@ public class TestTap extends TestBase {
}
@Test
void shouldWaitForANavigationCausedByATap() throws InterruptedException {
void shouldNotWaitForANavigationCausedByATap() throws InterruptedException, ExecutionException {
page.navigate(server.EMPTY_PAGE);
page.setContent("<a href='/intercept-this.html'>link</a>;");
Semaphore responseWritten = new Semaphore(0);
List<String> events = Collections.synchronizedList(new ArrayList<>());
server.setRoute("/intercept-this.html", exchange -> {
// make sure the tap doesnt resolve too early
assertDoesNotThrow(() -> Thread.sleep(100));
exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
exchange.sendResponseHeaders(200, 0);
try (OutputStreamWriter writer = new OutputStreamWriter(exchange.getResponseBody())) {
writer.write("foo");
}
events.add("sent response");
responseWritten.release();
});
Future<Server.Request> serverReq = server.futureRequest("/intercept-this.html");
server.setRoute("/intercept-this.html", exchange -> {});
page.tap("a");
events.add("tap finished");
responseWritten.acquire();
assertEquals(asList("sent response", "tap finished"), events);
serverReq.get();
}
@Test
@@ -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"));

Some files were not shown because too many files have changed in this diff Show More