diff --git a/.azure-pipelines/guardian/SDL/.gdnsuppress b/.azure-pipelines/guardian/SDL/.gdnsuppress
new file mode 100644
index 000000000..0973f4f8f
--- /dev/null
+++ b/.azure-pipelines/guardian/SDL/.gdnsuppress
@@ -0,0 +1,115 @@
+{
+ "hydrated": false,
+ "properties": {
+ "helpUri": "https://eng.ms/docs/microsoft-security/security/azure-security/cloudai-security-fundamentals-engineering/security-integration/guardian-wiki/microsoft-guardian/general/suppressions",
+ "hydrationStatus": "This file does not contain identifying data. It is safe to check into your repo. To hydrate this file with identifying data, run `guardian hydrate --help` and follow the guidance."
+ },
+ "version": "1.0.0",
+ "suppressionSets": {
+ "default": {
+ "name": "default",
+ "createdDate": "2024-02-06 20:37:57Z",
+ "lastUpdatedDate": "2024-02-06 20:37:57Z"
+ }
+ },
+ "results": {
+ "de854c6ab9b27b1ec642cec1a51059b92f88815a231c1c8f4b8e71d9e378f174": {
+ "signature": "de854c6ab9b27b1ec642cec1a51059b92f88815a231c1c8f4b8e71d9e378f174",
+ "alternativeSignatures": [
+ "79827cf2e75a7f99eec716562fb9fa0d49014ac96b7afc76d29d79a33e8edd94"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "ebe0026db71ae4bb2d8e76b706198003079a5c095658de8dd49e67f7e572ea46": {
+ "signature": "ebe0026db71ae4bb2d8e76b706198003079a5c095658de8dd49e67f7e572ea46",
+ "alternativeSignatures": [],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "bb02ef965dce40b6c950b6d0cf8a9f41c08c5e33f17268fb208f3687b11ffa26": {
+ "signature": "bb02ef965dce40b6c950b6d0cf8a9f41c08c5e33f17268fb208f3687b11ffa26",
+ "alternativeSignatures": [
+ "3a8630eaccc2c5c39ae78836bb115bf55557058bad206fdad7dbe4f0ae466ed1"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "dffa3e24f6dc7542d741b2fab22eec657aca441a51cee515ca9bb4932995a416": {
+ "signature": "dffa3e24f6dc7542d741b2fab22eec657aca441a51cee515ca9bb4932995a416",
+ "alternativeSignatures": [
+ "56a4b454840e2c21d44a76d9ab09fde76fba682ce7508a3f6abf7b411d389e56"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "5dbcaaac8cdccc6df557cbde94e5d7e0f1c8a67546ba82a1b85b629030f3d311": {
+ "signature": "5dbcaaac8cdccc6df557cbde94e5d7e0f1c8a67546ba82a1b85b629030f3d311",
+ "alternativeSignatures": [
+ "fdb8e8af8d5697f767d0e55194f91d4a089d981555e00d058ba866acb8602014"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "b7db026b2a60bdb63af1c0938ac16d9414bb4d38e9efdc51626e12aa55f6b72f": {
+ "signature": "b7db026b2a60bdb63af1c0938ac16d9414bb4d38e9efdc51626e12aa55f6b72f",
+ "alternativeSignatures": [
+ "bf7bb897e644659827d8dc8d55f719296d3ab94dc750b666ce90d8057361d9d5"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "aa702d85554c352e3016e3ec3d790df489833dc97e3733c58b57915ec125f47b": {
+ "signature": "aa702d85554c352e3016e3ec3d790df489833dc97e3733c58b57915ec125f47b",
+ "alternativeSignatures": [
+ "948787329d52a66b4691383c81af407b03e68344a6685bbab3cfa8eb8db34f81"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "38174b5c9b474c3c0278d4c4173c14022e03dec3dc4db5ced51d2ca8459e7f2a": {
+ "signature": "38174b5c9b474c3c0278d4c4173c14022e03dec3dc4db5ced51d2ca8459e7f2a",
+ "alternativeSignatures": [
+ "a9efa99679f3966da96a8b89f1250576cfceda774556d43ea89ea84289967276"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "08a4e1be4662d897e5b2b7a7dc6d6901405462cd2d5f8ad433c13e12a8503fb6": {
+ "signature": "08a4e1be4662d897e5b2b7a7dc6d6901405462cd2d5f8ad433c13e12a8503fb6",
+ "alternativeSignatures": [
+ "009132f89939956a3f4471bb13353394015c9a7e675d118aa427e75f05658e05"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ },
+ "551d69737553150380e58bc9a8ae1e8f17da931561ea4e195781fb8cad225188": {
+ "signature": "551d69737553150380e58bc9a8ae1e8f17da931561ea4e195781fb8cad225188",
+ "alternativeSignatures": [
+ "617ad56322c5fb82a162b0b583e676d66a8e76b0d444aaab487865e4bf89e83b"
+ ],
+ "memberOf": [
+ "default"
+ ],
+ "createdDate": "2024-02-06 20:37:57Z"
+ }
+ }
+}
\ No newline at end of file
diff --git a/.azure-pipelines/publish-docker.yml b/.azure-pipelines/publish-docker.yml
new file mode 100644
index 000000000..c9b3b0528
--- /dev/null
+++ b/.azure-pipelines/publish-docker.yml
@@ -0,0 +1,122 @@
+# Trigger: any `v*` release tag (e.g. v1.40.0).
+# Can also be queued manually from the ADO UI.
+trigger:
+ tags:
+ include:
+ - v*
+ exclude:
+ - v*-*
+
+pr: none
+
+parameters:
+- name: releaseChannel
+ displayName: "IMPORTANT: set this to 'canary' when triggering manually"
+ type: string
+ default: stable
+ values:
+ - stable
+ - canary
+
+resources:
+ repositories:
+ - repository: 1esPipelines
+ type: git
+ name: 1ESPipelineTemplates/1ESPipelineTemplates
+ ref: refs/tags/release
+
+extends:
+ template: v1/1ES.Official.PipelineTemplate.yml@1esPipelines
+ parameters:
+ pool:
+ name: DevDivPlaywrightAzurePipelinesUbuntu2204
+ os: linux
+ sdl:
+ sourceAnalysisPool:
+ name: DevDivPlaywrightAzurePipelinesWindows2022
+ # The image must be windows-based due to restrictions of the SDL tools. See: https://aka.ms/AAo6v8e
+ os: windows
+ suppression:
+ suppressionFile: $(Build.SourcesDirectory)\.azure-pipelines\guardian\SDL\.gdnsuppress
+ stages:
+ - stage: Publish
+ jobs:
+ - job: PublishDocker
+ displayName: "Publish Docker images to ACR"
+ # arm64 images are cross-built under QEMU emulation, which is slow.
+ timeoutInMinutes: 360
+ steps:
+ - checkout: self
+ persistCredentials: false
+ displayName: "Checkout code"
+
+ - task: UseNode@1
+ inputs:
+ version: '26.x'
+ displayName: "Install Node.js"
+
+ # Relocate the Docker data-root to the large /mnt volume: this job builds
+ # 6 images (jammy/noble/resolute x amd64/arm64) and `docker system prune`s
+ # between them, so the default disk fills up.
+ - task: Bash@3
+ displayName: "Setup docker"
+ inputs:
+ targetType: "inline"
+ script: |
+ set -x
+ sudo service docker stop
+ sudo mkdir -p /etc/docker
+ echo '{ "data-root": "/mnt/docker" }' | sudo tee /etc/docker/daemon.json
+ sudo service docker start
+
+ # scripts/build_driver.sh builds the driver from .upstream/ on the host. `npm ci` uses
+ # the registry and the credentials of this .npmrc file. The Docker build context is
+ # utils/docker (see build.sh), thus this file does not go into the images.
+ - task: Bash@3
+ displayName: "setup .npmrc"
+ inputs:
+ targetType: "inline"
+ script: |
+ echo "registry=https://devdiv.pkgs.visualstudio.com/DevDiv/_packaging/DevDiv_PublicPackages/npm/registry/" >> .npmrc
+
+ - task: npmAuthenticate@0
+ displayName: "authenticate the private npm registry"
+ inputs:
+ workingFile: .npmrc
+
+ # Must run before MavenAuthenticate@0 so the credentials it injects into
+ # ~/.m2/settings.xml are not overwritten by the copy.
+ - bash: |
+ mkdir -p ~/.m2
+ cp .azure-pipelines/settings.xml ~/.m2/settings.xml
+ displayName: 'Copy settings.xml (mirror Maven Central to DevDiv_PublicPackages)'
+
+ - task: MavenAuthenticate@0
+ displayName: 'Authenticate to DevDiv_PublicPackages feed'
+ inputs:
+ artifactsFeeds: DevDiv_PublicPackages
+
+ - task: AzureCLI@2
+ displayName: "Login to ACR via OIDC"
+ inputs:
+ azureSubscription: "Playwright-CDN"
+ scriptType: "bash"
+ scriptLocation: "inlineScript"
+ inlineScript: "az acr login --name playwright"
+
+ - task: Bash@3
+ displayName: "Register QEMU (binfmt) for arm64 cross-build"
+ inputs:
+ targetType: "inline"
+ script: "docker run --rm --privileged ${ACR_CACHE_PREFIX}tonistiigi/binfmt --install arm64"
+ env:
+ ACR_CACHE_PREFIX: "playwright.azurecr.io/cached/"
+
+ - task: Bash@3
+ displayName: "Build & publish Docker images"
+ inputs:
+ targetType: "inline"
+ script: ./utils/docker/publish_docker.sh ${{ parameters.releaseChannel }}
+ env:
+ ACR_CACHE_PREFIX: "playwright.azurecr.io/cached/"
+ UBUNTU_MIRROR_PREFIX: "azure."
diff --git a/.azure-pipelines/publish.yml b/.azure-pipelines/publish.yml
new file mode 100644
index 000000000..1478ea8cb
--- /dev/null
+++ b/.azure-pipelines/publish.yml
@@ -0,0 +1,137 @@
+pr: none
+
+trigger:
+ tags:
+ include:
+ - '*'
+
+resources:
+ repositories:
+ - repository: 1esPipelines
+ type: git
+ name: 1ESPipelineTemplates/1ESPipelineTemplates
+ ref: refs/tags/release
+
+extends:
+ template: v1/1ES.Official.PipelineTemplate.yml@1esPipelines
+ parameters:
+ pool:
+ name: DevDivPlaywrightAzurePipelinesUbuntu2204
+ os: linux
+ sdl:
+ sourceAnalysisPool:
+ name: DevDivPlaywrightAzurePipelinesWindows2022
+ # The image must be windows-based due to restrictions of the SDL tools. See: https://aka.ms/AAo6v8e
+ # In the case of a windows build, this can be the same as the above pool image.
+ os: windows
+ suppression:
+ suppressionFile: $(Build.SourcesDirectory)\.azure-pipelines\guardian\SDL\.gdnsuppress
+ stages:
+ - stage: Stage
+ jobs:
+ - job: Build
+ templateContext:
+ outputs:
+ - output: pipelineArtifact
+ path: $(Build.ArtifactStagingDirectory)/esrp-build
+ artifact: esrp-build
+ steps:
+ - checkout: self
+ persistCredentials: false
+ displayName: "Checkout code"
+
+ - bash: |
+ if [[ ! "$CURRENT_BRANCH" =~ ^v1\..* ]]; then
+ echo "Can only publish from a release tag branch (v1.*)."
+ echo "Unexpected branch name: $CURRENT_BRANCH"
+ exit 1
+ fi
+ env:
+ CURRENT_BRANCH: ${{ variables['Build.SourceBranchName'] }}
+ displayName: "Check the branch is a release branch"
+ # Allow manual runs on any branch to exercise the build without publishing.
+ condition: ne(variables['Build.Reason'], 'Manual')
+
+ - bash: |
+ echo "importing GPG key:"
+ # Pipeline variables do not preserve line ends so we use base64 instead of --armored as a workaround.
+ echo $GPG_PRIVATE_KEY_BASE64 | base64 -d | gpg --batch --import
+ echo "list keys after import:"
+ gpg --list-keys
+ env:
+ GPG_PRIVATE_KEY_BASE64: $(GPG_PRIVATE_KEY_BASE64) # secret variable has to be mapped to an env variable
+ displayName: "Import gpg key"
+
+ - task: UseNode@1
+ inputs:
+ version: '26.x'
+ displayName: "Install Node.js"
+
+ - task: Bash@3
+ displayName: "setup .npmrc"
+ inputs:
+ targetType: "inline"
+ script: |
+ echo "registry=https://devdiv.pkgs.visualstudio.com/DevDiv/_packaging/DevDiv_PublicPackages/npm/registry/" >> .npmrc
+
+ - task: npmAuthenticate@0
+ displayName: "authenticate the private npm registry"
+ inputs:
+ workingFile: .npmrc
+
+ # The script clones microsoft/playwright into .upstream/ at the commit in
+ # scripts/DRIVER_VERSION and builds the driver from it. `npm ci` uses the registry
+ # and the credentials of the .npmrc file above.
+ - bash: ./scripts/build_driver.sh
+ displayName: 'Build the driver'
+
+ # Must run before MavenAuthenticate@0 so the credentials it injects into
+ # ~/.m2/settings.xml are not overwritten by the copy.
+ - bash: |
+ mkdir -p ~/.m2
+ cp .azure-pipelines/settings.xml ~/.m2/settings.xml
+ displayName: 'Copy settings.xml (mirror Maven Central to DevDiv_PublicPackages)'
+
+ - task: MavenAuthenticate@0
+ displayName: 'Authenticate to DevDiv_PublicPackages feed'
+ inputs:
+ artifactsFeeds: DevDiv_PublicPackages
+
+ - bash: mvn -B deploy -D skipTests --no-transfer-progress --activate-profiles release -D gpg.passphrase=$GPG_PASSPHRASE -DaltDeploymentRepository=snapshot-repo::default::file:$(Build.ArtifactStagingDirectory)/esrp-build
+ displayName: 'Build and deploy to a local directory'
+ env:
+ GPG_PASSPHRASE: $(GPG_PASSPHRASE) # secret variable has to be mapped to an env variable
+
+ - job: Publish
+ dependsOn: Build
+ # Only publish from release tags; manual runs stop after Build.
+ condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v1.'))
+ templateContext:
+ type: releaseJob
+ isProduction: true
+ inputs:
+ - input: pipelineArtifact
+ artifactName: esrp-build
+ targetPath: $(Build.ArtifactStagingDirectory)/esrp-build
+ steps:
+ - checkout: none
+ - task: EsrpRelease@11
+ inputs:
+ connectedservicename: 'Playwright-ESRP-PME'
+ usemanagedidentity: true
+ keyvaultname: 'playwright-esrp-pme'
+ signcertname: 'ESRP-Release-Sign'
+ clientid: '13434a40-7de4-4c23-81a3-d843dc81c2c5'
+ intent: 'PackageDistribution'
+ contenttype: 'Maven'
+ # Keeping it commented out as a workaround for:
+ # https://portal.microsofticm.com/imp/v3/incidents/incident/499972482/summary
+ # contentsource: 'folder'
+ folderlocation: '$(Build.ArtifactStagingDirectory)/esrp-build'
+ waitforreleasecompletion: true
+ owners: 'yurys@microsoft.com'
+ approvers: 'yurys@microsoft.com'
+ serviceendpointurl: 'https://api.esrp.microsoft.com'
+ mainpublisher: 'Playwright'
+ domaintenantid: '975f013f-7f24-47e8-a7d3-abc4752bf346'
+ displayName: 'ESRP Release to Maven'
diff --git a/.azure-pipelines/settings.xml b/.azure-pipelines/settings.xml
new file mode 100644
index 000000000..1617d36e9
--- /dev/null
+++ b/.azure-pipelines/settings.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+ DevDiv_PublicPackages
+ https://pkgs.dev.azure.com/devdiv/DevDiv/_packaging/DevDiv_PublicPackages/maven/v1
+ *
+
+
+
diff --git a/.claude/skills/playwright-java-release/SKILL.md b/.claude/skills/playwright-java-release/SKILL.md
new file mode 100644
index 000000000..988f39b19
--- /dev/null
+++ b/.claude/skills/playwright-java-release/SKILL.md
@@ -0,0 +1,81 @@
+---
+name: playwright-java-release
+description: Prepare a Playwright Java release after the rolling PR has merged — cut the release branch, mark the Maven version, add Java-specific changes to the release notes, draft the GitHub release, and tick the Java boxes in the internal checklist.
+---
+
+Use this skill after the roll PR for `1.X` is in `main`. The [[playwright-roll]] skill does the roll.
+
+First, check the driver. We build the driver from the `microsoft/playwright` commit in `scripts/DRIVER_VERSION`, not from a published npm package. For a release, that commit must be on the upstream `release-1.X` branch, and the driver must report `1.X.y`:
+
+```bash
+scripts/build_driver.sh
+git -C .upstream fetch origin release-1.X
+git -C .upstream merge-base --is-ancestor "$(cat scripts/DRIVER_VERSION)" FETCH_HEAD && echo "on release-1.X"
+git -C .upstream show "$(cat scripts/DRIVER_VERSION)":packages/playwright-core/package.json | grep '"version"'
+```
+
+If a check fails, tell the user, and roll with `scripts/roll_driver.sh release-1.X` (the tip of the branch) or `scripts/roll_driver.sh ` (the commit that the user gives).
+
+Throughout this doc, replace `X` with the minor version (e.g. `60` for `1.60.0`) and `` with the fork owner (`gh api user --jq .login`).
+
+The full release checklist lives in the private `microsoft/playwright-internal` repo as the `v1.X checklist` issue. Find its number once:
+
+```bash
+unset GITHUB_TOKEN
+ISSUE=$(gh search issues --repo microsoft/playwright-internal "v1.X checklist" --json number --jq '.[0].number')
+```
+
+Tick each Java box incrementally (one PATCH per item) so the issue reflects accurate state if the flow is interrupted:
+
+```bash
+gh api repos/microsoft/playwright-internal/issues/$ISSUE --jq '.body' > /tmp/body.md
+# edit /tmp/body.md to flip "- [ ]" → "- [x]" on the relevant Java item
+gh api repos/microsoft/playwright-internal/issues/$ISSUE -X PATCH --field body=@/tmp/body.md
+```
+
+## 1. Cut the release branch
+
+Push `release-1.X` from current `upstream/main` (which now contains the merged roll commit):
+
+```bash
+git fetch upstream main
+git push upstream upstream/main:refs/heads/release-1.X
+```
+
+## 2. Release notes
+
+The Java notes in `docs/src/release-notes-java.md` are written upstream together with the Node.js notes, following the `playwright-release-notes` skill (`../playwright/.claude/skills/playwright-release-notes/SKILL.md`). Assume the `## Version 1.X` section is already on `release-1.X`, and only add what's missing: significant changes that only the Java port has, such as a new JUnit fixture or a Java-only API. Leave out minor bug fixes. To find candidates, list this repo's changes since the previous release branch was cut:
+
+```bash
+git log --oneline --no-merges $(git merge-base upstream/release-1. upstream/main)..upstream/main | grep -E '^\w+ (feat|fix)'
+```
+
+Ask the user before adding anything. Send additions upstream as `docs: release notes for v1.X Java`, and cherry-pick them to `release-1.X`.
+
+Write the GitHub release body from the section as step 3 of the upstream skill describes, and save it as `/tmp/v1.X.0-release-notes.md`. Create the draft directly against `release-1.X`. Drafting against `main` and retargeting later is fragile, because every `gh release edit` rotates the `untagged-` ID:
+
+```bash
+gh release create v1.X.0 --repo microsoft/playwright-java --draft \
+ --title "v1.X.0" --notes-file /tmp/v1.X.0-release-notes.md --target release-1.X
+```
+
+## 3. Bump the Maven version on the release branch
+
+Cut `mark-v-1.X.0` off `upstream/release-1.X`, run `set_maven_version.sh`, and PR back to the release branch:
+
+```bash
+git checkout -b mark-v-1.X.0 upstream/release-1.X
+./scripts/set_maven_version.sh 1.X.0
+git add -u
+git commit -m "chore: mark 1.X.0"
+git push -u origin mark-v-1.X.0
+gh pr create --repo microsoft/playwright-java --head :mark-v-1.X.0 --base release-1.X \
+ --title "chore: mark 1.X.0" \
+ --body "Updates Maven version in all modules to \`1.X.0\` for the v1.X release."
+```
+
+`set_maven_version.sh` only invokes `mvn versions:set` on `pom.xml`, `tools/*/pom.xml`, and `examples/pom.xml`, but the root invocation cascades through the reactor, so the expected diff is 11 poms: root + `driver/` + `driver-bundle/` + `playwright/` (from the reactor cascade) + 6 under `tools/` + `examples/`, all flipping `1..0-SNAPSHOT` → `1.X.0`. Any other file in the diff is a red flag.
+
+## 4. Publish
+
+The user publishes the draft release manually once the `mark-v-1.X.0` PR is merged. After publishing, the `v1.X.0` tag triggers the Azure DevOps pipelines that push the artifacts to Maven Central (`.azure-pipelines/publish.yml`) and the Docker images to ACR (`.azure-pipelines/publish-docker.yml`).
diff --git a/.claude/skills/playwright-roll/SKILL.md b/.claude/skills/playwright-roll/SKILL.md
new file mode 100644
index 000000000..000e37a19
--- /dev/null
+++ b/.claude/skills/playwright-roll/SKILL.md
@@ -0,0 +1,207 @@
+---
+name: playwright-roll
+description: Roll Playwright Java to a new microsoft/playwright commit. Moves the commit in scripts/DRIVER_VERSION, builds the driver from source, generates the API, and ports the upstream changes of the client.
+---
+
+# Rolling Playwright
+
+Read `AGENTS.md` and `ROLLING.md` first.
+
+`scripts/DRIVER_VERSION` holds one commit of `microsoft/playwright`. We build the driver from source at that commit. `.upstream/` (gitignored) is a clone of `microsoft/playwright` at that commit. Read the upstream code there. Do not edit, commit or switch branches in `.upstream/`.
+
+A roll moves `scripts/DRIVER_VERSION` to a newer commit and ports the changes between the two commits. A roll does not use the published npm packages or their versions.
+
+## 1. Roll
+
+```bash
+./scripts/roll_driver.sh # the tip of upstream main
+./scripts/roll_driver.sh release-1.X # the tip of an upstream release branch
+./scripts/roll_driver.sh # an exact commit (40 hex digits)
+```
+
+Use the target that the user gives. If the user gives no target, roll `main` to upstream `main`, and roll a `release-1.X` branch of this repository to upstream `release-1.X`.
+
+The script writes the commit to `scripts/DRIVER_VERSION`, rolls Node.js, builds the driver from `.upstream/`, generates the API and updates the README. Then get the two commits:
+
+```bash
+old=$(git show HEAD:scripts/DRIVER_VERSION)
+new=$(cat scripts/DRIVER_VERSION)
+```
+
+## 2. Find the changes to port
+
+List the upstream commits between the two commits that changed a path the Java client depends on:
+
+- `docs/src/api/` — the input of the API generator. A new or removed method or option, or a changed `langs:` filter, comes from here.
+- `packages/playwright-core/src/client/` — the JS client. The Java client is a port of it.
+- `packages/isomorphic/` — selector engines, locator generation and parsing, and the aria snapshot code. The client and the server share this code. A change here can change client helpers such as `getByRoleSelector`.
+- `packages/playwright/src/matchers/matchers.ts` — the assertion methods. A change here is usually a new option of `LocatorAssertions` or `PageAssertions`.
+- `packages/protocol/spec/` — the wire protocol, one `*.yml` file for each area. A new method or event, a renamed parameter or a changed result changes the messages that the Java `*Impl` classes send and receive.
+
+```bash
+git -C .upstream log "$old..$new" --oneline --reverse -- \
+ 'docs/src/api/' \
+ 'packages/playwright-core/src/client/' \
+ 'packages/isomorphic/' \
+ 'packages/playwright/src/matchers/matchers.ts' \
+ 'packages/protocol/spec/'
+```
+
+The list starts with the oldest commit. Do these steps for each commit:
+
+1. Read the commit: `git -C .upstream show `.
+2. If the change is internal to JS (bundling, dispatchers, electron, mcp, dashboard, trace viewer, test runner), skip it.
+3. If the commit changes `docs/src/api/` or types, read the `langs:` annotations. A feature with `langs: js` or `langs: js, python` does not apply to Java.
+4. If the commit adds or changes a public method or option that applies to Java, port it. `roll_driver.sh` already generated the new types and options in the Java interfaces. Usually only the `*Impl` code is missing.
+5. Make sure that a later commit did not revert the change. Look at the code at `$new` before you port.
+6. Keep notes in a file (for example `/tmp/roll-notes.md`). For each upstream PR, write one line: ported, skipped or already supported, with the reason. The PR description comes from this file.
+
+## 3. The roll PR
+
+The PR contains:
+
+- the new commit in `scripts/DRIVER_VERSION`, and the new `scripts/NODE_VERSION` if Node.js changed;
+- the generated interfaces from `roll_driver.sh`;
+- the `*Impl` code for each ported feature, the same as the upstream JS client (`.upstream/packages/playwright-core/src/client`);
+- changes to the generator (import lists, special cases) if there are new types;
+- one small test for each new public API: a listener for a new event, a call for a new method, a regression test for a changed return type.
+
+Title: `chore(driver): roll to ()`. `` is the version that the driver reports. Read it from the source, not from npm:
+
+```bash
+node -p "require('./.upstream/packages/playwright-core/package.json').version" # for example 1.67.0-next
+```
+
+Description: list each upstream PR that you ported, each PR that you skipped (with the reason), and each PR that Java already supported.
+
+## Mimicking the JavaScript implementation
+
+The Java client is a port of the JS client in `.upstream/packages/playwright-core/src/client/`. When implementing a new or changed method, always read the corresponding JS file first and mirror its logic:
+
+```
+.upstream/packages/playwright-core/src/client/browserContext.ts
+.upstream/packages/playwright-core/src/client/page.ts
+.upstream/packages/playwright-core/src/client/tracing.ts
+.upstream/packages/playwright-core/src/client/video.ts
+.upstream/packages/playwright-core/src/client/locator.ts
+.upstream/packages/playwright-core/src/client/network.ts
+...
+```
+
+Key translation rules:
+
+**Protocol calls** — `await this._channel.methodName(params)` → `sendMessage("methodName", params, NO_TIMEOUT)`
+
+**Extracting a returned channel object from a result** — JS uses `SomeClass.from(result.foo)` which resolves the JS-side object for a channel reference. In Java, the object was already created when the server sent `__create__`, so extract it from the connection: `connection.getExistingObject(result.getAsJsonObject("foo").get("guid").getAsString())`
+
+**Async/await** — all `await` calls become synchronous `sendMessage(...)` calls since the Java client is synchronous.
+
+**`undefined` / optional params** — JS `options?.foo` checks translate to `if (options != null && options.foo != null)` null checks before adding to the params `JsonObject`.
+
+**`_channel` fields** — the JS `this._channel.foo` maps to calling `sendMessage("foo", ...)` on `this` in the Impl class.
+
+**Channel object references in params** — when a JS call passes a channel object as a param (e.g. `{ frame: frame._channel }`), in Java pass the guid: `params.addProperty("frame", ((FrameImpl) frame).guid)`.
+
+**Module-level state** — JS sometimes keeps state at module level (e.g. the call id counter in `createCallIdGenerator()`). Don't translate it into a `static` field with atomics; keep it per `Connection` (or per object) as a plain field. Each connection is used from one thread, so the port should not change the threading model.
+
+## Fixing generator and compilation errors
+
+After running `./scripts/roll_driver.sh`, the build often fails because the generated Java interfaces reference new types or methods that the generator doesn't know how to handle yet, and the `*Impl` classes don't implement new interface methods.
+
+### API generator fixes (scripts/generate_java_api.mts)
+
+The generator has hardcoded lists that control which imports are added to each generated file. When new classes appear in the API, add them to the relevant lists in `INTERFACE_IMPORTS`:
+- `options.*` import list — add new classes that use types from the options package
+- `java.util.*` import list — add new classes that use `List`, `Map`, etc.
+- `java.util.function.Consumer` list — add new classes with `Consumer`-typed event handlers
+
+Type mapping: when JS-only types (like `Disposable`) are used as return types in Java-compatible methods, add a mapping in `BUILTIN_TYPES`. For example, `Disposable` → `AutoCloseable`.
+
+Event handler generation: events with `void` type generate invalid `Consumer`. Handle this case in `Event.writeListenerMethods` by emitting `Runnable` instead.
+
+Type names: give every new object type an explicit alias upstream. When a roll brings in a new object type (an option or return value written as `<[Object]>` in `docs/src/api/`), it should usually have its own `* alias: ` line. Without one, each language's generator makes up a name, and the Java one can be vague (e.g. `Style`) or differ between Java and .NET.
+- Prefer a plain `alias:` so every language gets the same name. Use `alias-java:` / `alias-csharp:` only when a language really needs a different name.
+- Add the aliases in a small upstream docs PR (e.g. microsoft/playwright#43164, `Style` → `ScreencastActionStyle`). Don't special-case names in the generator.
+- After the upstream change lands, roll to a driver that includes it. Don't hand-edit the generated files.
+
+After editing the generator, re-run it. Node.js runs the TypeScript file as is:
+```
+node scripts/generate_java_api.mts .upstream
+```
+
+### Impl class fixes (playwright/src/main/java/com/microsoft/playwright/impl/)
+
+After regenerating, compile `playwright/` to find what's missing:
+```
+mvn -f playwright/pom.xml compile 2>&1 | grep "ERROR"
+```
+
+Common patterns:
+
+**Return type changed (e.g. `void` → `AutoCloseable`):** Update the method signature in the Impl class and return an appropriate `AutoCloseable`. Check the JS client to see what kind of disposable is used:
+- If JS returns `DisposableObject.from(result.disposable)` — the server created a disposable channel object. Extract its guid from the protocol result and return `connection.getExistingObject(guid)` (a `DisposableObject`).
+- If JS returns `new DisposableStub(() => this.someCleanup())` — it's a local callback. Return `new DisposableStub(this::someCleanup)` in Java.
+- Examples: `addInitScript`/`exposeBinding`/`exposeFunction` → `DisposableObject`; `route(...)` → `DisposableStub(() -> unroute(...))`; `Tracing.group` → `DisposableStub(this::groupEnd)`; `Video.start` → `DisposableStub(this::stop)`.
+
+**New method missing:** Add a stub implementation. Common patterns:
+- Simple protocol message: `sendMessage("methodName", params, NO_TIMEOUT)`
+- New property accessor (e.g. from initializer): `return initializer.get("fieldName").getAsString()`
+- Delegation to mainFrame (for Page methods): `return mainFrame.locator(":root").method(...)`
+
+**New interface entirely (e.g. `Debugger`):** Create a new `*Impl` class extending `ChannelOwner`, implement the interface, and register the type in `Connection.java`'s switch statement. Initialize the field from the parent's initializer in the parent's constructor (e.g. `connection.getExistingObject(initializer.getAsJsonObject("debugger").get("guid").getAsString())`).
+
+**Field visibility:** If a field needs to be accessed from a sibling Impl class (e.g. setting `existingResponse` on `RequestImpl` from `BrowserContextImpl`), change it from `private` to package-private.
+
+**`ListenerCollection` only supports `Consumer`, not `Runnable`.** For void events that use `Runnable` handlers, maintain a plain `List` instead.
+
+**Protocol changes that remove events** — when a method's response now returns an object directly instead of via a subsequent event, update the Impl to capture it from the `sendMessage` result and remove the old event handler. Example: `videoStart` used to fire a `"video"` page event to deliver the artifact; it now returns the artifact directly in the response. Check git history of the upstream JS client when tests hang unexpectedly.
+
+**Protocol parameter renames** — protocol parameter names can change between versions (e.g. `wsEndpoint` → `endpoint` in `BrowserType.connect`). When a test fails with `expected string, got undefined` or similar validation errors from the driver, check `packages/protocol/spec/*.yml` for the current parameter names and update the corresponding `params.addProperty(...)` call in the Impl class. Also check the JS client (`src/client/`) to see how it builds the params object.
+
+## Rebuilding the driver modules after a roll
+
+`./scripts/roll_driver.sh` does the full roll. It moves `scripts/DRIVER_VERSION` to the new commit. It builds the driver from `.upstream/` into `driver/src/main/resources/driver/package/` and `driver-bundle/src/main/resources/driver//`. It generates the Java interfaces from the upstream docs, and it updates the README. If all steps pass, the next `mvn` command uses the new driver.
+
+If a step fails, the script stops before Maven installs the new driver. The most frequent cause is the API generator, which fails on a new type (see *Fixing generator and compilation errors*). After that, the test JVM loads the **old** driver from `target/classes` or from the installed jar, although the source resources already hold the new driver.
+
+To correct this, install the two driver modules one time before you run the tests again:
+```
+mvn -f driver/pom.xml install -DskipTests
+mvn -f driver-bundle/pom.xml install -DskipTests
+```
+
+If `scripts/generate_api.sh` prints `.upstream/ is not at ...`, run `scripts/build_driver.sh`.
+
+## Porting and verifying tests
+
+**Before porting an upstream test file, check the API exists in Java.** The upstream repo may have test files for brand-new APIs that haven't been added to the Java interface yet (e.g., `screencast.spec.ts` tests `page.screencast` which may not be in the generated `Page.java`). Check `git diff main --name-only` to see what interfaces were added this roll, and verify the method exists in the generated Java interface before porting.
+
+**Java test file names don't always match upstream spec names.** `TestScreencast.java` tests `recordVideo` video-file recording (which corresponds to `video.spec.ts`), not the newer `page.screencast` streaming API (`screencast.spec.ts`). When comparing coverage, check test *content*, not just file names.
+
+**Remove tests for behavior that was removed upstream.** When the JS client drops a client-side error check (e.g., "Page is not yet closed before saveAs", "Page did not produce any video frames"), delete the corresponding Java tests rather than trying to keep them passing. Check the upstream `tests/library/` spec to confirm the behavior is gone.
+
+**Run the full suite to catch regressions, re-run flaky failures in isolation.** Some tests (e.g., `TestClientCertificates#shouldKeepSupportingHttp`) time out only under heavy parallel load. Run the failing test alone to confirm it's flaky before investigating further.
+
+**Don't change the driver environment per test.** The driver is a JVM-wide singleton, so `Playwright.CreateOptions.env` (e.g. `PWTEST_UNDER_TEST`) only applies to the first `Playwright.create()` in the JVM. Forcing a new driver instance from a test breaks unrelated tests (`ClosedFileSystemException`). Test through what the public API exposes instead — e.g. screencast action decorations render in a closed shadow root, so the style test checks screencast frames for the decoration's pixels rather than querying the DOM.
+
+## Reviewing the diff before the PR
+
+Before opening the PR (and before pushing follow-ups), read `git diff upstream/main` end to end:
+- **Removed generated methods** — `git diff upstream/main -- playwright/src/main/java/com/microsoft/playwright/*.java | grep '^-.*;'`. A return type change like `void` → `AutoCloseable` still compiles for callers but breaks code compiled against the previous jar. Call these out in the PR.
+- **Behavior beyond upstream** — client-side checks or fixes not in the JS client (e.g. an option that was never sent). Keep them only if deliberate, and list them in the PR.
+- **Stray files** — local config such as `.claude/settings.json`, or unrelated edits like `examples/pom.xml`, must not be committed.
+
+## Diagnosing hanging tests
+
+When `mvn test` hangs and surefire eventually times the JVM out, it writes thread dumps to `playwright/target/surefire-reports/-jvmRun*.dump`. To find the stuck test:
+
+```
+grep "com.microsoft.playwright.Test" playwright/target/surefire-reports/*-jvmRun1.dump | sort -u
+```
+
+Each line is a stack frame inside a test method — typically you'll see one or two test methods blocked on a `Future.get()`, `waitForCondition`, or similar. That's the hanging test.
+
+When you've identified a hanging test:
+1. Run it in isolation: `mvn -f playwright/pom.xml test -Dtest='TestClass#testMethod'`. If it passes alone, it's a parallel-load flake — note it but move on.
+2. If it still hangs in isolation, look for a recent fix in the upstream repo for the *same* test name. Use `git -C .upstream log --oneline -- tests/library/.spec.ts`. Upstream fixes for client-side hangs are often small and portable (e.g. `about:blank` → `server.EMPTY_PAGE` from microsoft/playwright#39840 fixed `route-web-socket.spec.ts` arraybuffer hangs — apparently some browser changed the WebSocket origin policy on `about:blank`).
+3. When porting an upstream fix, mirror the helper signature change rather than hard-coding workarounds. E.g. if upstream added a `server` parameter to `setupWS`, do the same in Java by injecting `Server server` via the JUnit fixture (`@FixtureTest` already wires up `ServerLifecycle`, so adding `Server server` to the test method signature is enough — no class-level boilerplate). Watch for local-variable shadowing when you add a `Server server` parameter to a method that already has a `WebSocketRoute server` local; rename the local.
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
new file mode 100644
index 000000000..0163c60ab
--- /dev/null
+++ b/.devcontainer/devcontainer.json
@@ -0,0 +1,28 @@
+// For format details, see https://aka.ms/devcontainer.json. For config options, see the
+// README at: https://github.com/devcontainers/templates/tree/main/src/java
+{
+ "name": "Java",
+ // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
+ "image": "mcr.microsoft.com/devcontainers/java:1-21-bookworm",
+
+ "features": {
+ "ghcr.io/devcontainers/features/java:1": {
+ "version": "none",
+ "installGradle": "false",
+ "installMaven": "true"
+ },
+ "ghcr.io/devcontainers/features/docker-outside-of-docker:1": {}
+ }
+
+ // Use 'forwardPorts' to make a list of ports inside the container available locally.
+ // "forwardPorts": [],
+
+ // Use 'postCreateCommand' to run commands after the container is created.
+ // "postCreateCommand": "java -version",
+
+ // Configure tool-specific properties.
+ // "customizations": {},
+
+ // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
+ // "remoteUser": "root"
+}
diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md
deleted file mode 100644
index 02838603a..000000000
--- a/.github/ISSUE_TEMPLATE/bug.md
+++ /dev/null
@@ -1,41 +0,0 @@
----
-name: Bug Report
-about: Something doesn't work like it should? Tell us!
-title: "[BUG]"
-labels: ''
-assignees: ''
-
----
-
-**Context:**
-- Playwright Version: [what Playwright version do you use?]
-- Operating System: [e.g. Windows, Linux or Mac]
-- Browser: [e.g. All, Chromium, Firefox, WebKit]
-- Extra: [any specific details about your environment]
-
-
-
-
-**Code Snippet**
-
-Help us help you! Put down a short code snippet that illustrates your bug and
-that we can run and debug locally. For example:
-
-```java
-import com.microsoft.playwright.*;
-
-public class ExampleReproducible {
- public static void main(String[] args) {
- try (Playwright playwright = Playwright.create()) {
- Browser browser = playwright.chromium().launch();
- BrowserContext context = browser.newContext();
- Page page = context.newPage();
- // ...
- }
- }
-}
-```
-
-**Describe the bug**
-
-Add any other details about the problem here.
diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml
new file mode 100644
index 000000000..7fb77f29f
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,95 @@
+name: Bug Report 🪲
+description: Create a bug report to help us improve
+title: '[Bug]: '
+body:
+ - type: markdown
+ attributes:
+ value: |
+ # Please follow these steps first:
+ - type: markdown
+ attributes:
+ value: |
+ ## Troubleshoot
+ If Playwright is not behaving the way you expect, we'd ask you to look at the [documentation](https://playwright.dev/java/docs/intro) and search the issue tracker for evidence supporting your expectation.
+ Please make reasonable efforts to troubleshoot and rule out issues with your code, the configuration, or any 3rd party libraries you might be using.
+ Playwright offers [several debugging tools](https://playwright.dev/java/docs/debug) that you can use to troubleshoot your issues.
+ - type: markdown
+ attributes:
+ value: |
+ ## Ask for help through appropriate channels
+ If you feel unsure about the cause of the problem, consider asking for help on for example [StackOverflow](https://stackoverflow.com/questions/ask) or our [Discord channel](https://aka.ms/playwright/discord) before posting a bug report. The issue tracker is not a help forum.
+ - type: markdown
+ attributes:
+ value: |
+ ## Make a minimal reproduction
+ To file the report, you will need a GitHub repository with a minimal (but complete) example and simple/clear steps on how to reproduce the bug.
+ The simpler you can make it, the more likely we are to successfully verify and fix the bug.
+ - type: markdown
+ attributes:
+ value: |
+ > [!IMPORTANT]
+ > Bug reports without a minimal reproduction will be rejected.
+
+ ---
+ - type: input
+ id: version
+ attributes:
+ label: Version
+ description: |
+ The version of Playwright you are using.
+ Is it the [latest](https://github.com/microsoft/playwright-java/releases)? Test and see if the bug has already been fixed.
+ placeholder: ex. 1.41.1
+ validations:
+ required: true
+ - type: textarea
+ id: reproduction
+ attributes:
+ label: Steps to reproduce
+ description: Please link to a repository with a minimal reproduction and describe accurately how we can reproduce/verify the bug.
+ placeholder: |
+ Example steps (replace with your own):
+ 1. Clone my repo at https://github.com//example
+ 2. mvn test
+ 3. You should see the error come up
+ validations:
+ required: true
+ - type: textarea
+ id: expected
+ attributes:
+ label: Expected behavior
+ description: A description of what you expect to happen.
+ placeholder: I expect to see X or Y
+ validations:
+ required: true
+ - type: textarea
+ id: what-happened
+ attributes:
+ label: Actual behavior
+ description: |
+ A clear and concise description of the unexpected behavior.
+ Please include any relevant output here, especially any error messages.
+ placeholder: A bug happened!
+ validations:
+ required: true
+ - type: textarea
+ id: context
+ attributes:
+ label: Additional context
+ description: Anything else that might be relevant
+ validations:
+ required: false
+ - type: textarea
+ id: envinfo
+ attributes:
+ label: Environment
+ description: |
+ Please provide information about the environment you are running in.
+ placeholder: |
+ - Operating System: [Ubuntu 22.04]
+ - CPU: [arm64]
+ - Browser: [All, Chromium, Firefox, WebKit]
+ - Java Version: [20]
+ - Maven Version: [3.8.6]
+ - Other info:
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index 918439bd8..13b5b0a96 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -1,4 +1,5 @@
+blank_issues_enabled: false
contact_links:
- - name: Join our Slack community
- url: https://aka.ms/playwright-slack
- about: Ask questions and discuss with other community members
\ No newline at end of file
+ - name: Join our Discord Server
+ url: https://aka.ms/playwright/discord
+ about: Ask questions and discuss with other community members
diff --git a/.github/ISSUE_TEMPLATE/documentation.yml b/.github/ISSUE_TEMPLATE/documentation.yml
new file mode 100644
index 000000000..276d3347b
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/documentation.yml
@@ -0,0 +1,29 @@
+name: Documentation 📖
+description: Submit a request to add or update documentation
+title: '[Docs]: '
+labels: ['Documentation :book:']
+body:
+ - type: markdown
+ attributes:
+ value: |
+ ### Thank you for helping us improve our documentation!
+ Please be sure you are looking at [the Next version of the documentation](https://playwright.dev/java/docs/next/intro) before opening an issue here.
+ - type: textarea
+ id: links
+ attributes:
+ label: Page(s)
+ description: |
+ Links to one or more documentation pages that should be modified.
+ If you are reporting an issue with a specific section of a page, try to link directly to the nearest anchor.
+ If you are suggesting that a new page be created, link to the parent of the proposed page.
+ validations:
+ required: true
+ - type: textarea
+ id: description
+ attributes:
+ label: Description
+ description: |
+ Describe the change you are requesting.
+ If the issue pertains to a single function or matcher, be sure to specify the entire call signature.
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml
new file mode 100644
index 000000000..efec3315c
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature.yml
@@ -0,0 +1,30 @@
+name: Feature Request 🚀
+description: Submit a proposal for a new feature
+title: '[Feature]: '
+body:
+ - type: markdown
+ attributes:
+ value: |
+ ### Thank you for taking the time to suggest a new feature!
+ - type: textarea
+ id: description
+ attributes:
+ label: '🚀 Feature Request'
+ description: A clear and concise description of what the feature is.
+ validations:
+ required: true
+ - type: textarea
+ id: example
+ attributes:
+ label: Example
+ description: Describe how this feature would be used.
+ validations:
+ required: false
+ - type: textarea
+ id: motivation
+ attributes:
+ label: Motivation
+ description: |
+ Outline your motivation for the proposal. How will it make Playwright better?
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
deleted file mode 100644
index 37ec8a7d2..000000000
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ /dev/null
@@ -1,11 +0,0 @@
----
-name: Feature request
-about: Request new features to be added
-title: "[Feature]"
-labels: ''
-assignees: ''
-
----
-
-Let us know what functionality you'd like to see in Playwright and what your use case is.
-Do you think others might benefit from this as well?
diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md
deleted file mode 100644
index 55abfc3ec..000000000
--- a/.github/ISSUE_TEMPLATE/question.md
+++ /dev/null
@@ -1,10 +0,0 @@
----
-name: I have a question
-about: Feel free to ask us your questions!
-title: "[Question]"
-labels: ''
-assignees: ''
-
----
-
-
diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml
new file mode 100644
index 000000000..0b013d189
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/question.yml
@@ -0,0 +1,27 @@
+name: 'Questions / Help 💬'
+description: If you have questions, please check StackOverflow or Discord
+title: '[Please read the message below]'
+labels: [':speech_balloon: Question']
+body:
+ - type: markdown
+ attributes:
+ value: |
+ ## Questions and Help 💬
+
+ This issue tracker is reserved for bug reports and feature requests.
+
+ For anything else, such as questions or getting help, please see:
+
+ - [The Playwright documentation](https://playwright.dev/java)
+ - [Our Discord server](https://aka.ms/playwright/discord)
+ - type: checkboxes
+ id: no-post
+ attributes:
+ label: |
+ Please do not submit this issue.
+ description: |
+ > [!IMPORTANT]
+ > This issue will be closed.
+ options:
+ - label: I understand
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/regression.md b/.github/ISSUE_TEMPLATE/regression.md
deleted file mode 100644
index 1da4c0b32..000000000
--- a/.github/ISSUE_TEMPLATE/regression.md
+++ /dev/null
@@ -1,38 +0,0 @@
----
-name: Report regression
-about: Functionality that used to work and does not any more
-title: "[REGRESSION]: "
-labels: ''
-assignees: ''
-
----
-
-**Context:**
-- GOOD Playwright Version: [what Playwright version worked nicely?]
-- BAD Playwright Version: [what Playwright version doesn't work any more?]
-- Operating System: [e.g. Windows, Linux or Mac]
-- Extra: [any specific details about your environment]
-
-**Code Snippet**
-
-Help us help you! Put down a short code snippet that illustrates your bug and
-that we can run and debug locally. For example:
-
-```java
-import com.microsoft.playwright.*;
-
-public class ExampleReproducible {
- public static void main(String[] args) {
- try (Playwright playwright = Playwright.create()) {
- Browser browser = playwright.chromium().launch();
- BrowserContext context = browser.newContext();
- Page page = context.newPage();
- // ...
- }
- }
-}
-```
-
-**Describe the bug**
-
-Add any other details about the problem here.
diff --git a/.github/ISSUE_TEMPLATE/regression.yml b/.github/ISSUE_TEMPLATE/regression.yml
new file mode 100644
index 000000000..42de755b4
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/regression.yml
@@ -0,0 +1,90 @@
+name: Report regression
+description: Functionality that used to work and does not any more
+title: "[Regression]: "
+body:
+ - type: markdown
+ attributes:
+ value: |
+ # Please follow these steps first:
+ - type: markdown
+ attributes:
+ value: |
+ ## Make a minimal reproduction
+ To file the report, you will need a GitHub repository with a minimal (but complete) example and simple/clear steps on how to reproduce the regression.
+ The simpler you can make it, the more likely we are to successfully verify and fix the regression.
+ - type: markdown
+ attributes:
+ value: |
+ > [!IMPORTANT]
+ > Regression reports without a minimal reproduction will be rejected.
+
+ ---
+ - type: input
+ id: goodVersion
+ attributes:
+ label: Last Good Version
+ description: |
+ Last version of Playwright where the feature was working.
+ placeholder: ex. 1.40.1
+ validations:
+ required: true
+ - type: input
+ id: badVersion
+ attributes:
+ label: First Bad Version
+ description: |
+ First version of Playwright where the feature was broken.
+ Is it the [latest](https://github.com/microsoft/playwright-java/releases)? Test and see if the regression has already been fixed.
+ placeholder: ex. 1.41.1
+ validations:
+ required: true
+ - type: textarea
+ id: reproduction
+ attributes:
+ label: Steps to reproduce
+ description: Please link to a repository with a minimal reproduction and describe accurately how we can reproduce/verify the bug.
+ placeholder: |
+ Example steps (replace with your own):
+ 1. Clone my repo at https://github.com//example
+ 2. mvn test
+ 3. You should see the error come up
+ validations:
+ required: true
+ - type: textarea
+ id: expected
+ attributes:
+ label: Expected behavior
+ description: A description of what you expect to happen.
+ placeholder: I expect to see X or Y
+ validations:
+ required: true
+ - type: textarea
+ id: what-happened
+ attributes:
+ label: Actual behavior
+ description: A clear and concise description of the unexpected behavior.
+ placeholder: A bug happened!
+ validations:
+ required: true
+ - type: textarea
+ id: context
+ attributes:
+ label: Additional context
+ description: Anything else that might be relevant
+ validations:
+ required: false
+ - type: textarea
+ id: envinfo
+ attributes:
+ label: Environment
+ description: |
+ Please provide information about the environment you are running in.
+ placeholder: |
+ - Operating System: [Ubuntu 22.04]
+ - CPU: [arm64]
+ - Browser: [All, Chromium, Firefox, WebKit]
+ - Java Version: [20]
+ - Maven Version: [3.8.6]
+ - Other info:
+ validations:
+ required: true
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 000000000..fcee265fe
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,31 @@
+version: 2
+updates:
+ - package-ecosystem: "maven"
+ directory: "/" # Location of the pom.xml file
+ schedule:
+ 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
+ cooldown:
+ default-days: 7
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "monthly"
+ groups:
+ actions:
+ patterns:
+ - "*"
+ cooldown:
+ default-days: 7
diff --git a/.github/workflows/agent-review.yml b/.github/workflows/agent-review.yml
new file mode 100644
index 000000000..253f96729
--- /dev/null
+++ b/.github/workflows/agent-review.yml
@@ -0,0 +1,36 @@
+# Hands the pull request to the Playwright bot when a maintainer applies agent-review. Nothing
+# else of the bot lives in this repo. Apply the label again to start another run.
+name: "Agent: review"
+
+on:
+ # Runs from the default branch, also when the PR has a merge conflict. It never checks out the
+ # PR. The job skips a PR from a fork: the bot cannot push to a fork.
+ pull_request_target:
+ types: [labeled]
+
+permissions: {}
+
+jobs:
+ pr:
+ name: Hand the PR to the bot
+ if: >-
+ github.repository_owner == 'microsoft' && github.event.label.name == 'agent-review'
+ && github.event.pull_request.head.repo.full_name == github.repository
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
+ id: app-token
+ with:
+ client-id: ${{ vars.PLAYWRIGHT_APP_CLIENT_ID }}
+ private-key: ${{ secrets.PLAYWRIGHT_PRIVATE_KEY }}
+ owner: microsoft
+ repositories: devops.playwright.dev
+ permission-actions: write
+ - name: Start the bot
+ env:
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ NUMBER: ${{ github.event.pull_request.number }}
+ run: >-
+ gh workflow run pr.yml --repo microsoft/devops.playwright.dev --ref main
+ -f repo="$GITHUB_REPOSITORY" -f pr="$NUMBER"
diff --git a/.github/workflows/agent-task.yml b/.github/workflows/agent-task.yml
new file mode 100644
index 000000000..e9c57ce38
--- /dev/null
+++ b/.github/workflows/agent-task.yml
@@ -0,0 +1,36 @@
+# Starts the Playwright bot with the task that you type. The bot does it with the skills of this
+# repo, and opens the pull request as the app. Start it from the Actions tab.
+name: "Agent: task"
+
+on:
+ workflow_dispatch:
+ inputs:
+ task:
+ description: What the bot should do
+ type: string
+ required: true
+
+permissions: {}
+
+jobs:
+ start:
+ name: Hand the task to the bot
+ if: github.repository == 'microsoft/playwright-java'
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
+ id: app-token
+ with:
+ client-id: ${{ vars.PLAYWRIGHT_APP_CLIENT_ID }}
+ private-key: ${{ secrets.PLAYWRIGHT_PRIVATE_KEY }}
+ owner: microsoft
+ repositories: devops.playwright.dev
+ permission-actions: write
+ - name: Start the bot
+ env:
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ TASK: ${{ inputs.task }}
+ run: >-
+ gh workflow run task.yml --repo microsoft/devops.playwright.dev --ref main
+ -f repo="$GITHUB_REPOSITORY" -f task="$TASK"
diff --git a/.github/workflows/agent-triage.yml b/.github/workflows/agent-triage.yml
new file mode 100644
index 000000000..fb555215b
--- /dev/null
+++ b/.github/workflows/agent-triage.yml
@@ -0,0 +1,36 @@
+# Hands the issue to the Playwright bot when a maintainer applies agent-triage or agent-implement.
+# Nothing else of the bot lives in this repo. Apply the label again to start another run.
+name: "Agent: triage"
+
+on:
+ issues:
+ types: [labeled]
+
+permissions: {}
+
+jobs:
+ issue:
+ name: Hand the issue to the bot
+ if: >-
+ github.repository_owner == 'microsoft' && (
+ github.event.label.name == 'agent-triage' ||
+ github.event.label.name == 'agent-implement')
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
+ id: app-token
+ with:
+ client-id: ${{ vars.PLAYWRIGHT_APP_CLIENT_ID }}
+ private-key: ${{ secrets.PLAYWRIGHT_PRIVATE_KEY }}
+ owner: microsoft
+ repositories: devops.playwright.dev
+ permission-actions: write
+ - name: Start the bot
+ env:
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ NUMBER: ${{ github.event.issue.number }}
+ LABEL: ${{ github.event.label.name }}
+ run: >-
+ gh workflow run issue.yml --repo microsoft/devops.playwright.dev --ref main
+ -f repo="$GITHUB_REPOSITORY" -f issue="$NUMBER" -f label="$LABEL"
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
deleted file mode 100644
index b6ac1f720..000000000
--- a/.github/workflows/publish.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-name: Publish
-on:
- release:
- types: [published]
- push:
- branches:
- - main
-jobs:
- build:
- timeout-minutes: 30
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - uses: microsoft/playwright-github-action@v1.5.0
- - name: Set up JDK 1.8
- uses: actions/setup-java@v1
- with:
- java-version: 1.8
- server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml
- server-username: MAVEN_USERNAME # env variable for username in deploy
- server-password: MAVEN_PASSWORD # env variable for token in deploy
- gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
- gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
- - name: Download drivers
- shell: bash
- run: scripts/download_driver_for_all_platforms.sh
- - name: Publish to Maven Central
- run: mvn deploy --batch-mode -D skipTests --activate-profiles release --no-transfer-progress
- env:
- MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }}
- MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }}
- MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
diff --git a/.github/workflows/publish_canary_docker.yml b/.github/workflows/publish_canary_docker.yml
deleted file mode 100644
index 963daae88..000000000
--- a/.github/workflows/publish_canary_docker.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-name: "devrelease:docker"
-
-on:
- push:
- branches:
- - main
-jobs:
- publish-canary-docker:
- name: "publish to DockerHub"
- runs-on: ubuntu-20.04
- if: github.repository == 'microsoft/playwright-java'
- steps:
- - uses: actions/checkout@v2
- - uses: azure/docker-login@v1
- with:
- login-server: playwright.azurecr.io
- username: playwright
- password: ${{ secrets.DOCKER_PASSWORD }}
- - uses: actions/checkout@v2
- - name: Set up Docker QEMU for arm64 docker builds
- uses: docker/setup-qemu-action@v1
- with:
- platforms: arm64
- - name: publish docker canary
- run: ./utils/docker/publish_docker.sh canary
diff --git a/.github/workflows/publish_docker_release.yml b/.github/workflows/publish_docker_release.yml
deleted file mode 100644
index 357ad573c..000000000
--- a/.github/workflows/publish_docker_release.yml
+++ /dev/null
@@ -1,33 +0,0 @@
-name: Publish Release Docker
-on:
- release:
- types: [published]
- workflow_dispatch:
- inputs:
- is_release:
- required: true
- type: boolean
- description: "Is this a release image?"
- branches:
- - release-*
-jobs:
- publish-canary-docker:
- name: publish to DockerHub
- runs-on: ubuntu-20.04
- if: github.repository == 'microsoft/playwright-java'
- steps:
- - uses: actions/checkout@v2
- - uses: azure/docker-login@v1
- with:
- login-server: playwright.azurecr.io
- username: playwright
- password: ${{ secrets.DOCKER_PASSWORD }}
- - name: Set up Docker QEMU for arm64 docker builds
- uses: docker/setup-qemu-action@v1
- with:
- platforms: arm64
- - uses: actions/checkout@v2
- - 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')
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 69a1daf75..e0ded9c8a 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -8,34 +8,45 @@ on:
branches:
- main
- release-*
+env:
+ PW_MAX_RETRIES: 3
jobs:
dev:
- timeout-minutes: 30
+ timeout-minutes: 90
strategy:
fail-fast: false
matrix:
- os: [ubuntu-latest, windows-latest, macos-latest]
+ os: [playwright-x64-ubuntu24-64-core, playwright-x64-server2025-64-core, macos-26-xlarge]
browser: [chromium, firefox, webkit]
runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
steps:
- - uses: actions/checkout@v2
- - uses: microsoft/playwright-github-action@v1
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - uses: microsoft/playwright/.github/actions/ci-env@d1518e3e3fca90352c4390814943cced496fd7e4 # main
- name: Set up JDK 1.8
- uses: actions/setup-java@v2
+ uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: zulu
java-version: 8
- - name: Download drivers
+ - name: Set up Node.js
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: 24
+ - name: Build the driver
shell: bash
- run: scripts/download_driver_for_all_platforms.sh
+ run: scripts/build_driver.sh
- name: Build & Install
run: mvn -B install -D skipTests --no-transfer-progress
+ - name: Install browsers
+ run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
- name: Run tests
- run: mvn test --no-transfer-progress --fail-at-end
+ run: $CI_ENV_EXEC mvn test --no-transfer-progress --fail-at-end ${{ runner.os == 'Windows' && '-D junit.parallel.factor=0.25' || '' }} -D org.slf4j.simpleLogger.showDateTime=true -D org.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss
env:
BROWSER: ${{ matrix.browser }}
- name: Run tracing tests w/ sources
- run: mvn test --no-transfer-progress --fail-at-end -D test=*TestTracing*
+ run: $CI_ENV_EXEC mvn test --no-transfer-progress --fail-at-end --projects=playwright -D test=*TestTracing* -D org.slf4j.simpleLogger.showDateTime=true -D org.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss
env:
BROWSER: ${{ matrix.browser }}
PLAYWRIGHT_JAVA_SRC: src/test/java
@@ -49,63 +60,79 @@ jobs:
java -jar target/test-spring-boot*.jar
stable:
- timeout-minutes: 30
+ timeout-minutes: 90
strategy:
fail-fast: false
matrix:
- os: [ubuntu-latest, windows-latest, macos-latest]
- browser-channel: [chrome]
include:
- - os: windows-latest
- browser-channel: msedge
- - os: macos-latest
+ - os: playwright-x64-ubuntu24-64-core
+ browser-channel: chrome
+ - os: playwright-x64-server2025-64-core
browser-channel: msedge
runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
steps:
- - uses: actions/checkout@v2
- - uses: microsoft/playwright-github-action@v1
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - uses: microsoft/playwright/.github/actions/ci-env@d1518e3e3fca90352c4390814943cced496fd7e4 # main
- name: Install Media Pack
- if: matrix.os == 'windows-latest'
+ if: runner.os == 'Windows'
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- name: Set up JDK 1.8
- uses: actions/setup-java@v2
+ uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: zulu
java-version: 8
- - name: Download drivers
+ - name: Set up Node.js
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: 24
+ - name: Build the driver
shell: bash
- run: scripts/download_driver_for_all_platforms.sh
+ run: scripts/build_driver.sh
- name: Build & Install
run: mvn -B install -D skipTests --no-transfer-progress
+ - name: Install browsers
+ run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
- name: Run tests
- run: mvn test --no-transfer-progress --fail-at-end
+ run: $CI_ENV_EXEC mvn test --no-transfer-progress --fail-at-end ${{ runner.os == 'Windows' && '-D junit.parallel.factor=0.25' || '' }} -D org.slf4j.simpleLogger.showDateTime=true -D org.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss
env:
BROWSER: chromium
BROWSER_CHANNEL: ${{ matrix.browser-channel }}
- Java_17:
- timeout-minutes: 30
+ Java_25:
+ timeout-minutes: 90
strategy:
fail-fast: false
matrix:
- browser: [chromium, firefox, webkit]
- runs-on: ubuntu-latest
+ browser: [chromium]
+ runs-on: playwright-x64-ubuntu24-64-core
steps:
- - uses: actions/checkout@v2
- - uses: microsoft/playwright-github-action@v1
- - name: Set up JDK 17
- uses: actions/setup-java@v2
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - uses: microsoft/playwright/.github/actions/ci-env@d1518e3e3fca90352c4390814943cced496fd7e4 # main
+ - name: Set up JDK 25
+ uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
+ with:
+ distribution: temurin
+ java-version: 25
+ - name: Set up Node.js
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
- distribution: adopt
- java-version: 17
- - name: Download drivers
+ node-version: 24
+ - name: Build the driver
shell: bash
- run: scripts/download_driver_for_all_platforms.sh
+ run: scripts/build_driver.sh
- name: Build & Install
run: mvn -B install -D skipTests --no-transfer-progress
+ # Runs on JDK 25: with JDK 8 the javadoc plugin never uses the module path.
+ - name: Verify javadoc
+ run: scripts/verify_javadoc.sh
+ - name: Install browsers
+ run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
- name: Run tests
- run: mvn test --no-transfer-progress --fail-at-end
+ run: $CI_ENV_EXEC mvn test --no-transfer-progress --fail-at-end
env:
BROWSER: ${{ matrix.browser }}
- name: Test Spring Boot Starter
diff --git a/.github/workflows/test_cli.yml b/.github/workflows/test_cli.yml
index df206608b..c6b0bda5f 100644
--- a/.github/workflows/test_cli.yml
+++ b/.github/workflows/test_cli.yml
@@ -13,15 +13,19 @@ jobs:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Cache Maven packages
- uses: actions/cache@v2
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- - name: Download drivers
- run: scripts/download_driver_for_all_platforms.sh
+ - name: Set up Node.js
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: 24
+ - name: Build the driver
+ run: scripts/build_driver.sh
- name: Intall Playwright
run: mvn install -D skipTests --no-transfer-progress
- name: Test CLI
@@ -29,3 +33,6 @@ jobs:
- name: Test CLI version
shell: bash
run: tools/test-cli-version/test.sh
+ - name: Test CLI Fatjar
+ shell: bash
+ run: tools/test-cli-fatjar/test.sh
diff --git a/.github/workflows/test_docker.yml b/.github/workflows/test_docker.yml
index cc3a18fd6..a442ddbb2 100644
--- a/.github/workflows/test_docker.yml
+++ b/.github/workflows/test_docker.yml
@@ -1,4 +1,4 @@
-name: Test Docker
+name: Docker
on:
push:
paths:
@@ -11,20 +11,81 @@ on:
paths:
- .github/workflows/test_docker.yml
- '**/Dockerfile*'
- - scripts/CLI_VERSION
+ - scripts/DRIVER_VERSION
+ - scripts/NODE_VERSION
- '**/pom.xml'
branches:
- main
- release-*
jobs:
test:
- timeout-minutes: 60
- runs-on: ubuntu-20.04
+ name: Test
+ timeout-minutes: 120
+ runs-on: ${{ matrix.runs-on }}
+ env:
+ PW_MAX_RETRIES: 3
+ strategy:
+ fail-fast: false
+ matrix:
+ flavor: [jammy, noble, resolute]
+ runs-on: [ubuntu-24.04, ubuntu-24.04-arm]
+ include:
+ - runs-on: ubuntu-24.04
+ arch: amd64
+ - runs-on: ubuntu-24.04-arm
+ arch: arm64
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - name: Set up Node.js
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: 24
- name: Build Docker image
- run: bash utils/docker/build.sh --amd64 focal playwright-java:localbuild-focal
- - name: Test
run: |
- CONTAINER_ID="$(docker run --rm --ipc=host -v $(pwd):/root/playwright --name playwright-docker-test -d -t playwright-java:localbuild-focal /bin/bash)"
- docker exec "${CONTAINER_ID}" /root/playwright/tools/test-local-installation/create_project_and_run_tests.sh
+ bash utils/docker/build.sh --${{ matrix.arch }} ${{ matrix.flavor }} playwright-java:localbuild-${{ matrix.flavor }}
+ # The scan looks at the content of the files, in all layers of the image.
+ - name: Scan the image for secrets
+ uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
+ with:
+ image-ref: playwright-java:localbuild-${{ matrix.flavor }}
+ scanners: secret
+ exit-code: '1'
+ # The secret scan needs no vulnerability database.
+ cache: 'false'
+ - name: Start container
+ run: |
+ CONTAINER_ID=$(docker run \
+ --rm \
+ --name playwright-docker-test \
+ --platform linux/${{ matrix.arch }} \
+ --user=pwuser \
+ --workdir /home/pwuser \
+ --shm-size=2g \
+ -e CI \
+ -e PW_MAX_RETRIES \
+ -d -t \
+ playwright-java:localbuild-${{ matrix.flavor }} /bin/bash)
+ echo "CONTAINER_ID=$CONTAINER_ID" >> $GITHUB_ENV
+
+ - name: Copy repository inside docker container
+ run: |
+ # The container does not need .upstream/, and it is large.
+ rm -rf .upstream
+ docker cp . "$CONTAINER_ID":/home/pwuser/playwright
+ # build.sh installed the SNAPSHOT artifacts into the local Maven repository
+ # of the runner; give them to pwuser so the test projects resolve them.
+ docker exec "$CONTAINER_ID" mkdir -p /home/pwuser/.m2/repository/com/microsoft
+ docker cp ~/.m2/repository/com/microsoft/playwright "$CONTAINER_ID":/home/pwuser/.m2/repository/com/microsoft/playwright
+ docker exec --user root "$CONTAINER_ID" chown -R pwuser /home/pwuser/playwright /home/pwuser/.m2
+
+ - name: Run smoke tests in container
+ run: |
+ docker exec "$CONTAINER_ID" /home/pwuser/playwright/tools/test-local-installation/create_project_and_run_tests.sh -Dgroups=smoke
+
+ - name: Test ClassLoader
+ run: |
+ docker exec "${CONTAINER_ID}" /home/pwuser/playwright/tools/test-spring-boot-starter/package_and_run_async_test.sh
+
+ - name: Stop container
+ run: |
+ docker stop "$CONTAINER_ID"
diff --git a/.github/workflows/trigger_internal_tests.yml b/.github/workflows/trigger_internal_tests.yml
deleted file mode 100644
index a6ef471a5..000000000
--- a/.github/workflows/trigger_internal_tests.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-name: "Internal Tests"
-
-on:
- push:
- branches:
- - main
- - release-*
-
-jobs:
- trigger:
- name: "trigger"
- runs-on: ubuntu-20.04
- steps:
- - run: |
- curl -X POST \
- -H "Accept: application/vnd.github.v3+json" \
- -H "Authorization: token ${GH_TOKEN}" \
- --data "{\"event_type\": \"playwright_tests_java\", \"client_payload\": {\"ref\": \"${GITHUB_SHA}\"}}" \
- https://api.github.com/repos/microsoft/playwright-internal/dispatches
- env:
- GH_TOKEN: ${{ secrets.REPOSITORY_DISPATCH_PERSONAL_ACCESS_TOKEN }}
diff --git a/.github/workflows/verify_api.yml b/.github/workflows/verify_api.yml
index 99c22809d..d450ee716 100644
--- a/.github/workflows/verify_api.yml
+++ b/.github/workflows/verify_api.yml
@@ -6,25 +6,30 @@ on:
- release-*
paths:
- 'scripts/*'
- - 'api-generator/*'
pull_request:
branches:
- main
- release-*
paths:
- 'scripts/**'
- - 'api-generator/**'
jobs:
verify:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
- - uses: microsoft/playwright-github-action@v1
- - name: Download drivers
- run: scripts/download_driver_for_all_platforms.sh
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - name: Set up Node.js
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: 24
+ - name: Build the driver
+ run: scripts/build_driver.sh
- name: Regenerate APIs
run: scripts/generate_api.sh
+ - name: Build & Install
+ run: mvn -B install -D skipTests --no-transfer-progress
+ - name: Install browsers
+ run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
- name: Update browser versions in README
run: scripts/update_readme.sh
- name: Verify API is up to date
diff --git a/.gitignore b/.gitignore
index 31577e7c2..80cb47576 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,3 +21,7 @@ target/
.idea
*.iml
+.npmrc
+
+# The microsoft/playwright checkout. scripts/build_driver.sh builds the driver from it.
+.upstream/
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 000000000..cdf233e20
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,82 @@
+# Playwright Java
+
+The Java client is a port of the JavaScript client in `~/code/playwright/packages/playwright-core/src/client/`. When implementing or changing a method, read the corresponding JS file first and mirror its logic.
+
+Paths such as `~/code/playwright` in this file assume that you check the repos out in `~/code`. Use the `gh` cli to interact with GitHub.
+
+## How this repo depends on Playwright
+
+- **The driver.** The Java client talks to the Node.js driver. The driver is the `playwright-core` package of `microsoft/playwright`. We build it from source at the commit in `scripts/DRIVER_VERSION`. `scripts/build_driver.sh` clones `microsoft/playwright` into `.upstream/` (gitignored), checks out that commit, builds it and puts the package into `driver/src/main/resources/driver/package/`. Do not edit, commit or switch branches in `.upstream/`. `scripts/roll_driver.sh` moves the commit: to the tip of upstream `main`, to the tip of an upstream `release-1.X` branch, or to an exact commit. We do not use the published npm packages or their versions. `git show v1.X.0:scripts/DRIVER_VERSION` prints the upstream commit of a release. For releases up to 1.65, it prints the `playwright-core` version of the driver.
+- **Upstream code.** In `.upstream/`, at the commit of the driver, or in `~/code/playwright`, which may be ahead of it: the client in `packages/playwright-core/src/client/`, the API docs in `docs/src/api/`, the tests in `tests/page/` and `tests/library/`. Its `AGENTS.md` says how to build it and run a test.
+- **Where a bug is.** When the same calls fail in a Node.js test upstream too, the cause is in the driver or a browser, and the fix lands in `microsoft/playwright`. When Node.js passes, the bug is in the Java client: compare the `*Impl.java` with its JavaScript counterpart, and fix it here.
+- **The generated API.** `scripts/generate_api.sh` runs `scripts/generate_java_api.mts`. It parses `docs/src/api/*.md` of `.upstream/` with the upstream parser (`utils/doclint/api_parser.js`) and writes every interface and options class in `playwright/src/main/java/com/microsoft/playwright/`, `options/` and `assertions/`. Only `CLI.java`, `PlaywrightException.java`, `TimeoutError.java`, `options/Annotate.java`, `options/BindingCallback.java`, `options/BrowserChannel.java`, `options/FunctionCallback.java` and the `package-info.java` files there are written by hand. Never edit a generated file: the next roll reverts it. A missing method or option is a change to `docs/src/api/` upstream.
+
+## Build and test
+
+```bash
+scripts/build_driver.sh # the driver, once per DRIVER_VERSION; needs git and Node.js
+mvn -B install -D skipTests --no-transfer-progress # build and install every module
+mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress
+BROWSER=chromium mvn test -f playwright/pom.xml -D test=TestPageScreenshot --no-transfer-progress
+```
+
+- `mvn test -f playwright/pom.xml` compiles the `playwright` module and its tests, so a change in `playwright/src/main/` needs no separate build step. After a change in `driver/` or `driver-bundle/`, run `mvn -B install -D skipTests --no-transfer-progress -f /pom.xml` first: the `playwright` module takes those modules from the local Maven repository.
+- The project targets Java 8. CI builds with JDK 8 (Zulu) and JDK 25. Do not use a newer language feature or library API.
+- There is no lint or format check. The style is the Google Java Style with a two-space indent, and without comments. When you change a file under `playwright/src/test/java/com/microsoft/playwright/tests/`, run `python3 scripts/check_test_registry.py`.
+- `-D test=` runs one class, `-D test=#` one method. `BROWSER` is a comma-separated list of `chromium`, `firefox` and `webkit`; unset, it runs all three. `HEADED=1` runs headed. A filter that matches no test passes with `Tests run: 0`, so check the count. Each test method has a 120 second timeout, set in the root `pom.xml`. Do not set `PW_MAX_RETRIES`, which reruns a failed test; CI sets it to 3. The reports are in `playwright/target/surefire-reports/`.
+
+## Tests
+
+The tests are in `playwright/src/test/java/com/microsoft/playwright/`. A test is a `@PlaywrightTest` method that takes the fixtures it needs as parameters, resolved by type: `Page page`, `BrowserContext context`, `Browser browser`, `BrowserType browserType`, `Playwright playwright`, `BrowserName browserName`, `Server server`, `HttpsServer httpsServer` and `@TempDir Path`. The method runs once per selected browser, with a context and a page of its own; the browser and the servers are shared. A class overrides options with `@Fixture` methods, and skips a browser with `@DisabledOnBrowser` or `@EnabledOnBrowser`. Drive the page with `page.setContent(...)` or `page.navigate(server.PREFIX + "/...")`, and the server with `server.setRoute(...)`, `server.setRedirect(...)`, `server.futureRequest(...)` and `server.EMPTY_PAGE`.
+
+| Directory | Use for |
+|-----------|---------|
+| `com/microsoft/playwright/` | the Java-only tests, one class per feature (`TestPageScreenshot`, `TestBrowserContextHar`). A regression test for a bug of the Java client goes here, in the class that owns the feature, as one added case. |
+| `com/microsoft/playwright/tests/page/`, `tests/library/` | line-by-line ports of upstream `tests/page` and `tests/library`, one class per spec file (`TestPageCheck` for `page-check.spec.ts`), each test titled `@DisplayName("CH-001 ...")` with the upstream identifier. Do not add a test or an assertion that upstream does not have. When the port that covers a bug carries `@Fixme("java: ...")`, the fix removes the mark, and that port is the regression test. `playwright/src/test/AGENTS.md` has the rules. |
+| `com/microsoft/playwright/junit/` | the public JUnit extension, `@UsePlaywright` |
+
+Tag a regression test with the issue as the Java-only tests do: a comment with the full URL on the first line of the test body, `// https://github.com/microsoft/playwright-java/issues/`. Good models: `TestBrowserContextExposeFunction`, `shouldNotDispatchBindingOnAClosedPage` (a binding, a popup and a context of its own in a try-with-resources block); `TestTracing`, `shouldRecoverTracingAfterAFailedStop` (a tagged test with `@TempDir` on `context.tracing()`).
+
+## Commit Convention
+
+Semantic commit messages: `label(scope): description`
+
+Labels: `fix`, `feat`, `chore`, `docs`, `test`, `devops`
+
+```bash
+git checkout -b fix-39562
+# ... make changes ...
+git add
+git commit -m "$(cat <<'EOF'
+fix(proxy): handle SOCKS proxy authentication
+
+Fixes: https://github.com/microsoft/playwright-java/issues/39562
+EOF
+)"
+# **Never `git push` without an explicit instruction to push.**
+git push origin fix-39562
+gh pr create --repo microsoft/playwright-java --head :fix-39562 \
+ --title "fix(proxy): handle SOCKS proxy authentication" \
+ --body "$(cat <<'EOF'
+## Summary
+-
+
+Fixes https://github.com/microsoft/playwright-java/issues/39562
+EOF
+)"
+```
+
+Never add Co-Authored-By agents in commit message.
+Never add "Generated with" in commit message.
+Never add test plan to PR description. Keep PR description short — a few bullet points at most.
+Branch naming for issue fixes: `fix-`.
+
+**Never amend commits.** Always create a new commit for follow-up changes, even when iterating on an open PR. Amending rewrites history and forces a force-push, losing the incremental review trail. Only amend if the user explicitly says so.
+
+**Never `git push` without an explicit instruction to push.** Applies even when a PR is already open for the branch — additional commits are immediately visible to reviewers. Commit locally, report what was committed, and wait. Only push when the user's message contains "push", "upload", "create PR", "ship it", or equivalent.
+
+## Skills
+
+- **playwright-roll** (`.claude/skills/playwright-roll/SKILL.md`) — roll Playwright Java to a new upstream commit: move `scripts/DRIVER_VERSION`, build the driver, regenerate the API, and port relevant upstream changes.
+- **playwright-java-release** (`.claude/skills/playwright-java-release/SKILL.md`) — prepare a release after the rolling PR merges: cut the release branch, mark the Maven version, and draft the GitHub release.
+- **playwright-cherry-pick** (upstream, `~/code/playwright/.claude/skills/playwright-cherry-pick/SKILL.md`) — cherry-pick a merged PR into a `release-1.X` branch as `cherry-pick(#): `. Use the same rules for this repo's release branches.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c089dfeae..1e4d1c2c8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,5 +1,20 @@
# Contributing
+## Choosing an Issue
+
+To maintain project quality and focus, Playwright **requires a corresponding issue** for every contribution, with the exception of minor documentation fixes.
+
+If you would like to address a bug or feature that isn't currently listed, **please file a new issue first**. This allows the community and maintainers to provide early feedback and facilitates a discussion before you invest time in developing a pull request.
+
+When submitting an issue, please state clearly if you intend to work on it. Once triaged and approved, the maintainers will determine the best path forward—whether the task should be handled by the **core team**, an **automated agent**, or a **community contributor**. If the issue is assigned to you, you may then proceed with your changes and submit a PR.
+
+### Submission Policy
+To ensure the maintainability of the project, please note the following:
+
+* **Unsolicited PRs:** Pull requests submitted without a linked issue or prior approval will be closed.
+* **Low-Quality AI Contributions:** PRs that do not meet our quality standards or lack human oversight (including low-quality agentic submissions) will be closed without explanation.
+* **Approval Required:** Only proceed with a PR once the issue has been officially assigned to you or approved for community contribution.
+
## How to Contribute
### Installing Developer Tools
@@ -20,48 +35,83 @@ 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 build and assemble the Playwright driver; it needs git and Node.js with npm. The platform-independent `playwright-core` package is assembled once into `driver/src/main/resources/driver/package/`, and the Node.js binary for each platform into `driver-bundle/src/main/resources/driver//` (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/build_driver.sh
```
-Names of published driver archives can be found at https://github.com/microsoft/playwright-cli/actions
+The driver is built from source: the script clones [microsoft/playwright](https://github.com/microsoft/playwright) into `.upstream/` (gitignored), checks out the commit pinned in [scripts/DRIVER_VERSION](scripts/DRIVER_VERSION) and builds the `playwright-core` package from it (`npm ci`, `npm run build`, `npm pack`). The build of `.upstream/` is reused until the commit changes. Each driver also gets the Node.js binary of the version pinned in [scripts/NODE_VERSION](scripts/NODE_VERSION) from https://nodejs.org, the same way the upstream Playwright build does it. Run the script again when `scripts/DRIVER_VERSION` or `scripts/NODE_VERSION` changes, for example after a pull. `scripts/roll_driver.sh` updates the pinned Node.js version to the latest release of the same major version on each roll. To update only Node.js, run `scripts/roll_node.sh` and then `scripts/build_driver.sh`.
### Building and running the tests with Maven
```bash
mvn compile
+# Runs every test in Chromium, Firefox and WebKit
mvn test
+# Selecting browsers
+BROWSER=chromium mvn test
+BROWSER=firefox,webkit mvn test
# Executing a single test
BROWSER=chromium mvn test -Dtest=TestPageNetworkSizes#shouldHaveTheCorrectResponseBodySize
# Executing a single test class
BROWSER=chromium mvn test -Dtest=TestPageNetworkSizes
```
+Set `HEADED=1` to watch the browsers and `BROWSER_CHANNEL=chrome` (or `msedge`, ...) to test a stable channel.
+
+### Writing tests
+
+Tests use the fixtures from `playwright/src/test/java/com/microsoft/playwright/fixtures`, modeled after the
+upstream Playwright Test fixtures. A test is a `@PlaywrightTest` method that declares the fixtures it needs
+as parameters; it runs once per selected browser, in a fresh context:
+
+```java
+@PlaywrightTest
+void shouldWork(Page page, Server server) {
+ page.navigate(server.EMPTY_PAGE);
+}
+```
+
+The built-in fixtures are `Playwright`, `BrowserName`, `BrowserType`, `BrowserType.LaunchOptions`, `Browser`,
+`Browser.NewContextOptions`, `BrowserContext`, `Page`, `Server` and `HttpsServer`. Playwright, the browser and
+the test servers are shared by the tests that run one after another on the same thread; the context and the
+page are created for each test and closed afterwards. A test class adds or overrides fixtures with
+`@Fixture` methods, whose parameters are the fixtures they depend on:
+
+```java
+@Fixture
+Browser.NewContextOptions contextOptions() {
+ return new Browser.NewContextOptions().setHasTouch(true);
+}
+
+@Fixture(scope = Scope.WORKER)
+static BrowserType.LaunchOptions launchOptions(BrowserType.LaunchOptions defaults) {
+ return defaults.setArgs(asList("--enable-features=WebMCP"));
+}
+```
+
+Use `@DisabledOnBrowser` / `@EnabledOnBrowser` for browser-specific tests, and a `@Nested @ParameterizedClass`
+with a `@Fixture` method reading its `@Parameter` field to run the same tests with different options.
+
### 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 by [scripts/generate_java_api.mts](scripts/generate_java_api.mts) from the API docs (`docs/src/api/*.md`) in `.upstream/`, the `microsoft/playwright` checkout at the commit in [scripts/DRIVER_VERSION](scripts/DRIVER_VERSION) that the driver is built from (run `scripts/build_driver.sh` first). Set `PW_SRC_DIR` to generate from another `microsoft/playwright` checkout instead, to try a change to the upstream docs; the committed files must come from `.upstream/`. The generator is a TypeScript file that Node.js runs as is, so it needs Node.js 22.18 or newer. To regenerate Java interfaces for the current driver run:
```bash
-./scripts/download_driver_for_all_platforms.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:
+The driver does not depend on a published Playwright version. To roll the driver to a newer commit of `microsoft/playwright`, run the following command:
```bash
-cat > scripts/CLI_VERSION
-
-^D
-./scripts/download_driver_for_all_platforms.sh -f
-./scripts/generate_api.sh
-./scripts/update_readme.sh
+scripts/roll_driver.sh [main|release-1.|]
```
+`main` (the default) is the tip of upstream `main`, `release-1.` is the tip of that upstream release branch, and `` is a full commit hash. The script writes the commit to `scripts/DRIVER_VERSION`, builds the driver from it and regenerates the API. The driver reports the version of `packages/playwright-core/package.json` at that commit: `1.67.0-next` on `main`, `1.66.0` on `release-1.66`.
+
### Code Style
- We try to follow [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html)
diff --git a/CodeQL.yml b/CodeQL.yml
new file mode 100644
index 000000000..4b8f962c5
--- /dev/null
+++ b/CodeQL.yml
@@ -0,0 +1,3 @@
+path_classifiers:
+ tests:
+ - "playwright/src/test/**"
diff --git a/README.md b/README.md
index 8ff1b91a9..aa9ab07c3 100644
--- a/README.md
+++ b/README.md
@@ -2,8 +2,7 @@
[](https://javadoc.io/doc/com.microsoft.playwright/playwright)
[](https://search.maven.org/search?q=com.microsoft.playwright)
-[](https://oss.sonatype.org/content/repositories/snapshots/com/microsoft/playwright/playwright/)
-[](https://aka.ms/playwright-slack)
+[](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,61 +10,21 @@ Playwright is a Java library to automate [Chromium](https://www.chromium.org/Hom
| | Linux | macOS | Windows |
| :--- | :---: | :---: | :---: |
-| Chromium 106.0.5249.30 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
-| WebKit 16.0 | ✅ | ✅ | ✅ |
-| Firefox 104.0 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
+| Chromium 158.0.8127.18 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
+| WebKit 27.2 | ✅ | ✅ | ✅ |
+| Firefox 159.0 | :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/next/intro/#system-requirements) for details.
-
-* [Usage](#usage)
- - [Add Maven dependency](#add-maven-dependency)
- - [Is Playwright thread-safe?](#is-playwright-thread-safe)
-* [Examples](#examples)
- - [Page screenshot](#page-screenshot)
- - [Mobile and geolocation](#mobile-and-geolocation)
- - [Evaluate JavaScript in browser](#evaluate-javascript-in-browser)
- - [Intercept network requests](#intercept-network-requests)
-* [Documentation](#documentation)
-* [Contributing](#contributing)
-* [Is Playwright for Java ready?](#is-playwright-for-java-ready)
-
-## Usage
-
-Playwright requires **Java 8** or newer.
-
-#### Add Maven dependency
-
-Playwright is distributed as a set of [Maven](https://maven.apache.org/what-is-maven.html) modules. The easiest way to use it is to add one dependency to your Maven `pom.xml` file as described below. If you're not familiar with Maven please refer to its [documentation](https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html).
-
-To run Playwright simply add following dependency to your Maven project:
-
-```xml
-
- com.microsoft.playwright
- playwright
- 1.26.0
-
-```
-
-To run Playwright using Gradle add following dependency to your build.gradle file:
-
-```gradle
-dependencies {
- implementation group: 'com.microsoft.playwright', name: 'playwright', version: '1.26.0'
-}
-```
-
-#### Is Playwright thread-safe?
+## Documentation
-No, Playwright is not thread safe, i.e. all its methods as well as methods on all objects created by it (such as BrowserContext, Browser, Page etc.) are expected to be called on the same thread where Playwright object was created or proper synchronization should be implemented to ensure only one thread calls Playwright methods at any given time. Having said that it's okay to create multiple Playwright instances each on its own thread.
+[https://playwright.dev/java/docs/intro](https://playwright.dev/java/docs/intro)
-## Examples
+## API Reference
-You can find Maven project with the examples [here](./examples).
+[https://playwright.dev/java/docs/api/class-playwright](https://playwright.dev/java/docs/api/class-playwright)
-#### Page screenshot
+## Example
-This code snippet navigates to whatsmyuseragent.org in Chromium, Firefox and WebKit, and saves 3 screenshots.
+This code snippet navigates to Playwright homepage in Chromium, Firefox and WebKit, and saves 3 screenshots.
```java
import com.microsoft.playwright.*;
@@ -86,7 +45,7 @@ public class PageScreenshot {
try (Browser browser = browserType.launch()) {
BrowserContext context = browser.newContext();
Page page = context.newPage();
- page.navigate("http://whatsmyuseragent.org/");
+ page.navigate("https://playwright.dev/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot-" + browserType.name() + ".png")));
}
}
@@ -95,100 +54,9 @@ public class PageScreenshot {
}
```
-#### Mobile and geolocation
-
-This snippet emulates Mobile Chromium on a device at a given geolocation, navigates to openstreetmap.org, performs action and takes a screenshot.
-
-```java
-import com.microsoft.playwright.options.*;
-import com.microsoft.playwright.*;
-
-import java.nio.file.Paths;
-
-import static java.util.Arrays.asList;
-
-public class MobileAndGeolocation {
- public static void main(String[] args) {
- try (Playwright playwright = Playwright.create()) {
- Browser browser = playwright.chromium().launch();
- BrowserContext context = browser.newContext(new Browser.NewContextOptions()
- .setUserAgent("Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36")
- .setViewportSize(411, 731)
- .setDeviceScaleFactor(2.625)
- .setIsMobile(true)
- .setHasTouch(true)
- .setLocale("en-US")
- .setGeolocation(41.889938, 12.492507)
- .setPermissions(asList("geolocation")));
- Page page = context.newPage();
- page.navigate("https://www.openstreetmap.org/");
- page.click("a[data-original-title=\"Show My Location\"]");
- page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("colosseum-pixel2.png")));
- }
- }
-}
-```
-
-#### Evaluate JavaScript in browser
-
-This code snippet navigates to example.com in Firefox, and executes a script in the page context.
-
-```java
-import com.microsoft.playwright.*;
-
-public class EvaluateInBrowserContext {
- public static void main(String[] args) {
- try (Playwright playwright = Playwright.create()) {
- Browser browser = playwright.firefox().launch();
- BrowserContext context = browser.newContext();
- Page page = context.newPage();
- page.navigate("https://www.example.com/");
- Object dimensions = page.evaluate("() => {\n" +
- " return {\n" +
- " width: document.documentElement.clientWidth,\n" +
- " height: document.documentElement.clientHeight,\n" +
- " deviceScaleFactor: window.devicePixelRatio\n" +
- " }\n" +
- "}");
- System.out.println(dimensions);
- }
- }
-}
-```
-
-#### Intercept network requests
-
-This code snippet sets up request routing for a WebKit page to log all network requests.
-
-```java
-import com.microsoft.playwright.*;
-
-public class InterceptNetworkRequests {
- public static void main(String[] args) {
- try (Playwright playwright = Playwright.create()) {
- Browser browser = playwright.webkit().launch();
- BrowserContext context = browser.newContext();
- Page page = context.newPage();
- page.route("**", route -> {
- System.out.println(route.request().url());
- route.resume();
- });
- page.navigate("http://todomvc.com");
- }
- }
-}
-```
-
-## Documentation
-
-Check out our official [documentation site](https://playwright.dev/java).
-
-You can also browse [javadoc online](https://www.javadoc.io/doc/com.microsoft.playwright/playwright/latest/index.html).
-
-## Contributing
-
-Follow [the instructions](https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md#getting-code) to build the project from source and install the driver.
-
-## Is Playwright for Java ready?
+## Other languages
-Yes, Playwright for Java is ready. v1.10.0 is the first stable release. Going forward we will adhere to [semantic versioning](https://semver.org/) of the API.
+More comfortable in another programming language? [Playwright](https://playwright.dev) is also available in
+- [Node.js (JavaScript / TypeScript)](https://playwright.dev/docs/intro),
+- [Python](https://playwright.dev/python/docs/intro).
+- [.NET](https://playwright.dev/dotnet/docs/intro),
diff --git a/ROLLING.md b/ROLLING.md
index ae0170f94..8407d21b7 100644
--- a/ROLLING.md
+++ b/ROLLING.md
@@ -1,13 +1,8 @@
# Rolling Playwright-Java to the latest Playwright driver
-* make sure to have at least Java 8 and Maven 3.6.3
+* make sure to have at least Java 8 and Maven 3.6.3, git, and Node.js with npm
* 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`
+* roll the driver and update generated sources: `./scripts/roll_driver.sh [main|release-1.|]`. It rolls to the tip of upstream `main` (the default), to the tip of an upstream release branch, or to an exact commit of `microsoft/playwright`. It writes the commit to `scripts/DRIVER_VERSION`, checks it out in `.upstream/` (a gitignored clone of `microsoft/playwright`) and builds the driver from it
+* list the upstream commits to port: `git -C .upstream log --oneline --reverse $(git show HEAD:scripts/DRIVER_VERSION)..$(cat scripts/DRIVER_VERSION)`
+* fix any errors
* commit & send PR with the roll
-
-# Updating Version
-
-```bash
-./scripts/set_maven_version.sh 1.15.0
-```
diff --git a/SUPPORT.md b/SUPPORT.md
new file mode 100644
index 000000000..2ed47a1f3
--- /dev/null
+++ b/SUPPORT.md
@@ -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
diff --git a/driver-bundle/pom.xml b/driver-bundle/pom.xml
index 9cd6c1f7e..1f65521ad 100644
--- a/driver-bundle/pom.xml
+++ b/driver-bundle/pom.xml
@@ -6,18 +6,24 @@
com.microsoft.playwrightparent-pom
- 1.27.0-SNAPSHOT
+ 1.50.0-SNAPSHOTdriver-bundle
- Playwright - Drivers For All Platforms
+ Playwright - Node.js For All Platforms
- This module includes Playwright driver and related utilities for all supported platforms.
- It is intended to be used on the systems where Playwright driver is not preinstalled.
+ Node.js binaries for the Playwright driver on every supported platform. Can be excluded when
+ Node.js is preinstalled on the host (see PLAYWRIGHT_NODEJS_PATH).
+
+ com.microsoft.playwright.driver.bundle
+
+
+
org.apache.maven.pluginsmaven-source-plugin
@@ -25,26 +31,6 @@
true
-
- org.apache.maven.plugins
- maven-javadoc-plugin
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
-
- com.microsoft.playwright
- driver
- ${project.version}
- compile
-
-
- org.junit.jupiter
- junit-jupiter-engine
-
-
diff --git a/driver/pom.xml b/driver/pom.xml
index cd99bc046..bf621037f 100644
--- a/driver/pom.xml
+++ b/driver/pom.xml
@@ -6,35 +6,38 @@
com.microsoft.playwrightparent-pom
- 1.27.0-SNAPSHOT
+ 1.50.0-SNAPSHOTdriverPlaywright - Driver
- This module provides API for discovery and launching of Playwright driver.
+ API for launching the Playwright driver. Bundles the platform-independent playwright-core
+ package; the Node.js binary comes from the driver-bundle module or a preinstalled Node.js.
+
+ com.microsoft.playwright.driver
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+
+
+
+
org.apache.maven.pluginsmaven-source-plugin
-
-
- org.apache.maven.plugins
- maven-javadoc-plugin
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
+
+ true
+
-
-
- org.junit.jupiter
- junit-jupiter-engine
-
-
diff --git a/driver/src/main/java/com/microsoft/playwright/impl/driver/Driver.java b/driver/src/main/java/com/microsoft/playwright/impl/driver/Driver.java
index 9ee059eaf..c659003e0 100644
--- a/driver/src/main/java/com/microsoft/playwright/impl/driver/Driver.java
+++ b/driver/src/main/java/com/microsoft/playwright/impl/driver/Driver.java
@@ -18,7 +18,6 @@
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -26,11 +25,14 @@
/**
* This class provides access to playwright-cli. It can be either preinstalled
- * in the host system and its path is passed as a system property or it can be
- * loaded from the driver-bundle module if that module is in the classpath.
+ * in the host system and its path is passed as a system property, or it can be
+ * loaded from the classpath: the platform-independent driver code ships in the
+ * driver module and the Node.js binary in the optional driver-bundle module.
*/
public abstract class Driver {
- protected final Map env = new LinkedHashMap<>();
+ protected final Map env = new LinkedHashMap<>(System.getenv());
+ public static final String PLAYWRIGHT_NODEJS_PATH = "PLAYWRIGHT_NODEJS_PATH";
+ public static final String PLAYWRIGHT_DRIVER_DIR = "PLAYWRIGHT_DRIVER_DIR";
private static Driver instance;
@@ -47,12 +49,15 @@ protected void initialize(Boolean installBrowsers) {
}
@Override
- protected Path driverDir() {
+ public Path driverDir() {
return driverDir;
}
}
public static synchronized Driver ensureDriverInstalled(Map env, Boolean installBrowsers) {
+ if (env.containsKey(PLAYWRIGHT_DRIVER_DIR)) {
+ return createAndInstall(env, installBrowsers);
+ }
if (instance == null) {
instance = createAndInstall(env, installBrowsers);
}
@@ -65,14 +70,14 @@ private void initialize(Map env, Boolean installBrowsers) throws
}
protected abstract void initialize(Boolean installBrowsers) throws Exception;
- public Path driverPath() {
- String cliFileName = System.getProperty("os.name").toLowerCase().contains("windows") ?
- "playwright.cmd" : "playwright.sh";
- return driverDir().resolve(cliFileName);
- }
-
public ProcessBuilder createProcessBuilder() {
- ProcessBuilder pb = new ProcessBuilder(driverPath().toString());
+ String nodePath = env.get("PLAYWRIGHT_NODEJS_PATH");
+ if (nodePath == null) {
+ String node = System.getProperty("os.name").toLowerCase().contains("windows") ? "node.exe" : "node";
+ nodePath = driverDir().resolve(node).toAbsolutePath().toString();
+ }
+ ProcessBuilder pb = new ProcessBuilder(nodePath);
+ pb.command().add(driverDir().resolve("package").resolve("cli.js").toAbsolutePath().toString());
pb.environment().putAll(env);
pb.environment().put("PW_LANG_NAME", "java");
pb.environment().put("PW_LANG_NAME_VERSION", getMajorJavaVersion());
@@ -96,7 +101,7 @@ private static String getMajorJavaVersion() {
}
public static Driver createAndInstall(Map env, Boolean installBrowsers) {
try {
- Driver instance = newInstance();
+ Driver instance = newInstance(env);
logMessage("initializing driver");
instance.initialize(env, installBrowsers);
logMessage("driver initialized.");
@@ -106,10 +111,16 @@ public static Driver createAndInstall(Map env, Boolean installBr
}
}
- private static Driver newInstance() throws Exception {
- String pathFromProperty = System.getProperty("playwright.cli.dir");
- if (pathFromProperty != null) {
- return new PreinstalledDriver(Paths.get(pathFromProperty));
+ private static Driver newInstance(Map env) throws Exception {
+ String driverDir = System.getProperty("playwright.cli.dir");
+ if (driverDir == null) {
+ driverDir = env.get(PLAYWRIGHT_DRIVER_DIR);
+ }
+ if (driverDir == null) {
+ driverDir = System.getenv(PLAYWRIGHT_DRIVER_DIR);
+ }
+ if (driverDir != null) {
+ return new PreinstalledDriver(Paths.get(driverDir));
}
String driverImpl =
@@ -118,7 +129,7 @@ private static Driver newInstance() throws Exception {
return (Driver) jarDriver.getDeclaredConstructor().newInstance();
}
- protected abstract Path driverDir();
+ public abstract Path driverDir();
protected static void logMessage(String message) {
// This matches log format produced by the server.
diff --git a/driver-bundle/src/main/java/com/microsoft/playwright/impl/driver/jar/DriverJar.java b/driver/src/main/java/com/microsoft/playwright/impl/driver/jar/DriverJar.java
similarity index 69%
rename from driver-bundle/src/main/java/com/microsoft/playwright/impl/driver/jar/DriverJar.java
rename to driver/src/main/java/com/microsoft/playwright/impl/driver/jar/DriverJar.java
index 0e5eb5c6b..ab5fba81e 100644
--- a/driver-bundle/src/main/java/com/microsoft/playwright/impl/driver/jar/DriverJar.java
+++ b/driver/src/main/java/com/microsoft/playwright/impl/driver/jar/DriverJar.java
@@ -29,19 +29,12 @@
public class DriverJar extends Driver {
private static final String PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD";
private static final String SELENIUM_REMOTE_URL = "SELENIUM_REMOTE_URL";
- static final String PLAYWRIGHT_NODEJS_PATH = "PLAYWRIGHT_NODEJS_PATH";
private final Path driverTempDir;
+ private final boolean deleteOnExit;
private Path preinstalledNodePath;
public DriverJar() throws IOException {
- // Allow specifying custom path for the driver installation
- // See https://github.com/microsoft/playwright-java/issues/728
- String alternativeTmpdir = System.getProperty("playwright.driver.tmpdir");
- String prefix = "playwright-java-";
- driverTempDir = alternativeTmpdir == null
- ? Files.createTempDirectory(prefix)
- : Files.createTempDirectory(Paths.get(alternativeTmpdir), prefix);
- driverTempDir.toFile().deleteOnExit();
+ this(createTempDriverDir(), true);
String nodePath = System.getProperty("playwright.nodejs.path");
if (nodePath != null) {
preinstalledNodePath = Paths.get(nodePath);
@@ -52,6 +45,32 @@ public DriverJar() throws IOException {
logMessage("created DriverJar: " + driverTempDir);
}
+ private DriverJar(Path driverDir, boolean deleteOnExit) {
+ this.driverTempDir = driverDir;
+ this.deleteOnExit = deleteOnExit;
+ if (deleteOnExit) {
+ driverTempDir.toFile().deleteOnExit();
+ }
+ }
+
+ private static Path createTempDriverDir() throws IOException {
+ // Allow specifying custom path for the driver installation
+ // See https://github.com/microsoft/playwright-java/issues/728
+ String alternativeTmpdir = System.getProperty("playwright.driver.tmpdir");
+ String prefix = "playwright-java-";
+ return alternativeTmpdir == null
+ ? Files.createTempDirectory(prefix)
+ : Files.createTempDirectory(Paths.get(alternativeTmpdir), prefix);
+ }
+
+ // Extracts the driver (playwright-core package and the Node.js binary for the current platform)
+ // into the given directory, persistently. Point playwright.cli.dir / PLAYWRIGHT_DRIVER_DIR at it
+ // to run without extracting to a temp directory on every launch. See issue #1268.
+ public static void installDriverTo(Path driverDir) throws IOException, URISyntaxException {
+ Files.createDirectories(driverDir);
+ new DriverJar(driverDir, false).extractDriverToTempDir();
+ }
+
@Override
protected void initialize(Boolean installBrowsers) throws Exception {
if (preinstalledNodePath == null && env.containsKey(PLAYWRIGHT_NODEJS_PATH)) {
@@ -64,7 +83,7 @@ protected void initialize(Boolean installBrowsers) throws Exception {
env.put(PLAYWRIGHT_NODEJS_PATH, preinstalledNodePath.toString());
}
extractDriverToTempDir();
- logMessage("extracted driver from jar to " + driverPath());
+ logMessage("extracted driver from jar to " + driverDir());
if (installBrowsers)
installBrowsers(env);
}
@@ -75,14 +94,14 @@ private void installBrowsers(Map env) throws IOException, Interr
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) {
logMessage("Skipping browsers download because `SELENIUM_REMOTE_URL` env variable is set");
return;
}
- Path driver = driverPath();
+ Path driver = driverDir();
if (!Files.exists(driver)) {
throw new RuntimeException("Failed to find driver: " + driver);
}
@@ -106,14 +125,42 @@ private static boolean isExecutable(Path filePath) {
return name.endsWith(".sh") || name.endsWith(".exe") || !name.contains(".");
}
+ private FileSystem initFileSystem(URI uri) throws IOException {
+ try {
+ return FileSystems.newFileSystem(uri, Collections.emptyMap());
+ } catch (FileSystemAlreadyExistsException e) {
+ return null;
+ }
+ }
+
+ public static URI getDriverResourceURI() throws URISyntaxException {
+ ClassLoader classloader = DriverJar.class.getClassLoader();
+ return classloader.getResource("driver/" + platformDir()).toURI();
+ }
+
void extractDriverToTempDir() throws URISyntaxException, IOException {
- ClassLoader classloader = Thread.currentThread().getContextClassLoader();
- URI originalUri = classloader.getResource(
- "driver/" + platformDir()).toURI();
+ // Concurrent extractions would share the zip file system of the jar, and the first one to finish closes it.
+ synchronized (DriverJar.class) {
+ extractResourceToDir("driver/package", driverTempDir.resolve("package"));
+ if (preinstalledNodePath == null) {
+ String platformResource = "driver/" + platformDir();
+ if (DriverJar.class.getClassLoader().getResource(platformResource) == null) {
+ throw new RuntimeException("Failed to find the bundled Node.js for platform '" + platformDir()
+ + "'. Add the com.microsoft.playwright:driver-bundle dependency, or set the "
+ + PLAYWRIGHT_NODEJS_PATH + " environment variable (or the playwright.nodejs.path system "
+ + "property) to point at a preinstalled Node.js.");
+ }
+ extractResourceToDir(platformResource, driverTempDir);
+ }
+ }
+ }
+
+ private void extractResourceToDir(String resourcePath, Path destDir) throws URISyntaxException, IOException {
+ URI originalUri = DriverJar.class.getClassLoader().getResource(resourcePath).toURI();
URI uri = maybeExtractNestedJar(originalUri);
// Create zip filesystem if loading from jar.
- try (FileSystem fileSystem = "jar".equals(uri.getScheme()) ? FileSystems.newFileSystem(uri, Collections.emptyMap()) : null) {
+ try (FileSystem fileSystem = "jar".equals(uri.getScheme()) ? initFileSystem(uri) : null) {
Path srcRoot = Paths.get(uri);
// jar file system's .relativize gives wrong results when used with
// spring-boot-maven-plugin, convert to the default filesystem to
@@ -121,14 +168,8 @@ void extractDriverToTempDir() throws URISyntaxException, IOException {
// See https://github.com/microsoft/playwright-java/issues/306
Path srcRootDefaultFs = Paths.get(srcRoot.toString());
Files.walk(srcRoot).forEach(fromPath -> {
- if (preinstalledNodePath != null) {
- String fileName = fromPath.getFileName().toString();
- if ("node.exe".equals(fileName) || "node".equals(fileName)) {
- return;
- }
- }
Path relative = srcRootDefaultFs.relativize(Paths.get(fromPath.toString()));
- Path toPath = driverTempDir.resolve(relative.toString());
+ Path toPath = destDir.resolve(relative.toString());
try {
if (Files.isDirectory(fromPath)) {
Files.createDirectories(toPath);
@@ -138,7 +179,9 @@ void extractDriverToTempDir() throws URISyntaxException, IOException {
toPath.toFile().setExecutable(true, true);
}
}
- toPath.toFile().deleteOnExit();
+ if (deleteOnExit) {
+ toPath.toFile().deleteOnExit();
+ }
} catch (IOException e) {
throw new RuntimeException("Failed to extract driver from " + uri + ", full uri: " + originalUri, e);
}
@@ -161,7 +204,9 @@ private URI maybeExtractNestedJar(final URI uri) throws URISyntaxException {
Path fromPath = Paths.get(jarUri);
Path toPath = driverTempDir.resolve(fromPath.getFileName().toString());
Files.copy(fromPath, toPath);
- toPath.toFile().deleteOnExit();
+ if (deleteOnExit) {
+ toPath.toFile().deleteOnExit();
+ }
return new URI("jar:" + toPath.toUri() + JAR_URL_SEPARATOR + parts[2]);
} catch (IOException e) {
throw new RuntimeException("Failed to extract driver's nested .jar from " + jarUri + "; full uri: " + uri, e);
@@ -183,13 +228,17 @@ private static String platformDir() {
}
}
if (name.contains("mac os x")) {
- return "mac";
+ if (arch.equals("aarch64")) {
+ return "mac-arm64";
+ } else {
+ return "mac";
+ }
}
throw new RuntimeException("Unexpected os.name value: " + name);
}
@Override
- protected Path driverDir() {
+ public Path driverDir() {
return driverTempDir;
}
}
diff --git a/driver/src/main/resources/.gitignore b/driver/src/main/resources/.gitignore
new file mode 100644
index 000000000..045408616
--- /dev/null
+++ b/driver/src/main/resources/.gitignore
@@ -0,0 +1,2 @@
+driver/
+local-driver/
diff --git a/examples/pom.xml b/examples/pom.xml
index c28574d85..66f426a37 100644
--- a/examples/pom.xml
+++ b/examples/pom.xml
@@ -6,16 +6,17 @@
org.exampleexamples
- 1.27.0-SNAPSHOT
+ 1.50.0-SNAPSHOTPlaywright Client ExamplesUTF-8
+ 1.63.0com.microsoft.playwrightplaywright
- 1.22.0
+ ${playwright.version}
@@ -23,7 +24,7 @@
org.apache.maven.pluginsmaven-compiler-plugin
- 3.1
+ 3.12.11.81.8
diff --git a/examples/src/main/java/org/example/PageScreenshot.java b/examples/src/main/java/org/example/PageScreenshot.java
index 1a327835c..0217be732 100644
--- a/examples/src/main/java/org/example/PageScreenshot.java
+++ b/examples/src/main/java/org/example/PageScreenshot.java
@@ -34,7 +34,7 @@ public static void main(String[] args) {
try (Browser browser = browserType.launch()) {
BrowserContext context = browser.newContext();
Page page = context.newPage();
- page.navigate("http://whatsmyuseragent.org/");
+ page.navigate("https://playwright.dev/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot-" + browserType.name() + ".png")));
}
}
diff --git a/examples/src/main/java/org/example/WebKitScreenshot.java b/examples/src/main/java/org/example/WebKitScreenshot.java
index 1e62d9c4a..52e130e9d 100644
--- a/examples/src/main/java/org/example/WebKitScreenshot.java
+++ b/examples/src/main/java/org/example/WebKitScreenshot.java
@@ -24,7 +24,7 @@ public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.webkit().launch();
Page page = browser.newPage();
- page.navigate("http://whatsmyuseragent.org/");
+ page.navigate("https://playwright.dev/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example.png")));
}
}
diff --git a/playwright/pom.xml b/playwright/pom.xml
index e52d09523..a59e6f3e3 100644
--- a/playwright/pom.xml
+++ b/playwright/pom.xml
@@ -7,7 +7,7 @@
com.microsoft.playwrightparent-pom
- 1.27.0-SNAPSHOT
+ 1.50.0-SNAPSHOTplaywright
@@ -19,28 +19,23 @@
This is the main package that provides Playwright client.
+
+ com.microsoft.playwright
+
+
-
- org.apache.maven.plugins
- maven-source-plugin
- org.apache.maven.pluginsmaven-javadoc-plugin
-
+
+
+ ${project.build.sourceDirectory}com.microsoft.playwright
- com.microsoft.playwright.impl
+ com.microsoft.playwright.impl:com.microsoft.playwright.impl.*
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- org.apache.maven.pluginsmaven-jar-plugin
@@ -49,6 +44,14 @@
test-jar
+
+
+
+
+ com.microsoft.playwright.test
+
+
+
@@ -65,14 +68,36 @@
com.google.code.gsongson
+
+ org.jspecify
+ jspecify
+ org.java-websocketJava-WebSocket
+
+
+ org.slf4j
+ slf4j-simple
+ org.junit.jupiterjunit-jupiter-engine
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-params
+ org.opentest4jopentest4j
@@ -86,4 +111,65 @@
driver-bundle
+
+
+ nullaway
+
+ [21,)
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ nullaway-testCompile
+ test-compile
+
+ testCompile
+
+
+ true
+
+ ${project.build.directory}/nullaway-test-classes
+
+ com/microsoft/playwright/nullability/JSpecifyApiConsumer.java
+
+
+ -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED
+ -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED
+ -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED
+ -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED
+ -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED
+ -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED
+ -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED
+ -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
+ -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
+ -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED
+ -XDcompilePolicy=simple
+ --should-stop=ifError=FLOW
+ -XDaddTypeAnnotationsToSymbol=true
+ -Xplugin:ErrorProne -XepDisableAllChecks -Xep:NullAway:ERROR -XepOpt:NullAway:OnlyNullMarked=true -XepOpt:NullAway:JSpecifyMode=true
+
+
+
+ com.google.errorprone
+ error_prone_core
+ ${error-prone.version}
+
+
+ com.uber.nullaway
+ nullaway
+ ${nullaway.version}
+
+
+
+
+
+
+
+
+
+
diff --git a/playwright/src/main/java/com/microsoft/playwright/APIRequest.java b/playwright/src/main/java/com/microsoft/playwright/APIRequest.java
index 43f8f19dc..20bd60abb 100644
--- a/playwright/src/main/java/com/microsoft/playwright/APIRequest.java
+++ b/playwright/src/main/java/com/microsoft/playwright/APIRequest.java
@@ -16,77 +16,114 @@
package com.microsoft.playwright;
+import org.jspecify.annotations.Nullable;
import com.microsoft.playwright.options.*;
import java.nio.file.Path;
import java.util.*;
/**
- * Exposes API that can be used for the Web API testing. This class is used for creating {@code APIRequestContext} instance which
- * in turn can be used for sending web requests. An instance of this class can be obtained via {@link Playwright#request
- * Playwright.request()}. For more information see {@code APIRequestContext}.
+ * Exposes API that can be used for the Web API testing. This class is used for creating {@code APIRequestContext} instance
+ * which in turn can be used for sending web requests. An instance of this class can be obtained via {@link
+ * com.microsoft.playwright.Playwright#request Playwright.request()}. For more information see {@code APIRequestContext}.
*/
public interface APIRequest {
class NewContextOptions {
/**
- * Methods like {@link APIRequestContext#get APIRequestContext.get()} take the base URL into consideration by using the {@code URL()} constructor for building the corresponding
- * URL. Examples:
+ * Methods like {@link com.microsoft.playwright.APIRequestContext#get APIRequestContext.get()} take the base URL into
+ * consideration by using the {@code URL()}
+ * constructor for building the corresponding URL. Examples:
*
- *
baseURL: {@code http://localhost:3000} and sending request to {@code /bar.html} results in {@code http://localhost:3000/bar.html}
- *
baseURL: {@code http://localhost:3000/foo/} and sending request to {@code ./bar.html} results in
- * {@code http://localhost:3000/foo/bar.html}
+ *
baseURL: {@code http://localhost:3000} and sending request to {@code /bar.html} results in {@code
+ * http://localhost:3000/bar.html}
+ *
baseURL: {@code http://localhost:3000/foo/} and sending request to {@code ./bar.html} results in {@code
+ * http://localhost:3000/foo/bar.html}
*
baseURL: {@code http://localhost:3000/foo} (without trailing slash) and navigating to {@code ./bar.html} results in
* {@code http://localhost:3000/bar.html}
*
*/
- public String baseURL;
+ public @Nullable String baseURL;
/**
- * An object containing additional HTTP headers to be sent with every request.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ *
Details
+ *
+ *
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.
+ *
+ *
Client certificate authentication is only active when at least one client certificate is provided. If you want to reject
+ * all client certificates sent by the server, you need to provide a client certificate with an {@code origin} that does
+ * not match any of the domains you plan to visit.
+ *
+ *
NOTE: 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 Map extraHTTPHeaders;
+ public @Nullable List clientCertificates;
/**
- * Credentials for HTTP authentication.
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
- public HttpCredentials httpCredentials;
+ public @Nullable Map extraHTTPHeaders;
+ /**
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
+ */
+ public @Nullable Boolean failOnStatusCode;
+ /**
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
+ */
+ public @Nullable Object httpCredentials;
/**
* Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}.
*/
- public Boolean ignoreHTTPSErrors;
+ public @Nullable Boolean ignoreHTTPSErrors;
+ /**
+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
+ * exceeded. Defaults to {@code 20}. Pass {@code 0} to not follow redirects. This can be overwritten for each request
+ * individually.
+ */
+ public @Nullable Integer maxRedirects;
/**
* Network proxy settings.
*/
- public Proxy proxy;
+ public @Nullable Proxy proxy;
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()} or {@link APIRequestContext#storageState
- * APIRequestContext.storageState()}. Either a path to the file with saved storage, or the value returned by one of {@link
- * BrowserContext#storageState BrowserContext.storageState()} or {@link APIRequestContext#storageState
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()} or {@link
+ * com.microsoft.playwright.APIRequestContext#storageState APIRequestContext.storageState()}. Either a path to the file
+ * with saved storage, or the value returned by one of {@link com.microsoft.playwright.BrowserContext#storageState
+ * BrowserContext.storageState()} or {@link com.microsoft.playwright.APIRequestContext#storageState
* APIRequestContext.storageState()} methods.
*/
- public String storageState;
+ public @Nullable String storageState;
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}. Path to the file with saved storage
- * state.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the
+ * file with saved storage state.
*/
- public Path storageStatePath;
+ public @Nullable Path storageStatePath;
/**
- * Maximum time in milliseconds to wait for the response. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout.
+ * Maximum time in milliseconds to wait for the response. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable
+ * timeout.
*/
- public Double timeout;
+ public @Nullable Double timeout;
/**
* Specific user agent to use in this context.
*/
- public String userAgent;
+ public @Nullable String userAgent;
/**
- * Methods like {@link APIRequestContext#get APIRequestContext.get()} take the base URL into consideration by using the {@code URL()} constructor for building the corresponding
- * URL. Examples:
+ * Methods like {@link com.microsoft.playwright.APIRequestContext#get APIRequestContext.get()} take the base URL into
+ * consideration by using the {@code URL()}
+ * constructor for building the corresponding URL. Examples:
*
- *
baseURL: {@code http://localhost:3000} and sending request to {@code /bar.html} results in {@code http://localhost:3000/bar.html}
- *
baseURL: {@code http://localhost:3000/foo/} and sending request to {@code ./bar.html} results in
- * {@code http://localhost:3000/foo/bar.html}
+ *
baseURL: {@code http://localhost:3000} and sending request to {@code /bar.html} results in {@code
+ * http://localhost:3000/bar.html}
+ *
baseURL: {@code http://localhost:3000/foo/} and sending request to {@code ./bar.html} results in {@code
+ * http://localhost:3000/foo/bar.html}
*
baseURL: {@code http://localhost:3000/foo} (without trailing slash) and navigating to {@code ./bar.html} results in
* {@code http://localhost:3000/bar.html}
*
@@ -96,25 +133,72 @@ public NewContextOptions setBaseURL(String baseURL) {
return this;
}
/**
- * An object containing additional HTTP headers to be sent with every request.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ *
Details
+ *
+ *
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.
+ *
+ *
Client certificate authentication is only active when at least one client certificate is provided. If you want to reject
+ * all client certificates sent by the server, you need to provide a client certificate with an {@code origin} that does
+ * not match any of the domains you plan to visit.
+ *
+ *
NOTE: 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 clientCertificates) {
+ this.clientCertificates = clientCertificates;
+ return this;
+ }
+ /**
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
public NewContextOptions setExtraHTTPHeaders(Map extraHTTPHeaders) {
this.extraHTTPHeaders = extraHTTPHeaders;
return this;
}
/**
- * Credentials for HTTP authentication.
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
+ */
+ public NewContextOptions setFailOnStatusCode(boolean failOnStatusCode) {
+ this.failOnStatusCode = failOnStatusCode;
+ return this;
+ }
+ /**
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
*/
public NewContextOptions setHttpCredentials(String username, String password) {
return setHttpCredentials(new HttpCredentials(username, password));
}
/**
- * Credentials for HTTP authentication.
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
*/
public NewContextOptions setHttpCredentials(HttpCredentials httpCredentials) {
this.httpCredentials = httpCredentials;
return this;
}
+ /**
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
+ */
+ public NewContextOptions setHttpCredentials(List httpCredentials) {
+ this.httpCredentials = httpCredentials;
+ return this;
+ }
/**
* Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}.
*/
@@ -122,6 +206,15 @@ public NewContextOptions setIgnoreHTTPSErrors(boolean ignoreHTTPSErrors) {
this.ignoreHTTPSErrors = ignoreHTTPSErrors;
return this;
}
+ /**
+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
+ * exceeded. Defaults to {@code 20}. Pass {@code 0} to not follow redirects. This can be overwritten for each request
+ * individually.
+ */
+ public NewContextOptions setMaxRedirects(int maxRedirects) {
+ this.maxRedirects = maxRedirects;
+ return this;
+ }
/**
* Network proxy settings.
*/
@@ -137,9 +230,10 @@ public NewContextOptions setProxy(Proxy proxy) {
}
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()} or {@link APIRequestContext#storageState
- * APIRequestContext.storageState()}. Either a path to the file with saved storage, or the value returned by one of {@link
- * BrowserContext#storageState BrowserContext.storageState()} or {@link APIRequestContext#storageState
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()} or {@link
+ * com.microsoft.playwright.APIRequestContext#storageState APIRequestContext.storageState()}. Either a path to the file
+ * with saved storage, or the value returned by one of {@link com.microsoft.playwright.BrowserContext#storageState
+ * BrowserContext.storageState()} or {@link com.microsoft.playwright.APIRequestContext#storageState
* APIRequestContext.storageState()} methods.
*/
public NewContextOptions setStorageState(String storageState) {
@@ -148,15 +242,16 @@ public NewContextOptions setStorageState(String storageState) {
}
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}. Path to the file with saved storage
- * state.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the
+ * file with saved storage state.
*/
public NewContextOptions setStorageStatePath(Path storageStatePath) {
this.storageStatePath = storageStatePath;
return this;
}
/**
- * Maximum time in milliseconds to wait for the response. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout.
+ * Maximum time in milliseconds to wait for the response. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable
+ * timeout.
*/
public NewContextOptions setTimeout(double timeout) {
this.timeout = timeout;
@@ -172,13 +267,17 @@ public NewContextOptions setUserAgent(String userAgent) {
}
/**
* Creates new instances of {@code APIRequestContext}.
+ *
+ * @since v1.16
*/
default APIRequestContext newContext() {
return newContext(null);
}
/**
* Creates new instances of {@code APIRequestContext}.
+ *
+ * @since v1.16
*/
- APIRequestContext newContext(NewContextOptions options);
+ APIRequestContext newContext(@Nullable NewContextOptions options);
}
diff --git a/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java b/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java
index 6570d5324..ee2163995 100644
--- a/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java
+++ b/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java
@@ -16,38 +16,135 @@
package com.microsoft.playwright;
+import org.jspecify.annotations.Nullable;
import com.microsoft.playwright.options.*;
import java.nio.file.Path;
+import java.util.*;
+import java.util.regex.Pattern;
/**
* This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services, prepare
* environment or the service to your e2e test.
*
- *
Each Playwright browser context has associated with it {@code APIRequestContext} instance which shares cookie storage with the
- * browser context and can be accessed via {@link BrowserContext#request BrowserContext.request()} or {@link Page#request
- * Page.request()}. It is also possible to create a new APIRequestContext instance manually by calling {@link
- * APIRequest#newContext APIRequest.newContext()}.
+ *
Each Playwright browser context has an associated {@code APIRequestContext}, accessible via {@link
+ * com.microsoft.playwright.BrowserContext#request BrowserContext.request()} or {@link
+ * com.microsoft.playwright.Page#request Page.request()} (these return the
*
- *
**Cookie management**
+ *
**same instance** — {@code page.request} is a shortcut for {@code page.context().request}). You can also create a
+ * standalone, isolated instance with {@link com.microsoft.playwright.APIRequest#newContext APIRequest.newContext()}.
*
- *
{@code APIRequestContext} returned by {@link BrowserContext#request BrowserContext.request()} and {@link Page#request
- * Page.request()} shares cookie storage with the corresponding {@code BrowserContext}. Each API request will have {@code Cookie}
- * header populated with the values from the browser context. If the API response contains {@code Set-Cookie} header it will
- * automatically update {@code BrowserContext} cookies and requests made from the page will pick them up. This means that if you
- * log in using this API, your e2e test will be logged in and vice versa.
+ *
Cookie management
*
- *
If you want API requests to not interfere with the browser cookies you should create a new {@code APIRequestContext} by
- * calling {@link APIRequest#newContext APIRequest.newContext()}. Such {@code APIRequestContext} object will have its own
- * isolated cookie storage.
+ *
The {@code APIRequestContext} returned by {@link com.microsoft.playwright.BrowserContext#request
+ * BrowserContext.request()} and
+ *
+ *
{@link com.microsoft.playwright.Page#request Page.request()} uses the same cookie jar as its {@code BrowserContext}:
+ *
+ *
If you want API requests that do **not** share cookies with the browser, create an isolated context via {@link
+ * com.microsoft.playwright.APIRequest#newContext APIRequest.newContext()}. Such {@code APIRequestContext} object will have
+ * its own isolated cookie storage.
*/
public interface APIRequestContext {
+ class ClearCookiesOptions {
+ /**
+ * Only removes cookies with the given domain.
+ */
+ public @Nullable Object domain;
+ /**
+ * Only removes cookies with the given name.
+ */
+ public @Nullable Object name;
+ /**
+ * Only removes cookies with the given path.
+ */
+ public @Nullable Object path;
+
+ /**
+ * Only removes cookies with the given domain.
+ */
+ public ClearCookiesOptions setDomain(String domain) {
+ this.domain = domain;
+ return this;
+ }
+ /**
+ * Only removes cookies with the given domain.
+ */
+ public ClearCookiesOptions setDomain(Pattern domain) {
+ this.domain = domain;
+ return this;
+ }
+ /**
+ * Only removes cookies with the given name.
+ */
+ public ClearCookiesOptions setName(String name) {
+ this.name = name;
+ return this;
+ }
+ /**
+ * Only removes cookies with the given name.
+ */
+ public ClearCookiesOptions setName(Pattern name) {
+ this.name = name;
+ return this;
+ }
+ /**
+ * Only removes cookies with the given path.
+ */
+ public ClearCookiesOptions setPath(String path) {
+ this.path = path;
+ return this;
+ }
+ /**
+ * Only removes cookies with the given path.
+ */
+ public ClearCookiesOptions setPath(Pattern path) {
+ this.path = path;
+ return this;
+ }
+ }
+ class DisposeOptions {
+ /**
+ * The reason to be reported to the operations interrupted by the context disposal.
+ */
+ public @Nullable 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 {
+ /**
+ * Set to {@code true} to include IndexedDB in the storage state snapshot.
+ */
+ public @Nullable Boolean indexedDB;
+ /**
+ * Set to {@code true} to include the origin private file system in the storage state snapshot.
+ */
+ public @Nullable Boolean opfs;
/**
* The file path to save the storage state to. If {@code path} is a relative path, then it is resolved relative to current
* working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
*/
- public Path path;
+ public @Nullable Path path;
+ /**
+ * Set to {@code true} to include IndexedDB in the storage state snapshot.
+ */
+ public StorageStateOptions setIndexedDB(boolean indexedDB) {
+ this.indexedDB = indexedDB;
+ return this;
+ }
+ /**
+ * Set to {@code true} to include the origin private file system in the storage state snapshot.
+ */
+ public StorageStateOptions setOpfs(boolean opfs) {
+ this.opfs = opfs;
+ return this;
+ }
/**
* The file path to save the storage state to. If {@code path} is a relative path, then it is resolved relative to current
* working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
@@ -57,12 +154,102 @@ public StorageStateOptions setPath(Path path) {
return this;
}
}
+ /**
+ * Adds cookies into this request context. They will be sent with matching subsequent requests. For {@link
+ * com.microsoft.playwright.BrowserContext#request BrowserContext.request()} and {@link
+ * com.microsoft.playwright.Page#request Page.request()}, this is equivalent to calling {@link
+ * com.microsoft.playwright.BrowserContext#addCookies BrowserContext.addCookies()} on the corresponding browser context.
+ *
+ *
+ *
+ * @since v1.64
+ */
+ void clearCookies(@Nullable ClearCookiesOptions options);
+ /**
+ * If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs
+ * are returned. For {@link com.microsoft.playwright.BrowserContext#request BrowserContext.request()} and {@link
+ * com.microsoft.playwright.Page#request Page.request()}, this is equivalent to calling {@link
+ * com.microsoft.playwright.BrowserContext#cookies BrowserContext.cookies()} on the corresponding browser context.
+ *
+ * @since v1.64
+ */
+ default List cookies() {
+ return cookies((String) null);
+ }
+ /**
+ * If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs
+ * are returned. For {@link com.microsoft.playwright.BrowserContext#request BrowserContext.request()} and {@link
+ * com.microsoft.playwright.Page#request Page.request()}, this is equivalent to calling {@link
+ * com.microsoft.playwright.BrowserContext#cookies BrowserContext.cookies()} on the corresponding browser context.
+ *
+ * @param urls Optional list of URLs.
+ * @since v1.64
+ */
+ List cookies(@Nullable String urls);
+ /**
+ * If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs
+ * are returned. For {@link com.microsoft.playwright.BrowserContext#request BrowserContext.request()} and {@link
+ * com.microsoft.playwright.Page#request Page.request()}, this is equivalent to calling {@link
+ * com.microsoft.playwright.BrowserContext#cookies BrowserContext.cookies()} on the corresponding browser context.
+ *
+ * @param urls Optional list of URLs.
+ * @since v1.64
+ */
+ List cookies(@Nullable List urls);
/**
* Sends HTTP(S) DELETE 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.
*
* @param url Target URL.
+ * @since v1.16
*/
default APIResponse delete(String url) {
return delete(url, null);
@@ -74,19 +261,62 @@ default APIResponse delete(String url) {
*
* @param url Target URL.
* @param params Optional request parameters.
+ * @since v1.16
*/
- APIResponse delete(String url, RequestOptions params);
+ APIResponse delete(String url, @Nullable RequestOptions params);
/**
- * All responses returned by {@link APIRequestContext#get APIRequestContext.get()} and similar methods are stored in the
- * memory, so that you can later call {@link APIResponse#body APIResponse.body()}. This method discards all stored
- * responses, and makes {@link APIResponse#body APIResponse.body()} throw "Response disposed" error.
+ * 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();
+ 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(@Nullable 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.
*
+ *
Usage
+ *
+ *
JSON objects can be passed directly to the request:
+ *
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, by specifiying the {@code multipart} parameter:
+ *
{@code
+ * // Pass file path to the form data constructor:
+ * Path file = Paths.get("team.csv");
+ * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+ * RequestOptions.create().setMethod("post").setMultipart(
+ * FormData.create().set("fileField", file)));
+ *
+ * // Or you can pass the file content directly as FilePayload object:
+ * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
+ * "console.log(2022);".getBytes(StandardCharsets.UTF_8));
+ * APIResponse response = request.fetch("https://example.com/api/uploadScript",
+ * RequestOptions.create().setMethod("post").setMultipart(
+ * FormData.create().set("fileField", filePayload)));
+ * }
+ *
* @param urlOrRequest Target URL or Request to get all parameters from.
+ * @since v1.16
*/
default APIResponse fetch(String urlOrRequest) {
return fetch(urlOrRequest, null);
@@ -95,15 +325,71 @@ default APIResponse fetch(String urlOrRequest) {
* 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.
*
+ *
Usage
+ *
+ *
JSON objects can be passed directly to the request:
+ *
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, by specifiying the {@code multipart} parameter:
+ *
{@code
+ * // Pass file path to the form data constructor:
+ * Path file = Paths.get("team.csv");
+ * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+ * RequestOptions.create().setMethod("post").setMultipart(
+ * FormData.create().set("fileField", file)));
+ *
+ * // Or you can pass the file content directly as FilePayload object:
+ * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
+ * "console.log(2022);".getBytes(StandardCharsets.UTF_8));
+ * APIResponse response = request.fetch("https://example.com/api/uploadScript",
+ * RequestOptions.create().setMethod("post").setMultipart(
+ * FormData.create().set("fileField", filePayload)));
+ * }
+ *
* @param urlOrRequest Target URL or Request to get all parameters from.
* @param params Optional request parameters.
+ * @since v1.16
*/
- APIResponse fetch(String urlOrRequest, RequestOptions params);
+ APIResponse fetch(String urlOrRequest, @Nullable RequestOptions params);
/**
* 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.
*
+ *
Usage
+ *
+ *
JSON objects can be passed directly to the request:
+ *
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, by specifiying the {@code multipart} parameter:
+ *
{@code
+ * // Pass file path to the form data constructor:
+ * Path file = Paths.get("team.csv");
+ * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+ * RequestOptions.create().setMethod("post").setMultipart(
+ * FormData.create().set("fileField", file)));
+ *
+ * // Or you can pass the file content directly as FilePayload object:
+ * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
+ * "console.log(2022);".getBytes(StandardCharsets.UTF_8));
+ * APIResponse response = request.fetch("https://example.com/api/uploadScript",
+ * RequestOptions.create().setMethod("post").setMultipart(
+ * FormData.create().set("fileField", filePayload)));
+ * }
+ *
* @param urlOrRequest Target URL or Request to get all parameters from.
+ * @since v1.16
*/
default APIResponse fetch(Request urlOrRequest) {
return fetch(urlOrRequest, null);
@@ -112,16 +398,54 @@ default APIResponse fetch(Request urlOrRequest) {
* 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.
*
+ *
Usage
+ *
+ *
JSON objects can be passed directly to the request:
+ *
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, by specifiying the {@code multipart} parameter:
+ *
{@code
+ * // Pass file path to the form data constructor:
+ * Path file = Paths.get("team.csv");
+ * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+ * RequestOptions.create().setMethod("post").setMultipart(
+ * FormData.create().set("fileField", file)));
+ *
+ * // Or you can pass the file content directly as FilePayload object:
+ * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
+ * "console.log(2022);".getBytes(StandardCharsets.UTF_8));
+ * APIResponse response = request.fetch("https://example.com/api/uploadScript",
+ * RequestOptions.create().setMethod("post").setMultipart(
+ * FormData.create().set("fileField", filePayload)));
+ * }
+ *
* @param urlOrRequest Target URL or Request to get all parameters from.
* @param params Optional request parameters.
+ * @since v1.16
*/
- APIResponse fetch(Request urlOrRequest, RequestOptions params);
+ APIResponse fetch(Request urlOrRequest, @Nullable RequestOptions params);
/**
* Sends HTTP(S) GET 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.
*
+ *
Usage
+ *
+ *
Request parameters can be configured with {@code params} option, they will be serialized into the URL search parameters:
+ *
To send form data to the server use {@code form} option. Its value will be encoded into the request body with {@code
+ * application/x-www-form-urlencoded} encoding (see below how to use {@code multipart/form-data} form encoding to send
+ * files):
+ *
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:
+ *
{@code
+ * // Pass file path to the form data constructor:
+ * Path file = Paths.get("team.csv");
+ * APIResponse response = request.post("https://example.com/api/uploadTeamList",
+ * RequestOptions.create().setMultipart(
+ * FormData.create().set("fileField", file)));
+ *
+ * // Or you can pass the file content directly as FilePayload object:
+ * FilePayload filePayload1 = new FilePayload("f1.js", "text/javascript",
+ * "console.log(2022);".getBytes(StandardCharsets.UTF_8));
+ * APIResponse response = request.post("https://example.com/api/uploadScript",
+ * RequestOptions.create().setMultipart(
+ * FormData.create().set("fileField", filePayload)));
+ * }
+ *
* @param url Target URL.
+ * @since v1.16
*/
default APIResponse post(String url) {
return post(url, null);
@@ -188,16 +564,55 @@ default APIResponse post(String url) {
* response. The method will populate request cookies from the context and update context cookies from the response. The
* method will automatically follow redirects.
*
+ *
Usage
+ *
+ *
JSON objects can be passed directly to the request:
+ *
To send form data to the server use {@code form} option. Its value will be encoded into the request body with {@code
+ * application/x-www-form-urlencoded} encoding (see below how to use {@code multipart/form-data} form encoding to send
+ * files):
+ *
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:
+ *
{@code
+ * // Pass file path to the form data constructor:
+ * Path file = Paths.get("team.csv");
+ * APIResponse response = request.post("https://example.com/api/uploadTeamList",
+ * RequestOptions.create().setMultipart(
+ * FormData.create().set("fileField", file)));
+ *
+ * // Or you can pass the file content directly as FilePayload object:
+ * FilePayload filePayload1 = new FilePayload("f1.js", "text/javascript",
+ * "console.log(2022);".getBytes(StandardCharsets.UTF_8));
+ * APIResponse response = request.post("https://example.com/api/uploadScript",
+ * RequestOptions.create().setMultipart(
+ * FormData.create().set("fileField", filePayload)));
+ * }
+ *
* @param url Target URL.
* @param params Optional request parameters.
+ * @since v1.16
*/
- APIResponse post(String url, RequestOptions params);
+ APIResponse post(String url, @Nullable RequestOptions params);
/**
* Sends HTTP(S) PUT 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.
*
* @param url Target URL.
+ * @since v1.16
*/
default APIResponse put(String url) {
return put(url, null);
@@ -209,11 +624,14 @@ default APIResponse put(String url) {
*
* @param url Target URL.
* @param params Optional request parameters.
+ * @since v1.16
*/
- APIResponse put(String url, RequestOptions params);
+ APIResponse put(String url, @Nullable RequestOptions params);
/**
* Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to
* the constructor.
+ *
+ * @since v1.16
*/
default String storageState() {
return storageState(null);
@@ -221,7 +639,15 @@ default String storageState() {
/**
* Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to
* the constructor.
+ *
+ * @since v1.16
+ */
+ String storageState(@Nullable StorageStateOptions options);
+ /**
+ * Tracing recorder for requests made through this API request context.
+ *
+ * @since v1.60
*/
- String storageState(StorageStateOptions options);
+ Tracing tracing();
}
diff --git a/playwright/src/main/java/com/microsoft/playwright/APIResponse.java b/playwright/src/main/java/com/microsoft/playwright/APIResponse.java
index 5330fcad0..e72069b6a 100644
--- a/playwright/src/main/java/com/microsoft/playwright/APIResponse.java
+++ b/playwright/src/main/java/com/microsoft/playwright/APIResponse.java
@@ -16,49 +16,92 @@
package com.microsoft.playwright;
+import org.jspecify.annotations.Nullable;
import com.microsoft.playwright.options.*;
import java.util.*;
/**
- * {@code APIResponse} class represents responses returned by {@link APIRequestContext#get APIRequestContext.get()} and similar
- * methods.
+ * {@code APIResponse} class represents responses returned by {@link com.microsoft.playwright.APIRequestContext#get
+ * APIRequestContext.get()} and similar methods.
*/
public interface APIResponse {
/**
* Returns the buffer with response body.
+ *
+ * @since v1.16
*/
byte[] body();
/**
* Disposes the body of this response. If not called then the body will stay in memory until the context closes.
+ *
+ * @since v1.16
*/
void dispose();
/**
* An object with all the response HTTP headers associated with this response.
+ *
+ * @since v1.16
*/
Map 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
*/
List headersArray();
/**
* Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
+ *
+ * @since v1.16
*/
boolean ok();
+ /**
+ * Returns SSL and other security information. Resolves to {@code null} for non-HTTPS responses. For redirected requests,
+ * returns the information for the last request in the redirect chain.
+ *
+ * @since v1.61
+ */
+ @Nullable SecurityDetails securityDetails();
+ /**
+ * Returns the IP address and port of the server. Resolves to {@code null} if the server address is not available. For
+ * redirected requests, returns the information for the last request in the redirect chain.
+ *
+ * @since v1.61
+ */
+ @Nullable ServerAddr serverAddr();
/**
* Contains the status code of the response (e.g., 200 for a success).
+ *
+ * @since v1.16
*/
int status();
/**
* Contains the status text of the response (e.g. usually an "OK" for a success).
+ *
+ * @since v1.16
*/
String statusText();
/**
* Returns the text representation of response body.
+ *
+ * @since v1.16
*/
String text();
+ /**
+ * Returns resource timing information for given response. For redirected requests, returns the information for the last
+ * request in the redirect chain. When the response is served from the HAR file, timing information is not
+ * available and all the values are -1. Find more information at Resource Timing API.
+ *
+ * @since v1.62
+ */
+ Timing timing();
/**
* Contains the URL of the response.
+ *
+ * @since v1.16
*/
String url();
}
diff --git a/playwright/src/main/java/com/microsoft/playwright/Browser.java b/playwright/src/main/java/com/microsoft/playwright/Browser.java
index acb80d75f..3d5707d84 100644
--- a/playwright/src/main/java/com/microsoft/playwright/Browser.java
+++ b/playwright/src/main/java/com/microsoft/playwright/Browser.java
@@ -16,6 +16,7 @@
package com.microsoft.playwright;
+import org.jspecify.annotations.Nullable;
import com.microsoft.playwright.options.*;
import java.nio.file.Path;
import java.util.*;
@@ -23,31 +24,40 @@
import java.util.regex.Pattern;
/**
- * A Browser is created via {@link BrowserType#launch BrowserType.launch()}. An example of using a {@code Browser} to create a
- * {@code Page}:
+ * A Browser is created via {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}. An example of using a
+ * {@code Browser} to create a {@code Page}:
*
*/
public interface Browser extends AutoCloseable {
+ /**
+ * Emitted when a new browser context is created.
+ */
+ void onContext(Consumer handler);
+ /**
+ * Removes handler that was previously added with {@link #onContext onContext(handler)}.
+ */
+ void offContext(Consumer handler);
+
/**
* Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:
*
*
Browser application is closed or crashed.
- *
The {@link Browser#close Browser.close()} method was called.
+ *
The {@link com.microsoft.playwright.Browser#close Browser.close()} method was called.
*
*/
void onDisconnected(Consumer handler);
@@ -56,174 +66,240 @@ public interface Browser extends AutoCloseable {
*/
void offDisconnected(Consumer handler);
+ class CloseOptions {
+ /**
+ * The reason to be reported to the operations interrupted by the browser closure.
+ */
+ public @Nullable String reason;
+
+ /**
+ * The reason to be reported to the operations interrupted by the browser closure.
+ */
+ public CloseOptions setReason(String reason) {
+ this.reason = reason;
+ return this;
+ }
+ }
class NewContextOptions {
/**
* Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted.
*/
- public Boolean acceptDownloads;
+ public @Nullable Boolean acceptDownloads;
/**
- * When using {@link Page#navigate Page.navigate()}, {@link Page#route Page.route()}, {@link Page#waitForURL
- * Page.waitForURL()}, {@link Page#waitForRequest Page.waitForRequest()}, or {@link Page#waitForResponse
- * Page.waitForResponse()} it takes the base URL in consideration by using the {@code URL()} constructor for building the corresponding
- * URL. Examples:
+ * When using {@link com.microsoft.playwright.Page#navigate Page.navigate()}, {@link com.microsoft.playwright.Page#route
+ * Page.route()}, {@link com.microsoft.playwright.Page#waitForURL Page.waitForURL()}, {@link
+ * com.microsoft.playwright.Page#waitForRequest Page.waitForRequest()}, or {@link
+ * com.microsoft.playwright.Page#waitForResponse Page.waitForResponse()} it takes the base URL in consideration by using
+ * the {@code URL()} constructor for building the
+ * corresponding URL. Unset by default. Examples:
*
- *
baseURL: {@code http://localhost:3000} and navigating to {@code /bar.html} results in {@code http://localhost:3000/bar.html}
- *
baseURL: {@code http://localhost:3000/foo/} and navigating to {@code ./bar.html} results in {@code http://localhost:3000/foo/bar.html}
+ *
baseURL: {@code http://localhost:3000} and navigating to {@code /bar.html} results in {@code
+ * http://localhost:3000/bar.html}
+ *
baseURL: {@code http://localhost:3000/foo/} and navigating to {@code ./bar.html} results in {@code
+ * http://localhost:3000/foo/bar.html}
*
baseURL: {@code http://localhost:3000/foo} (without trailing slash) and navigating to {@code ./bar.html} results in
* {@code http://localhost:3000/bar.html}
*
*/
- public String baseURL;
+ public @Nullable String baseURL;
+ /**
+ * Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}.
+ */
+ public @Nullable Boolean bypassCSP;
/**
- * Toggles bypassing page's Content-Security-Policy.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ *
Details
+ *
+ *
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.
+ *
+ *
Client certificate authentication is only active when at least one client certificate is provided. If you want to reject
+ * all client certificates sent by the server, you need to provide a client certificate with an {@code origin} that does
+ * not match any of the domains you plan to visit.
+ *
+ *
NOTE: 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 Boolean bypassCSP;
+ public @Nullable List clientCertificates;
/**
- * Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code "no-preference"}. See
- * {@link Page#emulateMedia Page.emulateMedia()} for more details. Defaults to {@code "light"}.
+ * Emulates prefers-colors-scheme media
+ * feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
+ * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
+ * "light"}.
*/
- public ColorScheme colorScheme;
+ public @Nullable Optional colorScheme;
/**
- * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}.
+ * Emulates {@code "prefers-contrast"} media feature, supported values are {@code "no-preference"}, {@code "more"}. See
+ * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets
+ * emulation to system defaults. Defaults to {@code "no-preference"}.
*/
- public Double deviceScaleFactor;
+ public @Nullable Optional contrast;
/**
- * An object containing additional HTTP headers to be sent with every request.
+ * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}. Learn more about emulating devices with device scale factor.
*/
- public Map extraHTTPHeaders;
+ public @Nullable Double deviceScaleFactor;
/**
- * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
- * Page.emulateMedia()} for more details. Defaults to {@code "none"}.
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
- public ForcedColors forcedColors;
- public Geolocation geolocation;
+ public @Nullable Map extraHTTPHeaders;
/**
- * Specifies if viewport supports touch events. Defaults to false.
+ * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link
+ * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation
+ * to system defaults. Defaults to {@code "none"}.
*/
- public Boolean hasTouch;
+ public @Nullable Optional forcedColors;
+ public @Nullable Geolocation geolocation;
/**
- * Credentials for HTTP authentication.
+ * Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.
*/
- public HttpCredentials httpCredentials;
+ public @Nullable Boolean hasTouch;
+ /**
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
+ */
+ public @Nullable Object httpCredentials;
/**
* Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}.
*/
- public Boolean ignoreHTTPSErrors;
+ public @Nullable Boolean ignoreHTTPSErrors;
/**
- * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. Defaults to {@code false}. Not supported
- * in Firefox.
+ * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. isMobile is a part of device,
+ * so you don't actually need to set it manually. Defaults to {@code false}. Learn more about mobile emulation.
*/
- public Boolean isMobile;
+ public @Nullable Boolean isMobile;
/**
- * Whether or not to enable JavaScript in the context. Defaults to {@code true}.
+ * Whether or not to enable JavaScript in the context. Defaults to {@code true}. Learn more about disabling JavaScript.
*/
- public Boolean javaScriptEnabled;
+ public @Nullable Boolean javaScriptEnabled;
/**
- * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value, {@code Accept-Language}
- * request header value as well as number and date formatting rules.
+ * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value,
+ * {@code Accept-Language} request header value as well as number and date formatting rules. Defaults to the system default
+ * locale. Learn more about emulation in our emulation guide.
*/
- public String locale;
+ public @Nullable String locale;
/**
- * Whether to emulate network being offline. Defaults to {@code false}.
+ * Whether to emulate network being offline. Defaults to {@code false}. Learn more about network emulation.
*/
- public Boolean offline;
+ public @Nullable Boolean offline;
/**
- * A list of permissions to grant to all pages in this context. See {@link BrowserContext#grantPermissions
- * BrowserContext.grantPermissions()} for more details.
+ * A list of permissions to grant to all pages in this context. See {@link
+ * com.microsoft.playwright.BrowserContext#grantPermissions BrowserContext.grantPermissions()} for more details. Defaults
+ * to none.
*/
- public List permissions;
+ public @Nullable List permissions;
/**
- * Network proxy settings to use with this context.
- *
- *
NOTE: 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' } })}.
+ * Network proxy settings to use with this context. Defaults to none.
*/
- public Proxy proxy;
+ public @Nullable Proxy proxy;
/**
- * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach}
- * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file.
- * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
+ * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If
+ * {@code attach} is specified, resources are persisted as separate files and all of these files are archived along with
+ * the HAR file. Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
*/
- public HarContentPolicy recordHarContent;
+ public @Nullable HarContentPolicy recordHarContent;
/**
- * 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}.
+ * 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}.
*/
- public HarMode recordHarMode;
+ public @Nullable HarMode recordHarMode;
/**
* Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}.
*/
- public Boolean recordHarOmitContent;
+ public @Nullable Boolean recordHarOmitContent;
/**
* Enables HAR recording for all pages into the specified HAR
- * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link BrowserContext#close
- * BrowserContext.close()} for the HAR to be saved.
+ * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link
+ * com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for the HAR to be saved.
*/
- public Path recordHarPath;
- public Object recordHarUrlFilter;
+ public @Nullable Path recordHarPath;
+ public @Nullable Object recordHarUrlFilter;
/**
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
- * to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
+ * to call {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for videos to be saved.
+ */
+ public @Nullable Path recordVideoDir;
+ /**
+ * Frame rate of the recorded videos in frames per second. Defaults to {@code 25}. Firefox and WebKit currently capture up
+ * to 25 frames per second.
*/
- public Path recordVideoDir;
+ public @Nullable Integer recordVideoFps;
/**
* Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into
- * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each page will
- * be scaled down if necessary to fit the specified size.
+ * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each
+ * page will be scaled down if necessary to fit the specified size.
*/
- public RecordVideoSize recordVideoSize;
+ public @Nullable RecordVideoSize recordVideoSize;
/**
- * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}. See {@link
- * Page#emulateMedia Page.emulateMedia()} for more details. Defaults to {@code "no-preference"}.
+ * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}.
+ * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets
+ * emulation to system defaults. Defaults to {@code "no-preference"}.
*/
- public ReducedMotion reducedMotion;
+ public @Nullable Optional reducedMotion;
/**
- * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code viewport}
- * is set.
+ * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code
+ * viewport} is set.
*/
- public ScreenSize screenSize;
+ public @Nullable ScreenSize screenSize;
/**
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
*
{@code "block"}: Playwright will block all registration of Service Workers.
*
*/
- public ServiceWorkerPolicy serviceWorkers;
+ public @Nullable ServiceWorkerPolicy serviceWorkers;
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}.
*/
- public String storageState;
+ public @Nullable String storageState;
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}. Path to the file with saved storage
- * state.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the
+ * file with saved storage state.
*/
- public Path storageStatePath;
+ public @Nullable Path storageStatePath;
/**
- * If specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
- * that imply single target DOM element will throw when more than one element matches the selector. See {@code Locator} to learn
- * more about the strict mode.
+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
+ * that imply single target DOM element will throw when more than one element matches the selector. This option does not
+ * affect any Locator APIs (Locators are always strict). Defaults to {@code false}. See {@code Locator} to learn more about
+ * the strict mode.
*/
- public Boolean strictSelectors;
+ public @Nullable Boolean strictSelectors;
/**
* Changes the timezone of the context. See ICU's
- * metaZones.txt for a list of supported timezone IDs.
+ * metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.
*/
- public String timezoneId;
+ public @Nullable String timezoneId;
/**
* Specific user agent to use in this context.
*/
- public String userAgent;
+ public @Nullable String userAgent;
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. {@code null} disables the default viewport.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent
+ * viewport emulation. Learn more about viewport
+ * emulation.
+ *
+ *
NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the
+ * operating system. It makes the execution of the tests non-deterministic.
*/
- public Optional viewportSize;
+ public @Nullable Optional viewportSize;
/**
* Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted.
@@ -233,14 +309,17 @@ public NewContextOptions setAcceptDownloads(boolean acceptDownloads) {
return this;
}
/**
- * When using {@link Page#navigate Page.navigate()}, {@link Page#route Page.route()}, {@link Page#waitForURL
- * Page.waitForURL()}, {@link Page#waitForRequest Page.waitForRequest()}, or {@link Page#waitForResponse
- * Page.waitForResponse()} it takes the base URL in consideration by using the {@code URL()} constructor for building the corresponding
- * URL. Examples:
+ * When using {@link com.microsoft.playwright.Page#navigate Page.navigate()}, {@link com.microsoft.playwright.Page#route
+ * Page.route()}, {@link com.microsoft.playwright.Page#waitForURL Page.waitForURL()}, {@link
+ * com.microsoft.playwright.Page#waitForRequest Page.waitForRequest()}, or {@link
+ * com.microsoft.playwright.Page#waitForResponse Page.waitForResponse()} it takes the base URL in consideration by using
+ * the {@code URL()} constructor for building the
+ * corresponding URL. Unset by default. Examples:
*
- *
baseURL: {@code http://localhost:3000} and navigating to {@code /bar.html} results in {@code http://localhost:3000/bar.html}
- *
baseURL: {@code http://localhost:3000/foo/} and navigating to {@code ./bar.html} results in {@code http://localhost:3000/foo/bar.html}
+ *
baseURL: {@code http://localhost:3000} and navigating to {@code /bar.html} results in {@code
+ * http://localhost:3000/bar.html}
+ *
baseURL: {@code http://localhost:3000/foo/} and navigating to {@code ./bar.html} results in {@code
+ * http://localhost:3000/foo/bar.html}
*
baseURL: {@code http://localhost:3000/foo} (without trailing slash) and navigating to {@code ./bar.html} results in
* {@code http://localhost:3000/bar.html}
*
@@ -250,40 +329,75 @@ public NewContextOptions setBaseURL(String baseURL) {
return this;
}
/**
- * Toggles bypassing page's Content-Security-Policy.
+ * Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}.
*/
public NewContextOptions setBypassCSP(boolean bypassCSP) {
this.bypassCSP = bypassCSP;
return this;
}
/**
- * Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code "no-preference"}. See
- * {@link Page#emulateMedia Page.emulateMedia()} for more details. Defaults to {@code "light"}.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ *
Details
+ *
+ *
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.
+ *
+ *
Client certificate authentication is only active when at least one client certificate is provided. If you want to reject
+ * all client certificates sent by the server, you need to provide a client certificate with an {@code origin} that does
+ * not match any of the domains you plan to visit.
+ *
+ *
NOTE: 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 setColorScheme(ColorScheme colorScheme) {
- this.colorScheme = colorScheme;
+ public NewContextOptions setClientCertificates(List clientCertificates) {
+ this.clientCertificates = clientCertificates;
return this;
}
/**
- * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}.
+ * Emulates prefers-colors-scheme media
+ * feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
+ * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
+ * "light"}.
+ */
+ public NewContextOptions setColorScheme(@Nullable ColorScheme colorScheme) {
+ this.colorScheme = Optional.ofNullable(colorScheme);
+ return this;
+ }
+ /**
+ * Emulates {@code "prefers-contrast"} media feature, supported values are {@code "no-preference"}, {@code "more"}. See
+ * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets
+ * emulation to system defaults. Defaults to {@code "no-preference"}.
+ */
+ public NewContextOptions setContrast(@Nullable Contrast contrast) {
+ this.contrast = Optional.ofNullable(contrast);
+ return this;
+ }
+ /**
+ * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}. Learn more about emulating devices with device scale factor.
*/
public NewContextOptions setDeviceScaleFactor(double deviceScaleFactor) {
this.deviceScaleFactor = deviceScaleFactor;
return this;
}
/**
- * An object containing additional HTTP headers to be sent with every request.
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
public NewContextOptions setExtraHTTPHeaders(Map extraHTTPHeaders) {
this.extraHTTPHeaders = extraHTTPHeaders;
return this;
}
/**
- * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
- * Page.emulateMedia()} for more details. Defaults to {@code "none"}.
+ * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link
+ * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation
+ * to system defaults. Defaults to {@code "none"}.
*/
- public NewContextOptions setForcedColors(ForcedColors forcedColors) {
- this.forcedColors = forcedColors;
+ public NewContextOptions setForcedColors(@Nullable ForcedColors forcedColors) {
+ this.forcedColors = Optional.ofNullable(forcedColors);
return this;
}
public NewContextOptions setGeolocation(double latitude, double longitude) {
@@ -294,25 +408,45 @@ public NewContextOptions setGeolocation(Geolocation geolocation) {
return this;
}
/**
- * Specifies if viewport supports touch events. Defaults to false.
+ * Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.
*/
public NewContextOptions setHasTouch(boolean hasTouch) {
this.hasTouch = hasTouch;
return this;
}
/**
- * Credentials for HTTP authentication.
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
*/
public NewContextOptions setHttpCredentials(String username, String password) {
return setHttpCredentials(new HttpCredentials(username, password));
}
/**
- * Credentials for HTTP authentication.
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
*/
public NewContextOptions setHttpCredentials(HttpCredentials httpCredentials) {
this.httpCredentials = httpCredentials;
return this;
}
+ /**
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
+ */
+ public NewContextOptions setHttpCredentials(List httpCredentials) {
+ this.httpCredentials = httpCredentials;
+ return this;
+ }
/**
* Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}.
*/
@@ -321,76 +455,75 @@ public NewContextOptions setIgnoreHTTPSErrors(boolean ignoreHTTPSErrors) {
return this;
}
/**
- * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. Defaults to {@code false}. Not supported
- * in Firefox.
+ * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. isMobile is a part of device,
+ * so you don't actually need to set it manually. Defaults to {@code false}. Learn more about mobile emulation.
*/
public NewContextOptions setIsMobile(boolean isMobile) {
this.isMobile = isMobile;
return this;
}
/**
- * Whether or not to enable JavaScript in the context. Defaults to {@code true}.
+ * Whether or not to enable JavaScript in the context. Defaults to {@code true}. Learn more about disabling JavaScript.
*/
public NewContextOptions setJavaScriptEnabled(boolean javaScriptEnabled) {
this.javaScriptEnabled = javaScriptEnabled;
return this;
}
/**
- * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value, {@code Accept-Language}
- * request header value as well as number and date formatting rules.
+ * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value,
+ * {@code Accept-Language} request header value as well as number and date formatting rules. Defaults to the system default
+ * locale. Learn more about emulation in our emulation guide.
*/
public NewContextOptions setLocale(String locale) {
this.locale = locale;
return this;
}
/**
- * Whether to emulate network being offline. Defaults to {@code false}.
+ * Whether to emulate network being offline. Defaults to {@code false}. Learn more about network emulation.
*/
public NewContextOptions setOffline(boolean offline) {
this.offline = offline;
return this;
}
/**
- * A list of permissions to grant to all pages in this context. See {@link BrowserContext#grantPermissions
- * BrowserContext.grantPermissions()} for more details.
+ * A list of permissions to grant to all pages in this context. See {@link
+ * com.microsoft.playwright.BrowserContext#grantPermissions BrowserContext.grantPermissions()} for more details. Defaults
+ * to none.
*/
public NewContextOptions setPermissions(List permissions) {
this.permissions = permissions;
return this;
}
/**
- * Network proxy settings to use with this context.
- *
- *
NOTE: 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' } })}.
+ * Network proxy settings to use with this context. Defaults to none.
*/
public NewContextOptions setProxy(String server) {
return setProxy(new Proxy(server));
}
/**
- * Network proxy settings to use with this context.
- *
- *
NOTE: 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' } })}.
+ * Network proxy settings to use with this context. Defaults to none.
*/
public NewContextOptions setProxy(Proxy proxy) {
this.proxy = proxy;
return this;
}
/**
- * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach}
- * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file.
- * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
+ * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If
+ * {@code attach} is specified, resources are persisted as separate files and all of these files are archived along with
+ * the HAR file. Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
*/
public NewContextOptions setRecordHarContent(HarContentPolicy recordHarContent) {
this.recordHarContent = recordHarContent;
return this;
}
/**
- * 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}.
+ * 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}.
*/
public NewContextOptions setRecordHarMode(HarMode recordHarMode) {
this.recordHarMode = recordHarMode;
@@ -405,8 +538,8 @@ public NewContextOptions setRecordHarOmitContent(boolean recordHarOmitContent) {
}
/**
* Enables HAR recording for all pages into the specified HAR
- * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link BrowserContext#close
- * BrowserContext.close()} for the HAR to be saved.
+ * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link
+ * com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for the HAR to be saved.
*/
public NewContextOptions setRecordHarPath(Path recordHarPath) {
this.recordHarPath = recordHarPath;
@@ -422,47 +555,56 @@ public NewContextOptions setRecordHarUrlFilter(Pattern recordHarUrlFilter) {
}
/**
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
- * to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
+ * to call {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for videos to be saved.
*/
public NewContextOptions setRecordVideoDir(Path recordVideoDir) {
this.recordVideoDir = recordVideoDir;
return this;
}
+ /**
+ * Frame rate of the recorded videos in frames per second. Defaults to {@code 25}. Firefox and WebKit currently capture up
+ * to 25 frames per second.
+ */
+ public NewContextOptions setRecordVideoFps(int recordVideoFps) {
+ this.recordVideoFps = recordVideoFps;
+ return this;
+ }
/**
* Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into
- * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each page will
- * be scaled down if necessary to fit the specified size.
+ * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each
+ * page will be scaled down if necessary to fit the specified size.
*/
public NewContextOptions setRecordVideoSize(int width, int height) {
return setRecordVideoSize(new RecordVideoSize(width, height));
}
/**
* Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into
- * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each page will
- * be scaled down if necessary to fit the specified size.
+ * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each
+ * page will be scaled down if necessary to fit the specified size.
*/
public NewContextOptions setRecordVideoSize(RecordVideoSize recordVideoSize) {
this.recordVideoSize = recordVideoSize;
return this;
}
/**
- * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}. See {@link
- * Page#emulateMedia Page.emulateMedia()} for more details. Defaults to {@code "no-preference"}.
+ * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}.
+ * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets
+ * emulation to system defaults. Defaults to {@code "no-preference"}.
*/
- public NewContextOptions setReducedMotion(ReducedMotion reducedMotion) {
- this.reducedMotion = reducedMotion;
+ public NewContextOptions setReducedMotion(@Nullable ReducedMotion reducedMotion) {
+ this.reducedMotion = Optional.ofNullable(reducedMotion);
return this;
}
/**
- * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code viewport}
- * is set.
+ * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code
+ * viewport} is set.
*/
public NewContextOptions setScreenSize(int width, int height) {
return setScreenSize(new ScreenSize(width, height));
}
/**
- * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code viewport}
- * is set.
+ * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code
+ * viewport} is set.
*/
public NewContextOptions setScreenSize(ScreenSize screenSize) {
this.screenSize = screenSize;
@@ -471,8 +613,8 @@ public NewContextOptions setScreenSize(ScreenSize screenSize) {
/**
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
*
{@code "block"}: Playwright will block all registration of Service Workers.
*
*/
@@ -482,7 +624,7 @@ public NewContextOptions setServiceWorkers(ServiceWorkerPolicy serviceWorkers) {
}
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}.
*/
public NewContextOptions setStorageState(String storageState) {
this.storageState = storageState;
@@ -490,17 +632,18 @@ public NewContextOptions setStorageState(String storageState) {
}
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}. Path to the file with saved storage
- * state.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the
+ * file with saved storage state.
*/
public NewContextOptions setStorageStatePath(Path storageStatePath) {
this.storageStatePath = storageStatePath;
return this;
}
/**
- * If specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
- * that imply single target DOM element will throw when more than one element matches the selector. See {@code Locator} to learn
- * more about the strict mode.
+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
+ * that imply single target DOM element will throw when more than one element matches the selector. This option does not
+ * affect any Locator APIs (Locators are always strict). Defaults to {@code false}. See {@code Locator} to learn more about
+ * the strict mode.
*/
public NewContextOptions setStrictSelectors(boolean strictSelectors) {
this.strictSelectors = strictSelectors;
@@ -509,7 +652,7 @@ public NewContextOptions setStrictSelectors(boolean strictSelectors) {
/**
* Changes the timezone of the context. See ICU's
- * metaZones.txt for a list of supported timezone IDs.
+ * metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.
*/
public NewContextOptions setTimezoneId(String timezoneId) {
this.timezoneId = timezoneId;
@@ -523,15 +666,25 @@ public NewContextOptions setUserAgent(String userAgent) {
return this;
}
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. {@code null} disables the default viewport.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent
+ * viewport emulation. Learn more about viewport
+ * emulation.
+ *
+ *
NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the
+ * operating system. It makes the execution of the tests non-deterministic.
*/
public NewContextOptions setViewportSize(int width, int height) {
return setViewportSize(new ViewportSize(width, height));
}
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. {@code null} disables the default viewport.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent
+ * viewport emulation. Learn more about viewport
+ * emulation.
+ *
+ *
NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the
+ * operating system. It makes the execution of the tests non-deterministic.
*/
- public NewContextOptions setViewportSize(ViewportSize viewportSize) {
+ public NewContextOptions setViewportSize(@Nullable ViewportSize viewportSize) {
this.viewportSize = Optional.ofNullable(viewportSize);
return this;
}
@@ -540,170 +693,222 @@ class NewPageOptions {
/**
* Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted.
*/
- public Boolean acceptDownloads;
+ public @Nullable Boolean acceptDownloads;
/**
- * When using {@link Page#navigate Page.navigate()}, {@link Page#route Page.route()}, {@link Page#waitForURL
- * Page.waitForURL()}, {@link Page#waitForRequest Page.waitForRequest()}, or {@link Page#waitForResponse
- * Page.waitForResponse()} it takes the base URL in consideration by using the {@code URL()} constructor for building the corresponding
- * URL. Examples:
+ * When using {@link com.microsoft.playwright.Page#navigate Page.navigate()}, {@link com.microsoft.playwright.Page#route
+ * Page.route()}, {@link com.microsoft.playwright.Page#waitForURL Page.waitForURL()}, {@link
+ * com.microsoft.playwright.Page#waitForRequest Page.waitForRequest()}, or {@link
+ * com.microsoft.playwright.Page#waitForResponse Page.waitForResponse()} it takes the base URL in consideration by using
+ * the {@code URL()} constructor for building the
+ * corresponding URL. Unset by default. Examples:
*
- *
baseURL: {@code http://localhost:3000} and navigating to {@code /bar.html} results in {@code http://localhost:3000/bar.html}
- *
baseURL: {@code http://localhost:3000/foo/} and navigating to {@code ./bar.html} results in {@code http://localhost:3000/foo/bar.html}
+ *
baseURL: {@code http://localhost:3000} and navigating to {@code /bar.html} results in {@code
+ * http://localhost:3000/bar.html}
+ *
baseURL: {@code http://localhost:3000/foo/} and navigating to {@code ./bar.html} results in {@code
+ * http://localhost:3000/foo/bar.html}
*
baseURL: {@code http://localhost:3000/foo} (without trailing slash) and navigating to {@code ./bar.html} results in
* {@code http://localhost:3000/bar.html}
*
*/
- public String baseURL;
+ public @Nullable String baseURL;
/**
- * Toggles bypassing page's Content-Security-Policy.
+ * Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}.
*/
- public Boolean bypassCSP;
+ public @Nullable Boolean bypassCSP;
/**
- * Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code "no-preference"}. See
- * {@link Page#emulateMedia Page.emulateMedia()} for more details. Defaults to {@code "light"}.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ *
Details
+ *
+ *
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.
+ *
+ *
Client certificate authentication is only active when at least one client certificate is provided. If you want to reject
+ * all client certificates sent by the server, you need to provide a client certificate with an {@code origin} that does
+ * not match any of the domains you plan to visit.
+ *
+ *
NOTE: 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 ColorScheme colorScheme;
+ public @Nullable List clientCertificates;
/**
- * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}.
+ * Emulates prefers-colors-scheme media
+ * feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
+ * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
+ * "light"}.
*/
- public Double deviceScaleFactor;
+ public @Nullable Optional colorScheme;
/**
- * An object containing additional HTTP headers to be sent with every request.
+ * Emulates {@code "prefers-contrast"} media feature, supported values are {@code "no-preference"}, {@code "more"}. See
+ * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets
+ * emulation to system defaults. Defaults to {@code "no-preference"}.
*/
- public Map extraHTTPHeaders;
+ public @Nullable Optional contrast;
/**
- * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
- * Page.emulateMedia()} for more details. Defaults to {@code "none"}.
+ * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}. Learn more about emulating devices with device scale factor.
*/
- public ForcedColors forcedColors;
- public Geolocation geolocation;
+ public @Nullable Double deviceScaleFactor;
/**
- * Specifies if viewport supports touch events. Defaults to false.
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
- public Boolean hasTouch;
+ public @Nullable Map extraHTTPHeaders;
/**
- * Credentials for HTTP authentication.
+ * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link
+ * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation
+ * to system defaults. Defaults to {@code "none"}.
*/
- public HttpCredentials httpCredentials;
+ public @Nullable Optional forcedColors;
+ public @Nullable Geolocation geolocation;
+ /**
+ * Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.
+ */
+ public @Nullable Boolean hasTouch;
+ /**
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
+ */
+ public @Nullable Object httpCredentials;
/**
* Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}.
*/
- public Boolean ignoreHTTPSErrors;
+ public @Nullable Boolean ignoreHTTPSErrors;
/**
- * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. Defaults to {@code false}. Not supported
- * in Firefox.
+ * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. isMobile is a part of device,
+ * so you don't actually need to set it manually. Defaults to {@code false}. Learn more about mobile emulation.
*/
- public Boolean isMobile;
+ public @Nullable Boolean isMobile;
/**
- * Whether or not to enable JavaScript in the context. Defaults to {@code true}.
+ * Whether or not to enable JavaScript in the context. Defaults to {@code true}. Learn more about disabling JavaScript.
*/
- public Boolean javaScriptEnabled;
+ public @Nullable Boolean javaScriptEnabled;
/**
- * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value, {@code Accept-Language}
- * request header value as well as number and date formatting rules.
+ * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value,
+ * {@code Accept-Language} request header value as well as number and date formatting rules. Defaults to the system default
+ * locale. Learn more about emulation in our emulation guide.
*/
- public String locale;
+ public @Nullable String locale;
/**
- * Whether to emulate network being offline. Defaults to {@code false}.
+ * Whether to emulate network being offline. Defaults to {@code false}. Learn more about network emulation.
*/
- public Boolean offline;
+ public @Nullable Boolean offline;
/**
- * A list of permissions to grant to all pages in this context. See {@link BrowserContext#grantPermissions
- * BrowserContext.grantPermissions()} for more details.
+ * A list of permissions to grant to all pages in this context. See {@link
+ * com.microsoft.playwright.BrowserContext#grantPermissions BrowserContext.grantPermissions()} for more details. Defaults
+ * to none.
*/
- public List permissions;
+ public @Nullable List permissions;
/**
- * Network proxy settings to use with this context.
- *
- *
NOTE: 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' } })}.
+ * Network proxy settings to use with this context. Defaults to none.
*/
- public Proxy proxy;
+ public @Nullable Proxy proxy;
/**
- * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach}
- * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file.
- * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
+ * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If
+ * {@code attach} is specified, resources are persisted as separate files and all of these files are archived along with
+ * the HAR file. Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
*/
- public HarContentPolicy recordHarContent;
+ public @Nullable HarContentPolicy recordHarContent;
/**
- * 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}.
+ * 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}.
*/
- public HarMode recordHarMode;
+ public @Nullable HarMode recordHarMode;
/**
* Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}.
*/
- public Boolean recordHarOmitContent;
+ public @Nullable Boolean recordHarOmitContent;
/**
* Enables HAR recording for all pages into the specified HAR
- * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link BrowserContext#close
- * BrowserContext.close()} for the HAR to be saved.
+ * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link
+ * com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for the HAR to be saved.
*/
- public Path recordHarPath;
- public Object recordHarUrlFilter;
+ public @Nullable Path recordHarPath;
+ public @Nullable Object recordHarUrlFilter;
/**
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
- * to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
+ * to call {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for videos to be saved.
*/
- public Path recordVideoDir;
+ public @Nullable Path recordVideoDir;
+ /**
+ * Frame rate of the recorded videos in frames per second. Defaults to {@code 25}. Firefox and WebKit currently capture up
+ * to 25 frames per second.
+ */
+ public @Nullable Integer recordVideoFps;
/**
* Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into
- * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each page will
- * be scaled down if necessary to fit the specified size.
+ * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each
+ * page will be scaled down if necessary to fit the specified size.
*/
- public RecordVideoSize recordVideoSize;
+ public @Nullable RecordVideoSize recordVideoSize;
/**
- * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}. See {@link
- * Page#emulateMedia Page.emulateMedia()} for more details. Defaults to {@code "no-preference"}.
+ * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}.
+ * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets
+ * emulation to system defaults. Defaults to {@code "no-preference"}.
*/
- public ReducedMotion reducedMotion;
+ public @Nullable Optional reducedMotion;
/**
- * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code viewport}
- * is set.
+ * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code
+ * viewport} is set.
*/
- public ScreenSize screenSize;
+ public @Nullable ScreenSize screenSize;
/**
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
*
{@code "block"}: Playwright will block all registration of Service Workers.
*
*/
- public ServiceWorkerPolicy serviceWorkers;
+ public @Nullable ServiceWorkerPolicy serviceWorkers;
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}.
*/
- public String storageState;
+ public @Nullable String storageState;
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}. Path to the file with saved storage
- * state.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the
+ * file with saved storage state.
*/
- public Path storageStatePath;
+ public @Nullable Path storageStatePath;
/**
- * If specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
- * that imply single target DOM element will throw when more than one element matches the selector. See {@code Locator} to learn
- * more about the strict mode.
+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
+ * that imply single target DOM element will throw when more than one element matches the selector. This option does not
+ * affect any Locator APIs (Locators are always strict). Defaults to {@code false}. See {@code Locator} to learn more about
+ * the strict mode.
*/
- public Boolean strictSelectors;
+ public @Nullable Boolean strictSelectors;
/**
* Changes the timezone of the context. See ICU's
- * metaZones.txt for a list of supported timezone IDs.
+ * metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.
*/
- public String timezoneId;
+ public @Nullable String timezoneId;
/**
* Specific user agent to use in this context.
*/
- public String userAgent;
+ public @Nullable String userAgent;
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. {@code null} disables the default viewport.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent
+ * viewport emulation. Learn more about viewport
+ * emulation.
+ *
+ *
NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the
+ * operating system. It makes the execution of the tests non-deterministic.
*/
- public Optional viewportSize;
+ public @Nullable Optional viewportSize;
/**
* Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted.
@@ -713,14 +918,17 @@ public NewPageOptions setAcceptDownloads(boolean acceptDownloads) {
return this;
}
/**
- * When using {@link Page#navigate Page.navigate()}, {@link Page#route Page.route()}, {@link Page#waitForURL
- * Page.waitForURL()}, {@link Page#waitForRequest Page.waitForRequest()}, or {@link Page#waitForResponse
- * Page.waitForResponse()} it takes the base URL in consideration by using the {@code URL()} constructor for building the corresponding
- * URL. Examples:
+ * When using {@link com.microsoft.playwright.Page#navigate Page.navigate()}, {@link com.microsoft.playwright.Page#route
+ * Page.route()}, {@link com.microsoft.playwright.Page#waitForURL Page.waitForURL()}, {@link
+ * com.microsoft.playwright.Page#waitForRequest Page.waitForRequest()}, or {@link
+ * com.microsoft.playwright.Page#waitForResponse Page.waitForResponse()} it takes the base URL in consideration by using
+ * the {@code URL()} constructor for building the
+ * corresponding URL. Unset by default. Examples:
*
- *
baseURL: {@code http://localhost:3000} and navigating to {@code /bar.html} results in {@code http://localhost:3000/bar.html}
- *
baseURL: {@code http://localhost:3000/foo/} and navigating to {@code ./bar.html} results in {@code http://localhost:3000/foo/bar.html}
+ *
baseURL: {@code http://localhost:3000} and navigating to {@code /bar.html} results in {@code
+ * http://localhost:3000/bar.html}
+ *
baseURL: {@code http://localhost:3000/foo/} and navigating to {@code ./bar.html} results in {@code
+ * http://localhost:3000/foo/bar.html}
*
baseURL: {@code http://localhost:3000/foo} (without trailing slash) and navigating to {@code ./bar.html} results in
* {@code http://localhost:3000/bar.html}
*
@@ -730,40 +938,75 @@ public NewPageOptions setBaseURL(String baseURL) {
return this;
}
/**
- * Toggles bypassing page's Content-Security-Policy.
+ * Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}.
*/
public NewPageOptions setBypassCSP(boolean bypassCSP) {
this.bypassCSP = bypassCSP;
return this;
}
/**
- * Emulates {@code "prefers-colors-scheme"} media feature, supported values are {@code "light"}, {@code "dark"}, {@code "no-preference"}. See
- * {@link Page#emulateMedia Page.emulateMedia()} for more details. Defaults to {@code "light"}.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ *
Details
+ *
+ *
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.
+ *
+ *
Client certificate authentication is only active when at least one client certificate is provided. If you want to reject
+ * all client certificates sent by the server, you need to provide a client certificate with an {@code origin} that does
+ * not match any of the domains you plan to visit.
+ *
+ *
NOTE: 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 clientCertificates) {
+ this.clientCertificates = clientCertificates;
+ return this;
+ }
+ /**
+ * Emulates prefers-colors-scheme media
+ * feature, supported values are {@code "light"} and {@code "dark"}. See {@link com.microsoft.playwright.Page#emulateMedia
+ * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code
+ * "light"}.
+ */
+ public NewPageOptions setColorScheme(@Nullable ColorScheme colorScheme) {
+ this.colorScheme = Optional.ofNullable(colorScheme);
+ return this;
+ }
+ /**
+ * Emulates {@code "prefers-contrast"} media feature, supported values are {@code "no-preference"}, {@code "more"}. See
+ * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets
+ * emulation to system defaults. Defaults to {@code "no-preference"}.
*/
- public NewPageOptions setColorScheme(ColorScheme colorScheme) {
- this.colorScheme = colorScheme;
+ public NewPageOptions setContrast(@Nullable Contrast contrast) {
+ this.contrast = Optional.ofNullable(contrast);
return this;
}
/**
- * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}.
+ * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}. Learn more about emulating devices with device scale factor.
*/
public NewPageOptions setDeviceScaleFactor(double deviceScaleFactor) {
this.deviceScaleFactor = deviceScaleFactor;
return this;
}
/**
- * An object containing additional HTTP headers to be sent with every request.
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
public NewPageOptions setExtraHTTPHeaders(Map extraHTTPHeaders) {
this.extraHTTPHeaders = extraHTTPHeaders;
return this;
}
/**
- * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
- * Page.emulateMedia()} for more details. Defaults to {@code "none"}.
+ * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link
+ * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation
+ * to system defaults. Defaults to {@code "none"}.
*/
- public NewPageOptions setForcedColors(ForcedColors forcedColors) {
- this.forcedColors = forcedColors;
+ public NewPageOptions setForcedColors(@Nullable ForcedColors forcedColors) {
+ this.forcedColors = Optional.ofNullable(forcedColors);
return this;
}
public NewPageOptions setGeolocation(double latitude, double longitude) {
@@ -774,25 +1017,45 @@ public NewPageOptions setGeolocation(Geolocation geolocation) {
return this;
}
/**
- * Specifies if viewport supports touch events. Defaults to false.
+ * Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.
*/
public NewPageOptions setHasTouch(boolean hasTouch) {
this.hasTouch = hasTouch;
return this;
}
/**
- * Credentials for HTTP authentication.
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
*/
public NewPageOptions setHttpCredentials(String username, String password) {
return setHttpCredentials(new HttpCredentials(username, password));
}
/**
- * Credentials for HTTP authentication.
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
*/
public NewPageOptions setHttpCredentials(HttpCredentials httpCredentials) {
this.httpCredentials = httpCredentials;
return this;
}
+ /**
+ * Credentials for HTTP authentication. If
+ * no origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ *
+ *
Pass an array to use different credentials for different origins. The first entry that matches the request origin is
+ * used, and entries with no origin match any request.
+ */
+ public NewPageOptions setHttpCredentials(List httpCredentials) {
+ this.httpCredentials = httpCredentials;
+ return this;
+ }
/**
* Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}.
*/
@@ -801,76 +1064,75 @@ public NewPageOptions setIgnoreHTTPSErrors(boolean ignoreHTTPSErrors) {
return this;
}
/**
- * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. Defaults to {@code false}. Not supported
- * in Firefox.
+ * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. isMobile is a part of device,
+ * so you don't actually need to set it manually. Defaults to {@code false}. Learn more about mobile emulation.
*/
public NewPageOptions setIsMobile(boolean isMobile) {
this.isMobile = isMobile;
return this;
}
/**
- * Whether or not to enable JavaScript in the context. Defaults to {@code true}.
+ * Whether or not to enable JavaScript in the context. Defaults to {@code true}. Learn more about disabling JavaScript.
*/
public NewPageOptions setJavaScriptEnabled(boolean javaScriptEnabled) {
this.javaScriptEnabled = javaScriptEnabled;
return this;
}
/**
- * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value, {@code Accept-Language}
- * request header value as well as number and date formatting rules.
+ * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value,
+ * {@code Accept-Language} request header value as well as number and date formatting rules. Defaults to the system default
+ * locale. Learn more about emulation in our emulation guide.
*/
public NewPageOptions setLocale(String locale) {
this.locale = locale;
return this;
}
/**
- * Whether to emulate network being offline. Defaults to {@code false}.
+ * Whether to emulate network being offline. Defaults to {@code false}. Learn more about network emulation.
*/
public NewPageOptions setOffline(boolean offline) {
this.offline = offline;
return this;
}
/**
- * A list of permissions to grant to all pages in this context. See {@link BrowserContext#grantPermissions
- * BrowserContext.grantPermissions()} for more details.
+ * A list of permissions to grant to all pages in this context. See {@link
+ * com.microsoft.playwright.BrowserContext#grantPermissions BrowserContext.grantPermissions()} for more details. Defaults
+ * to none.
*/
public NewPageOptions setPermissions(List permissions) {
this.permissions = permissions;
return this;
}
/**
- * Network proxy settings to use with this context.
- *
- *
NOTE: 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' } })}.
+ * Network proxy settings to use with this context. Defaults to none.
*/
public NewPageOptions setProxy(String server) {
return setProxy(new Proxy(server));
}
/**
- * Network proxy settings to use with this context.
- *
- *
NOTE: 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' } })}.
+ * Network proxy settings to use with this context. Defaults to none.
*/
public NewPageOptions setProxy(Proxy proxy) {
this.proxy = proxy;
return this;
}
/**
- * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach}
- * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file.
- * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
+ * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If
+ * {@code attach} is specified, resources are persisted as separate files and all of these files are archived along with
+ * the HAR file. Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
*/
public NewPageOptions setRecordHarContent(HarContentPolicy recordHarContent) {
this.recordHarContent = recordHarContent;
return this;
}
/**
- * 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}.
+ * 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}.
*/
public NewPageOptions setRecordHarMode(HarMode recordHarMode) {
this.recordHarMode = recordHarMode;
@@ -885,8 +1147,8 @@ public NewPageOptions setRecordHarOmitContent(boolean recordHarOmitContent) {
}
/**
* Enables HAR recording for all pages into the specified HAR
- * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link BrowserContext#close
- * BrowserContext.close()} for the HAR to be saved.
+ * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link
+ * com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for the HAR to be saved.
*/
public NewPageOptions setRecordHarPath(Path recordHarPath) {
this.recordHarPath = recordHarPath;
@@ -902,47 +1164,56 @@ public NewPageOptions setRecordHarUrlFilter(Pattern recordHarUrlFilter) {
}
/**
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
- * to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
+ * to call {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for videos to be saved.
*/
public NewPageOptions setRecordVideoDir(Path recordVideoDir) {
this.recordVideoDir = recordVideoDir;
return this;
}
+ /**
+ * Frame rate of the recorded videos in frames per second. Defaults to {@code 25}. Firefox and WebKit currently capture up
+ * to 25 frames per second.
+ */
+ public NewPageOptions setRecordVideoFps(int recordVideoFps) {
+ this.recordVideoFps = recordVideoFps;
+ return this;
+ }
/**
* Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into
- * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each page will
- * be scaled down if necessary to fit the specified size.
+ * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each
+ * page will be scaled down if necessary to fit the specified size.
*/
public NewPageOptions setRecordVideoSize(int width, int height) {
return setRecordVideoSize(new RecordVideoSize(width, height));
}
/**
* Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into
- * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each page will
- * be scaled down if necessary to fit the specified size.
+ * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each
+ * page will be scaled down if necessary to fit the specified size.
*/
public NewPageOptions setRecordVideoSize(RecordVideoSize recordVideoSize) {
this.recordVideoSize = recordVideoSize;
return this;
}
/**
- * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}. See {@link
- * Page#emulateMedia Page.emulateMedia()} for more details. Defaults to {@code "no-preference"}.
+ * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}.
+ * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets
+ * emulation to system defaults. Defaults to {@code "no-preference"}.
*/
- public NewPageOptions setReducedMotion(ReducedMotion reducedMotion) {
- this.reducedMotion = reducedMotion;
+ public NewPageOptions setReducedMotion(@Nullable ReducedMotion reducedMotion) {
+ this.reducedMotion = Optional.ofNullable(reducedMotion);
return this;
}
/**
- * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code viewport}
- * is set.
+ * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code
+ * viewport} is set.
*/
public NewPageOptions setScreenSize(int width, int height) {
return setScreenSize(new ScreenSize(width, height));
}
/**
- * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code viewport}
- * is set.
+ * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code
+ * viewport} is set.
*/
public NewPageOptions setScreenSize(ScreenSize screenSize) {
this.screenSize = screenSize;
@@ -951,8 +1222,8 @@ public NewPageOptions setScreenSize(ScreenSize screenSize) {
/**
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
*
{@code "block"}: Playwright will block all registration of Service Workers.
*
*/
@@ -962,7 +1233,7 @@ public NewPageOptions setServiceWorkers(ServiceWorkerPolicy serviceWorkers) {
}
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}.
*/
public NewPageOptions setStorageState(String storageState) {
this.storageState = storageState;
@@ -970,17 +1241,18 @@ public NewPageOptions setStorageState(String storageState) {
}
/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
- * obtained via {@link BrowserContext#storageState BrowserContext.storageState()}. Path to the file with saved storage
- * state.
+ * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the
+ * file with saved storage state.
*/
public NewPageOptions setStorageStatePath(Path storageStatePath) {
this.storageStatePath = storageStatePath;
return this;
}
/**
- * If specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
- * that imply single target DOM element will throw when more than one element matches the selector. See {@code Locator} to learn
- * more about the strict mode.
+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
+ * that imply single target DOM element will throw when more than one element matches the selector. This option does not
+ * affect any Locator APIs (Locators are always strict). Defaults to {@code false}. See {@code Locator} to learn more about
+ * the strict mode.
*/
public NewPageOptions setStrictSelectors(boolean strictSelectors) {
this.strictSelectors = strictSelectors;
@@ -989,7 +1261,7 @@ public NewPageOptions setStrictSelectors(boolean strictSelectors) {
/**
* Changes the timezone of the context. See ICU's
- * metaZones.txt for a list of supported timezone IDs.
+ * metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.
*/
public NewPageOptions setTimezoneId(String timezoneId) {
this.timezoneId = timezoneId;
@@ -1003,32 +1275,80 @@ public NewPageOptions setUserAgent(String userAgent) {
return this;
}
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. {@code null} disables the default viewport.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent
+ * viewport emulation. Learn more about viewport
+ * emulation.
+ *
+ *
NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the
+ * operating system. It makes the execution of the tests non-deterministic.
*/
public NewPageOptions setViewportSize(int width, int height) {
return setViewportSize(new ViewportSize(width, height));
}
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. {@code null} disables the default viewport.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent
+ * viewport emulation. Learn more about viewport
+ * emulation.
+ *
+ *
NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the
+ * operating system. It makes the execution of the tests non-deterministic.
*/
- public NewPageOptions setViewportSize(ViewportSize viewportSize) {
+ public NewPageOptions setViewportSize(@Nullable ViewportSize viewportSize) {
this.viewportSize = Optional.ofNullable(viewportSize);
return this;
}
}
+ class BindOptions {
+ /**
+ * Host to bind the web socket server to. When specified, a web socket server is created instead of a named pipe.
+ */
+ public @Nullable String host;
+ /**
+ * Port to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. Use
+ * {@code 0} to let the OS pick an available port.
+ */
+ public @Nullable Integer port;
+ /**
+ * Working directory associated with this browser server.
+ */
+ public @Nullable String workspaceDir;
+
+ /**
+ * Host to bind the web socket server to. When specified, a web socket server is created instead of a named pipe.
+ */
+ public BindOptions setHost(String host) {
+ this.host = host;
+ return this;
+ }
+ /**
+ * Port to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. Use
+ * {@code 0} to let the OS pick an available port.
+ */
+ public BindOptions setPort(int port) {
+ this.port = port;
+ return this;
+ }
+ /**
+ * Working directory associated with this browser server.
+ */
+ public BindOptions setWorkspaceDir(String workspaceDir) {
+ this.workspaceDir = workspaceDir;
+ return this;
+ }
+ }
class StartTracingOptions {
/**
* specify custom categories to use instead of default.
*/
- public List categories;
+ public @Nullable List categories;
/**
* A path to write the trace file to.
*/
- public Path path;
+ public @Nullable Path path;
/**
* captures screenshots in the trace.
*/
- public Boolean screenshots;
+ public @Nullable Boolean screenshots;
/**
* specify custom categories to use instead of default.
@@ -1054,55 +1374,97 @@ public StartTracingOptions setScreenshots(boolean screenshots) {
}
/**
* Get the browser type (chromium, firefox or webkit) that the browser belongs to.
+ *
+ * @since v1.23
*/
BrowserType browserType();
/**
- * In case this browser is obtained using {@link BrowserType#launch BrowserType.launch()}, closes the browser and all of
- * its pages (if any were opened).
+ * In case this browser is obtained using {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}, closes
+ * the browser and all of its pages (if any were opened).
+ *
+ *
In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the
+ * browser server.
+ *
+ *
NOTE: This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close events, call
+ * {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} on any {@code BrowserContext} instances you
+ * explicitly created earlier using {@link com.microsoft.playwright.Browser#newContext Browser.newContext()} **before**
+ * calling {@link com.microsoft.playwright.Browser#close Browser.close()}.
+ *
+ *
The {@code Browser} object itself is considered to be disposed and cannot be used anymore.
+ *
+ * @since v1.8
+ */
+ default void close() {
+ close(null);
+ }
+ /**
+ * In case this browser is obtained using {@link com.microsoft.playwright.BrowserType#launch BrowserType.launch()}, closes
+ * the browser and all of its pages (if any were opened).
*
*
In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the
* browser server.
*
- *
NOTE: This is similar to force quitting the browser. Therefore, you should call {@link BrowserContext#close
- * BrowserContext.close()} on any {@code BrowserContext}'s you explicitly created earlier with {@link Browser#newContext
- * Browser.newContext()} **before** calling {@link Browser#close Browser.close()}.
+ *
NOTE: This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close events, call
+ * {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} on any {@code BrowserContext} instances you
+ * explicitly created earlier using {@link com.microsoft.playwright.Browser#newContext Browser.newContext()} **before**
+ * calling {@link com.microsoft.playwright.Browser#close Browser.close()}.
*
*
The {@code Browser} object itself is considered to be disposed and cannot be used anymore.
+ *
+ * @since v1.8
*/
- void close();
+ void close(@Nullable CloseOptions options);
/**
* Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
+ *
+ *
+ *
+ * @since v1.8
*/
List contexts();
/**
* Indicates that the browser is connected.
+ *
+ * @since v1.8
*/
boolean isConnected();
+ /**
+ * NOTE: CDP Sessions are only supported on Chromium-based browsers.
+ *
+ *
Returns the newly created browser session.
+ *
+ * @since v1.11
+ */
+ CDPSession newBrowserCDPSession();
/**
* Creates a new browser context. It won't share cookies/cache with other browser contexts.
*
- *
NOTE: If directly using this method to create {@code BrowserContext}s, it is best practice to explicitly close the returned context
- * via {@link BrowserContext#close BrowserContext.close()} when your code is done with the {@code BrowserContext}, and before
- * calling {@link Browser#close Browser.close()}. This will ensure the {@code context} is closed gracefully and any
- * artifacts—like HARs and videos—are fully flushed and saved.
+ *
NOTE: If directly using this method to create {@code BrowserContext}s, it is best practice to explicitly close the returned
+ * context via {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} when your code is done with the
+ * {@code BrowserContext}, and before calling {@link com.microsoft.playwright.Browser#close Browser.close()}. This will
+ * ensure the {@code context} is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved.
+ *
+ *
Usage
*
{@code
* Browser browser = playwright.firefox().launch(); // Or 'chromium' or 'webkit'.
* // Create a new incognito browser context.
* BrowserContext context = browser.newContext();
* // Create a new page in a pristine context.
* Page page = context.newPage();
- * page.navigate('https://example.com');
+ * page.navigate("https://example.com");
*
* // Graceful close up everything
* context.close();
* browser.close();
* }
+ *
+ * @since v1.8
*/
default BrowserContext newContext() {
return newContext(null);
@@ -1110,30 +1472,37 @@ default BrowserContext newContext() {
/**
* Creates a new browser context. It won't share cookies/cache with other browser contexts.
*
- *
NOTE: If directly using this method to create {@code BrowserContext}s, it is best practice to explicitly close the returned context
- * via {@link BrowserContext#close BrowserContext.close()} when your code is done with the {@code BrowserContext}, and before
- * calling {@link Browser#close Browser.close()}. This will ensure the {@code context} is closed gracefully and any
- * artifacts—like HARs and videos—are fully flushed and saved.
+ *
NOTE: If directly using this method to create {@code BrowserContext}s, it is best practice to explicitly close the returned
+ * context via {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} when your code is done with the
+ * {@code BrowserContext}, and before calling {@link com.microsoft.playwright.Browser#close Browser.close()}. This will
+ * ensure the {@code context} is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved.
+ *
+ *
Usage
*
{@code
* Browser browser = playwright.firefox().launch(); // Or 'chromium' or 'webkit'.
* // Create a new incognito browser context.
* BrowserContext context = browser.newContext();
* // Create a new page in a pristine context.
* Page page = context.newPage();
- * page.navigate('https://example.com');
+ * page.navigate("https://example.com");
*
* // Graceful close up everything
* context.close();
* browser.close();
* }
+ *
+ * @since v1.8
*/
- BrowserContext newContext(NewContextOptions options);
+ BrowserContext newContext(@Nullable NewContextOptions options);
/**
* Creates a new page in a new browser context. Closing this page will close the context as well.
*
*
This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and
- * testing frameworks should explicitly create {@link Browser#newContext Browser.newContext()} followed by the {@link
- * BrowserContext#newPage BrowserContext.newPage()} to control their exact life times.
+ * testing frameworks should explicitly create {@link com.microsoft.playwright.Browser#newContext Browser.newContext()}
+ * followed by the {@link com.microsoft.playwright.BrowserContext#newPage BrowserContext.newPage()} to control their exact
+ * life times.
+ *
+ * @since v1.8
*/
default Page newPage() {
return newPage(null);
@@ -1142,28 +1511,51 @@ default Page newPage() {
* Creates a new page in a new browser context. Closing this page will close the context as well.
*
*
This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and
- * testing frameworks should explicitly create {@link Browser#newContext Browser.newContext()} followed by the {@link
- * BrowserContext#newPage BrowserContext.newPage()} to control their exact life times.
+ * testing frameworks should explicitly create {@link com.microsoft.playwright.Browser#newContext Browser.newContext()}
+ * followed by the {@link com.microsoft.playwright.BrowserContext#newPage BrowserContext.newPage()} to control their exact
+ * life times.
+ *
+ * @since v1.8
+ */
+ Page newPage(@Nullable NewPageOptions options);
+ /**
+ * Binds the browser to a named pipe or web socket, making it available for other clients to connect to.
+ *
+ * @param title Title of the browser server, used for identification.
+ * @since v1.59
+ */
+ default BindResult bind(String title) {
+ return bind(title, null);
+ }
+ /**
+ * Binds the browser to a named pipe or web socket, making it available for other clients to connect to.
+ *
+ * @param title Title of the browser server, used for identification.
+ * @since v1.59
*/
- Page newPage(NewPageOptions options);
+ BindResult bind(String title, @Nullable BindOptions options);
/**
* NOTE: This API controls Chromium Tracing
* which is a low-level chromium-specific debugging tool. API to control Playwright Tracing could be found here.
*
- *
You can use {@link Browser#startTracing Browser.startTracing()} and {@link Browser#stopTracing Browser.stopTracing()} to
- * create a trace file that can be opened in Chrome DevTools performance panel.
+ *
You can use {@link com.microsoft.playwright.Browser#startTracing Browser.startTracing()} and {@link
+ * com.microsoft.playwright.Browser#stopTracing Browser.stopTracing()} to create a trace file that can be opened in Chrome
+ * DevTools performance panel.
+ *
+ *
*
* @param page Optional, if specified, tracing includes screenshots of the given page.
+ * @since v1.11
*/
- default void startTracing(Page page) {
+ default void startTracing(@Nullable Page page) {
startTracing(page, null);
}
/**
@@ -1172,14 +1564,19 @@ default void startTracing(Page page) {
* href="https://playwright.dev/java/docs/trace-viewer">Playwright Tracing could be found here.
*
- *
You can use {@link Browser#startTracing Browser.startTracing()} and {@link Browser#stopTracing Browser.stopTracing()} to
- * create a trace file that can be opened in Chrome DevTools performance panel.
+ *
You can use {@link com.microsoft.playwright.Browser#startTracing Browser.startTracing()} and {@link
+ * com.microsoft.playwright.Browser#stopTracing Browser.stopTracing()} to create a trace file that can be opened in Chrome
+ * DevTools performance panel.
+ *
+ *
+ *
+ * @since v1.11
*/
default void startTracing() {
startTracing(null);
@@ -1190,18 +1587,22 @@ default void startTracing() {
* href="https://playwright.dev/java/docs/trace-viewer">Playwright Tracing could be found here.
*
- *
You can use {@link Browser#startTracing Browser.startTracing()} and {@link Browser#stopTracing Browser.stopTracing()} to
- * create a trace file that can be opened in Chrome DevTools performance panel.
+ *
You can use {@link com.microsoft.playwright.Browser#startTracing Browser.startTracing()} and {@link
+ * com.microsoft.playwright.Browser#stopTracing Browser.stopTracing()} to create a trace file that can be opened in Chrome
+ * DevTools performance panel.
+ *
+ *
*
* @param page Optional, if specified, tracing includes screenshots of the given page.
+ * @since v1.11
*/
- void startTracing(Page page, StartTracingOptions options);
+ void startTracing(@Nullable Page page, @Nullable StartTracingOptions options);
/**
* NOTE: This API controls Chromium Tracing
* which is a low-level chromium-specific debugging tool. API to control here.
*
*
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.
*
- *
Playwright allows creating "incognito" browser contexts with {@link Browser#newContext Browser.newContext()} method.
- * "Incognito" browser contexts don't write any browsing data to disk.
+ *
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.
*
{@code
* // Create a new incognito browser context
* BrowserContext context = browser.newContext();
@@ -43,12 +46,21 @@
*/
public interface BrowserContext extends AutoCloseable {
+ /**
+ * @deprecated Background pages have been removed from Chromium together with Manifest V2 extensions.
+ */
+ void onBackgroundPage(Consumer handler);
+ /**
+ * Removes handler that was previously added with {@link #onBackgroundPage onBackgroundPage(handler)}.
+ */
+ void offBackgroundPage(Consumer handler);
+
/**
* Emitted when Browser context gets closed. This might happen because of one of the following:
*
*
Browser context is closed.
*
Browser application is closed or crashed.
- *
The {@link Browser#close Browser.close()} method was called.
+ *
The {@link com.microsoft.playwright.Browser#close Browser.close()} method was called.
*
*/
void onClose(Consumer handler);
@@ -58,22 +70,124 @@ public interface BrowserContext extends AutoCloseable {
void offClose(Consumer handler);
/**
- * The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will
- * also fire for popup pages. See also {@link Page#onPopup Page.onPopup()} to receive events about popups relevant to a
+ * Emitted when JavaScript within the page calls one of console API methods, e.g. {@code console.log} or {@code
+ * console.dir}.
+ *
+ *
The arguments passed into {@code console.log} and the page are available on the {@code ConsoleMessage} event handler
+ * argument.
+ *
+ *
+ */
+ void onConsoleMessage(Consumer handler);
+ /**
+ * Removes handler that was previously added with {@link #onConsoleMessage onConsoleMessage(handler)}.
+ */
+ void offConsoleMessage(Consumer handler);
+
+ /**
+ * Emitted when a JavaScript dialog appears, such as {@code alert}, {@code prompt}, {@code confirm} or {@code
+ * beforeunload}. Listener **must** either {@link com.microsoft.playwright.Dialog#accept Dialog.accept()} or {@link
+ * com.microsoft.playwright.Dialog#dismiss Dialog.dismiss()} the dialog - otherwise the page will freeze waiting for the
+ * dialog, and actions like click will never finish.
+ *
+ *
NOTE: When no {@link com.microsoft.playwright.Page#onDialog Page.onDialog()} or {@link
+ * com.microsoft.playwright.BrowserContext#onDialog BrowserContext.onDialog()} listeners are present, all dialogs are
+ * automatically dismissed.
+ */
+ void onDialog(Consumer