mirror of
https://github.com/microsoft/playwright-cli.git
synced 2026-09-14 19:59:39 +08:00
Compare commits
94 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d5f54db786 | |||
| 50112f2489 | |||
| b56effcc38 | |||
| 6f442ce36c | |||
| bc16472032 | |||
| f50b043e23 | |||
| d409d659fd | |||
| 9a2ef83e98 | |||
| bd9098520e | |||
| a7ab322867 | |||
| e8047b4537 | |||
| 1bec2d3407 | |||
| 47748ac6da | |||
| 928ed88ca6 | |||
| 85e57228a6 | |||
| a4e83525f9 | |||
| f6e12059e6 | |||
| fa627130bc | |||
| 8f44f58cd2 | |||
| a12be9f139 | |||
| cc2453ca61 | |||
| e4f8ca945d | |||
| b38c120d45 | |||
| 70e0163d40 | |||
| 2d2e804fa3 | |||
| b3e6ab8f71 | |||
| 2a7746ebb2 | |||
| f449ecf9a3 | |||
| e68ebc769a | |||
| a4238dafa6 | |||
| 7a75b45aa9 | |||
| 1bf8492925 | |||
| c8b97974ec | |||
| aa7d0f8771 | |||
| 7e1fbf5980 | |||
| d6a8703a34 | |||
| b274301b10 | |||
| 0e6b779da5 | |||
| 0e446c24ea | |||
| 9eb0e09067 | |||
| 54dc65fa7f | |||
| 5fe3a60ea1 | |||
| 439c7235f2 | |||
| 69e847d4b5 | |||
| 0427d7b5bb | |||
| fe2da88604 | |||
| 11a02e287c | |||
| fa17f7e5ea | |||
| b3d926d425 | |||
| 0adabe0a95 | |||
| 941e0046a3 | |||
| f35db74640 | |||
| b646c13fe8 | |||
| 4368180516 | |||
| 5993a4ae2a | |||
| abd805114a | |||
| 05ce2068b8 | |||
| ff102b87de | |||
| 2a164338d3 | |||
| 602d4bb9a8 | |||
| a98b2d69eb | |||
| 10eeedc527 | |||
| 8728fe1230 | |||
| 10aa24adf3 | |||
| 14edce8d9a | |||
| d92b934a11 | |||
| 8698ae19c5 | |||
| 27ea019980 | |||
| db85f56a86 | |||
| fc407de3d7 | |||
| 8267c4aed9 | |||
| ea48d31fef | |||
| 308b583cbb | |||
| 8538203e74 | |||
| ee431a3c92 | |||
| 4df84b20c7 | |||
| 481af71f71 | |||
| 453b93cb5a | |||
| eb12021b5d | |||
| 214a7cab22 | |||
| 659dc7ab23 | |||
| a87ef72372 | |||
| be74b393eb | |||
| b9a3cdee8a | |||
| 44980ef3d5 | |||
| 7b129aa780 | |||
| 3ac367e595 | |||
| beeee56b2c | |||
| 64580c80cc | |||
| 0f79f41fe2 | |||
| c69827bc29 | |||
| b277c58ecf | |||
| 56a2e8b5de | |||
| d655d9ad20 |
@@ -1,141 +0,0 @@
|
||||
# Publishes @playwright/cli via ESRP. Manual trigger only, regular publishing
|
||||
# is done from GitHub Actions, see .github/workflows/publish.yml.
|
||||
# Depending on the selected ref, a manual run publishes:
|
||||
# - @next (alpha with current timestamp) from main
|
||||
# - @latest from v* release tags
|
||||
trigger: none
|
||||
|
||||
pr: none
|
||||
|
||||
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:
|
||||
# SDL tools require windows, see https://aka.ms/AAo6v8e
|
||||
name: DevDivPlaywrightAzurePipelinesWindows2022
|
||||
os: windows
|
||||
stages:
|
||||
- stage: Stage
|
||||
jobs:
|
||||
- job: Build
|
||||
displayName: "Build npm package"
|
||||
templateContext:
|
||||
outputs:
|
||||
- output: pipelineArtifact
|
||||
path: $(Build.ArtifactStagingDirectory)/esrp-build
|
||||
artifact: esrp-build
|
||||
steps:
|
||||
- checkout: self
|
||||
displayName: "Checkout code"
|
||||
|
||||
- task: Bash@3
|
||||
displayName: "Check the branch is main or a v* tag"
|
||||
inputs:
|
||||
targetType: "inline"
|
||||
script: |
|
||||
if [[ "$BUILD_SOURCE_BRANCH" != "refs/heads/main" && "$BUILD_SOURCE_BRANCH" != refs/tags/v* ]]; then
|
||||
echo "Can only publish from main or v* tags."
|
||||
echo "Unexpected branch: $BUILD_SOURCE_BRANCH"
|
||||
exit 1
|
||||
fi
|
||||
env:
|
||||
BUILD_SOURCE_BRANCH: $(Build.SourceBranch)
|
||||
|
||||
- task: UseNode@1
|
||||
inputs:
|
||||
version: '24.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
|
||||
|
||||
- script: npm ci
|
||||
displayName: "npm ci"
|
||||
|
||||
- task: Bash@3
|
||||
name: setVersion
|
||||
displayName: "Set version and dist-tag"
|
||||
inputs:
|
||||
targetType: "inline"
|
||||
script: |
|
||||
set -e
|
||||
BASE_VERSION=$(node -p "require('./package.json').version.split('-')[0]")
|
||||
if [[ "$BUILD_SOURCE_BRANCH" == refs/tags/v* ]]; then
|
||||
# Release version is already checked in, only publish what the tag points at.
|
||||
NPM_DIST_TAG="latest"
|
||||
if [[ "$BUILD_SOURCE_BRANCH" != "refs/tags/v$BASE_VERSION" ]]; then
|
||||
echo "ERROR: version '$BASE_VERSION' does not match tag '$BUILD_SOURCE_BRANCH'"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
NPM_DIST_TAG="next"
|
||||
npm version "${BASE_VERSION}-alpha-$(date +%s)000" --no-git-tag-version
|
||||
fi
|
||||
echo "Publishing version $(node -p "require('./package.json').version") with dist-tag $NPM_DIST_TAG"
|
||||
echo "##vso[task.setvariable variable=npmDistTag;isOutput=true]$NPM_DIST_TAG"
|
||||
env:
|
||||
BUILD_SOURCE_BRANCH: $(Build.SourceBranch)
|
||||
|
||||
- task: Bash@3
|
||||
displayName: "Pack the package"
|
||||
inputs:
|
||||
targetType: "inline"
|
||||
script: |
|
||||
set -e
|
||||
mkdir -p "$(Build.ArtifactStagingDirectory)/esrp-build"
|
||||
npm pack --pack-destination="$(Build.ArtifactStagingDirectory)/esrp-build"
|
||||
ls -la "$(Build.ArtifactStagingDirectory)/esrp-build"
|
||||
|
||||
- job: Publish
|
||||
displayName: "ESRP Release to npm"
|
||||
dependsOn: Build
|
||||
variables:
|
||||
npmDistTag: $[ dependencies.Build.outputs['setVersion.npmDistTag'] ]
|
||||
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: 'npm'
|
||||
# npm dist-tag to publish with.
|
||||
productstate: '$(npmDistTag)'
|
||||
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 npm'
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: dev
|
||||
description: Development workflows for the playwright-cli repository. Use when the user asks about rolling dependencies, releasing, or other repo maintenance tasks.
|
||||
---
|
||||
|
||||
# Development skills
|
||||
|
||||
* **Rolling Playwright dependency** [roll.md](roll.md)
|
||||
* **Preparing Release** [release.md](release.md)
|
||||
@@ -1,77 +0,0 @@
|
||||
# How to prepare a release
|
||||
|
||||
A release is a `chore: mark v<next-patch>` commit whose PR body is the release notes. Example: https://github.com/microsoft/playwright-cli/pull/367.
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Bump the patch version** in `package.json` (e.g. `0.1.7` → `0.1.8`), then `npm install` to sync `package-lock.json`. This is the entry point — everything else (branch name, PR title, release notes filename) keys off the new version.
|
||||
|
||||
2. **Find the baseline.** The previous release is the last `chore: mark v...` commit on `main`. Read the Playwright version pinned at that commit — that's the baseline for the diff.
|
||||
```bash
|
||||
git log --oneline | grep "mark v" | head -1
|
||||
git show <sha>:package.json | grep '"playwright"'
|
||||
```
|
||||
|
||||
3. **Figure out the playwright commit window.** Convert the baseline's alpha timestamp to a UTC date, and use the new alpha's date as the upper bound. Alphas are either `1.X.0-alpha-<ms-epoch>` or `1.X.0-alpha-<YYYY-MM-DD>`.
|
||||
```bash
|
||||
date -u -d @<seconds> '+%Y-%m-%d %H:%M:%S UTC' # for ms-epoch, divide by 1000 first
|
||||
```
|
||||
|
||||
4. **List Playwright commits in the window.** Run from `~/code/playwright` (a local Playwright checkout). `--after` / `--before` work on any ref regardless of what `origin/main` currently points at; `--since` / `--until` can silently return empty if the branch is behind.
|
||||
```bash
|
||||
cd ~/code/playwright && git log --after='<baseline-date>' --before='<new-date>' --pretty=format:'%h %ci %s'
|
||||
```
|
||||
|
||||
5. **Filter to CLI-relevant commits.** Keep anything touching the CLI surface or its runtime; drop internal/unrelated churn.
|
||||
- **Keep:** `src/tools/cli-client/**`, `src/tools/cli-daemon/**`, `src/tools/mcp/**`, `remote/playwrightConnection`, CDP-attach paths, tracing/video APIs the CLI exposes, and anything with a `fix(cli)` / `feat(cli)` / `fix(mcp)` / `feat(mcp)` prefix.
|
||||
- **Drop:** test-runner rolls, firefox/chromium/webkit version bumps, docs-only, test infra, unrelated refactors.
|
||||
- Use `git show --stat <sha>` to sanity-check whether a commit's files touch the CLI.
|
||||
|
||||
6. **Pull issue context for each kept PR.** The PR's linked issue often has better user-facing wording than the PR/commit title.
|
||||
```bash
|
||||
gh pr view <pr> --repo microsoft/playwright --json title,body,closingIssuesReferences
|
||||
gh issue view <issue> --repo microsoft/playwright-cli --json title,body,state
|
||||
```
|
||||
|
||||
7. **Write the release notes** to `RELEASE_NOTES_v<version>.md`. Use this exact shape — **no top-level `#` header**, the PR title is the heading:
|
||||
|
||||
```markdown
|
||||
## Highlights
|
||||
|
||||
- **<issue wording, not commit wording>** ([#<issue>](https://github.com/microsoft/playwright-cli/issues/<issue>)) — one sentence on the user-facing effect. ([microsoft/playwright#<pr>](https://github.com/microsoft/playwright/pull/<pr>))
|
||||
|
||||
## Fixes
|
||||
|
||||
- `<commit subject>` — what changed and why it matters. ([#<pr>](https://github.com/microsoft/playwright/pull/<pr>))
|
||||
|
||||
## Upgrading
|
||||
|
||||
```bash
|
||||
npm install -g @playwright/cli@<version>
|
||||
```
|
||||
```
|
||||
|
||||
Wording rules:
|
||||
- **Highlights lead with the user-reported problem from the linked issue**, not the commit subject. Drop internal terms (`cdpPort`, `tombstones`) from highlight bullets.
|
||||
- Only list things that change user-visible behavior. Skip internal cleanups unless they have a user-facing effect.
|
||||
- Reference both the playwright-cli issue (if any) and the microsoft/playwright PR.
|
||||
|
||||
8. **Commit, push, open PR.** The PR body is the contents of the release notes file (no `#` header, no filename).
|
||||
```bash
|
||||
git checkout -b mark-v<version>
|
||||
git add package.json package-lock.json
|
||||
git commit -m "chore: mark v<version>"
|
||||
git push -u origin mark-v<version>
|
||||
gh pr create --repo microsoft/playwright-cli \
|
||||
--head pavelfeldman:mark-v<version> \
|
||||
--base main \
|
||||
--title "chore: mark v<version>" \
|
||||
--body "$(cat RELEASE_NOTES_v<version>.md)"
|
||||
```
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **Don't use `--since` / `--until`** when diffing Playwright — if `origin/main` in the local checkout is behind, they return empty. `--after` / `--before` against the local ref work.
|
||||
- **Don't include a `# playwright-cli vX.Y.Z` header** in the PR body — GitHub already renders the PR title.
|
||||
- **Don't paraphrase the commit subject as the highlight.** A user who filed an issue described the pain; reuse their framing.
|
||||
- **Don't include test-runner / browser-version-roll commits** in release notes — they're noise for CLI users.
|
||||
@@ -1,47 +0,0 @@
|
||||
# How to roll Playwright dependency
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Obtain latest Playwright version**
|
||||
`npm info playwright@next version`
|
||||
|
||||
2. **Update Playwright packages** in `package.json`:
|
||||
- Update `playwright` and `playwright-core` (dependencies) and `@playwright/test` (devDependency) to the target version.
|
||||
- Run `npm install` to update `package-lock.json`.
|
||||
- Verify with `npm ls playwright-core` that the root `playwright-core` actually rolled — it is pinned directly in `package.json` and is what `playwright-cli.js` runs; forgetting it leaves the CLI on the old version while tests pass against the new `@playwright/test`.
|
||||
|
||||
3. **Run the update script** to sync skills and README:
|
||||
```bash
|
||||
node scripts/update.js
|
||||
```
|
||||
This script:
|
||||
- Runs `node playwright-cli.js install --skills` to regenerate skills from the new Playwright version.
|
||||
- Copies the generated skills from `.claude/skills/playwright-cli/` into `skills/playwright-cli/`.
|
||||
- Cleans up the generated `.claude/skills/` directory.
|
||||
|
||||
3. **Update README.md** with relevant changes from the updated skill at `skills/playwright-cli/SKILL.md`. Compare the skill file with the README and update any sections that are out of date (commands, flags, default behaviors, examples).
|
||||
|
||||
4. **Verify** the CLI works:
|
||||
```bash
|
||||
node playwright-cli.js --help
|
||||
```
|
||||
|
||||
5. **Test** the CLI:
|
||||
```bash
|
||||
npm run test
|
||||
```
|
||||
|
||||
5. **Create a branch and commit**:
|
||||
- Branch name: `roll_<version>` (e.g. `roll_214`)
|
||||
- Commit message: `chore: roll Playwright to <version>`
|
||||
- do not add Co-Authored-By
|
||||
|
||||
## Key files
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `package.json` | Playwright version pins (`playwright`, `@playwright/test`) |
|
||||
| `playwright-cli.js` | CLI entry point — requires Playwright's program module |
|
||||
| `scripts/update.js` | Automation script for syncing skills and README after version bump |
|
||||
| `skills/playwright-cli/SKILL.md` | Skill definition installed from Playwright (source of truth for commands) |
|
||||
| `README.md` | User-facing docs — must reflect current skill commands and behavior |
|
||||
@@ -1,11 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
groups:
|
||||
github-actions:
|
||||
patterns: ["*"]
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
cooldown:
|
||||
default-days: 7
|
||||
+19
-14
@@ -1,26 +1,31 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
branches: [ master ]
|
||||
jobs:
|
||||
test:
|
||||
build:
|
||||
name: Build
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-15, windows-latest]
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Use Node.js 20
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
- name: Install dependencies
|
||||
node-version: 10.17
|
||||
- uses: microsoft/playwright-github-action@v1
|
||||
- name: install
|
||||
run: npm ci
|
||||
- name: Run tests
|
||||
run: npm run test
|
||||
- name: build
|
||||
run: npm run build
|
||||
- name: test (Linux)
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: xvfb-run npm run test -- --forbid-only --timeout=30000 --retries=3 --global-timeout=1200000 --retries=3
|
||||
- name: test
|
||||
if: matrix.os != 'ubuntu-latest'
|
||||
run: npm run test -- --forbid-only --timeout=30000 --retries=3 --global-timeout=1200000 --retries=3
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
name: Publish
|
||||
name: "publish"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
publish-npm:
|
||||
if: github.event_name == 'release'
|
||||
publish-npm-release:
|
||||
name: "publish to NPM"
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # Required for OIDC npm publishing
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: 24
|
||||
registry-url: https://registry.npmjs.org/
|
||||
- run: npm ci
|
||||
- run: npm publish
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12.x
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
- uses: microsoft/playwright-github-action@v1
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- run: npm publish
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
+5
-9
@@ -1,9 +1,5 @@
|
||||
node_modules/
|
||||
.vscode/
|
||||
/test-results/
|
||||
/.playwright-cli/
|
||||
# Ignore self-skill which is a build artifact
|
||||
.claude/skills/playwright-cli/
|
||||
.npmrc
|
||||
# Playwright CLI output (may contain credentials)
|
||||
.playwright-cli/
|
||||
/node_modules/
|
||||
/src/generated/*
|
||||
/lib/
|
||||
*.swp
|
||||
.vscode
|
||||
|
||||
+2
-5
@@ -1,6 +1,3 @@
|
||||
**/*
|
||||
!README.md
|
||||
!LICENSE
|
||||
!playwright-cli.js
|
||||
!skillCheck.js
|
||||
!skills/**
|
||||
!/index.js
|
||||
!/lib/**/*.js
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
## 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 <changed-files>
|
||||
git commit -m "$(cat <<'EOF'
|
||||
fix(proxy): handle SOCKS proxy authentication
|
||||
|
||||
Fixes: https://github.com/microsoft/playwright/issues/39562
|
||||
EOF
|
||||
)"
|
||||
git push origin fix-39562
|
||||
gh pr create --repo microsoft/playwright --head username:fix-39562 \
|
||||
--title "fix(proxy): handle SOCKS proxy authentication" \
|
||||
--body "$(cat <<'EOF'
|
||||
## Summary
|
||||
- <describe the change very! briefly>
|
||||
|
||||
Fixes https://github.com/microsoft/playwright/issues/39562
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
Never add Co-Authored-By agents in commit message.
|
||||
Branch naming for issue fixes: `fix-<issue-number>`
|
||||
@@ -0,0 +1,9 @@
|
||||
# Microsoft Open Source Code of Conduct
|
||||
|
||||
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
|
||||
|
||||
Resources:
|
||||
|
||||
- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
|
||||
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
|
||||
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
|
||||
@@ -1,45 +0,0 @@
|
||||
# Contributing
|
||||
|
||||
[Playwright CLI sources](https://github.com/microsoft/playwright/tree/main/packages/playwright/src/mcp/terminal) are located in the [Playwright monorepo](https://github.com/microsoft/playwright).
|
||||
|
||||
### Clone
|
||||
|
||||
```bash
|
||||
git clone https://github.com/microsoft/playwright
|
||||
cd playwright
|
||||
npm i
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
npm run watch
|
||||
```
|
||||
|
||||
### Run
|
||||
|
||||
```bash
|
||||
npm run playwright-cli open example.com -- --headed
|
||||
```
|
||||
|
||||
### Test
|
||||
|
||||
```bash
|
||||
npm run test-playwright-cli
|
||||
```
|
||||
|
||||
## Contributor License Agreement
|
||||
|
||||
This project welcomes contributions and suggestions. Most contributions require you to agree to a
|
||||
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
|
||||
the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
|
||||
|
||||
When you submit a pull request, a CLA bot will automatically determine whether you need to provide
|
||||
a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions
|
||||
provided by the bot. You will only need to do this once across all repos using our CLA.
|
||||
|
||||
### Code of Conduct
|
||||
|
||||
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
|
||||
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
|
||||
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
|
||||
@@ -1,201 +1,202 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Portions Copyright (c) Microsoft Corporation.
|
||||
Portions Copyright 2017 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
@@ -1,579 +1,140 @@
|
||||
# playwright-cli
|
||||
# 🎭 Playwright CLI [](https://www.npmjs.com/package/playwright-cli) [](https://join.slack.com/t/playwright/shared_invite/enQtOTEyMTUxMzgxMjIwLThjMDUxZmIyNTRiMTJjNjIyMzdmZDA3MTQxZWUwZTFjZjQwNGYxZGM5MzRmNzZlMWI5ZWUyOTkzMjE5Njg1NDg)
|
||||
|
||||
Playwright CLI with SKILLS
|
||||
Playwright CLI is utility tool for [Playwright](https://github.com/Microsoft/playwright). With the CLI, you can:
|
||||
|
||||
### Playwright CLI vs Playwright MCP
|
||||
* [Generate code](#generate-code): Record user interactions and generate Playwright scripts.
|
||||
* [Open pages](#open-pages): Open pages in Chromium, Firefox and WebKit (Safari) on all platforms.
|
||||
* Emulate [devices](#emulate-devices), [color schemes](#emulate-color-scheme-and-viewport-size) and [geolocation](#emulate-geolocation-language-and-timezone).
|
||||
* [Inspect selectors](#inspect-selectors): Use the Playwright DevTools API to inspect selectors.
|
||||
* Generate [page screenshots](#take-screenshot) and [PDFs](#generate-pdf)
|
||||
|
||||
This package provides CLI interface into Playwright. If you are using **coding agents**, that is the best fit.
|
||||
## Usage
|
||||
|
||||
- **CLI**: Modern **coding agents** increasingly favor CLI–based workflows exposed as SKILLs over MCP because CLI invocations are more token-efficient: they avoid loading large tool schemas and verbose accessibility trees into the model context, allowing agents to act through concise, purpose-built commands. This makes CLI + SKILLs better suited for high-throughput coding agents that must balance browser automation with large codebases, tests, and reasoning within limited context windows.
|
||||
```sh
|
||||
$ npx playwright-cli --help
|
||||
|
||||
- **MCP**: MCP remains relevant for specialized agentic loops that benefit from persistent state, rich introspection, and iterative reasoning over page structure, such as exploratory automation, self-healing tests, or long-running autonomous workflows where maintaining continuous browser context outweighs token cost concerns. Learn more about [Playwright MCP](https://github.com/microsoft/playwright-mcp).
|
||||
|
||||
### Key Features
|
||||
|
||||
- **Token-efficient**. Does not force page data into LLM.
|
||||
|
||||
### Requirements
|
||||
- Node.js 18 or newer
|
||||
- Claude Code, GitHub Copilot, or any other coding agent.
|
||||
|
||||
## Getting Started
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install -g @playwright/cli@latest
|
||||
playwright-cli --help
|
||||
# To save as a dependency
|
||||
$ npm install -D playwright-cli
|
||||
```
|
||||
|
||||
### Installing skills
|
||||
## Generate code
|
||||
|
||||
Claude Code, GitHub Copilot and others will use the locally installed skills.
|
||||
|
||||
```bash
|
||||
playwright-cli install --skills
|
||||
```sh
|
||||
$ npx playwright-cli codegen wikipedia.org
|
||||
```
|
||||
|
||||
### Skills-less operation
|
||||
Run `codegen` and perform actions in the browser. Playwright CLI will generate JavaScript code for the user interactions. `codegen` will attempt to generate resilient text-based selectors.
|
||||
|
||||
Point your agent at the CLI and let it cook. It'll read the skill off `playwright-cli --help` on its own:
|
||||
<img src="https://user-images.githubusercontent.com/284612/92536033-7e7ebe00-f1ed-11ea-9e1a-7cbd912e3391.gif">
|
||||
|
||||
```
|
||||
Test the "add todo" flow on https://demo.playwright.dev/todomvc using playwright-cli.
|
||||
Check playwright-cli --help for available commands.
|
||||
## Open pages
|
||||
|
||||
With `open`, you can use Playwright bundled browsers to browse web pages. Playwright provides cross-platform WebKit builds that can be used to reproduce Safari rendering across Windows, Linux and macOS.
|
||||
|
||||
```sh
|
||||
# Open page in Chromium
|
||||
npx playwright-cli open example.com
|
||||
```
|
||||
|
||||
## Demo
|
||||
|
||||
```
|
||||
> Use playwright skills to test https://demo.playwright.dev/todomvc/.
|
||||
Take screenshots for all successful and failing scenarios.
|
||||
```sh
|
||||
# Open page in WebKit
|
||||
npx playwright-cli wk example.com
|
||||
```
|
||||
|
||||
Your agent will be running commands, but it does not mean you can't play with it manually:
|
||||
### Emulate devices
|
||||
`open` can emulate mobile and tablet devices ([see all devices](https://github.com/microsoft/playwright/blob/master/src/server/deviceDescriptors.ts)).
|
||||
|
||||
```
|
||||
playwright-cli open https://demo.playwright.dev/todomvc/ --headed
|
||||
playwright-cli type "Buy groceries"
|
||||
playwright-cli press Enter
|
||||
playwright-cli type "Water flowers"
|
||||
playwright-cli press Enter
|
||||
playwright-cli check e21
|
||||
playwright-cli check e35
|
||||
playwright-cli screenshot
|
||||
```sh
|
||||
# Emulate iPhone 11.
|
||||
npx playwright-cli --device="iPhone 11" open wikipedia.org
|
||||
```
|
||||
|
||||
## Headed operation
|
||||
|
||||
Playwright CLI is headless by default. If you'd like to see the browser, pass `--headed` to `open`:
|
||||
|
||||
```bash
|
||||
playwright-cli open https://playwright.dev --headed
|
||||
### Emulate color scheme and viewport size
|
||||
```sh
|
||||
# Emulate screen size and color scheme.
|
||||
npx playwright-cli --viewport-size=800,600 --color-scheme=dark open twitter.com
|
||||
```
|
||||
|
||||
## Sessions
|
||||
|
||||
Playwright CLI keeps the browser profile in memory by default. Your cookies and storage state
|
||||
are preserved between CLI calls within the session, but lost when the browser closes. Use
|
||||
`--persistent` to save the profile to disk for persistence across browser restarts.
|
||||
|
||||
You can use different instances of the browser for different projects with sessions. Pass `-s=` to
|
||||
the invocation to talk to a specific browser.
|
||||
|
||||
```bash
|
||||
playwright-cli open https://playwright.dev
|
||||
playwright-cli -s=example open https://example.com --persistent
|
||||
playwright-cli list
|
||||
### Emulate geolocation, language and timezone
|
||||
```sh
|
||||
# Emulate timezone, language & location
|
||||
# Once page opens, click the "my location" button to see geolocation in action
|
||||
npx playwright-cli --timezone="Europe/Rome" --geolocation="41.890221,12.492348" --lang="it-IT" open maps.google.com
|
||||
```
|
||||
|
||||
You can run your coding agent with the `PLAYWRIGHT_CLI_SESSION` environment variable:
|
||||
## Inspect selectors
|
||||
During `open` or `codegen`, you can use following API inside the developer tools console of any browser.
|
||||
|
||||
```bash
|
||||
PLAYWRIGHT_CLI_SESSION=todo-app claude .
|
||||
<img src="https://user-images.githubusercontent.com/284612/92536317-37dd9380-f1ee-11ea-875d-daf1b206dd56.png">
|
||||
|
||||
#### playwright.$(selector)
|
||||
|
||||
Query Playwright selector, using the actual Playwright query engine, for example:
|
||||
|
||||
```js
|
||||
> playwright.$('.auth-form >> text=Log in');
|
||||
|
||||
<button>Log in</button>
|
||||
```
|
||||
|
||||
Or instruct it to prepend `-s=` to the calls.
|
||||
#### playwright.$$(selector)
|
||||
|
||||
Manage your sessions as follows:
|
||||
Same as `playwright.$`, but returns all matching elements.
|
||||
|
||||
```bash
|
||||
playwright-cli list # list all sessions
|
||||
playwright-cli close-all # close all browsers
|
||||
playwright-cli kill-all # forcefully kill all browser processes
|
||||
```js
|
||||
> playwright.$$('li >> text=John')
|
||||
|
||||
> [<li>, <li>, <li>, <li>]
|
||||
```
|
||||
|
||||
## Monitoring
|
||||
#### playwright.inspect(selector)
|
||||
|
||||
Use `playwright-cli show` to open a visual dashboard that lets you see and control all running
|
||||
browser sessions. This is useful when your coding agents are running browser automation in the
|
||||
background and you want to observe their progress or step in to help.
|
||||
Reveal element in the Elements panel (if DevTools of the respective browser supports it).
|
||||
|
||||
```bash
|
||||
playwright-cli show
|
||||
```js
|
||||
> playwright.inspect('text=Log in')
|
||||
```
|
||||
|
||||
<img width="1107" height="729" alt="Image" src="https://github.com/user-attachments/assets/99df739d-106a-4520-b004-bb315db41da7" />
|
||||
#### playwright.selector(element)
|
||||
|
||||
The dashboard opens a window with two views:
|
||||
Generates selector for the given element.
|
||||
|
||||
- **Session grid** — shows all active sessions grouped by workspace, each with a live screencast
|
||||
preview, session name, current URL, and page title. Click any session to zoom in.
|
||||
- **Session detail** — shows a live view of the selected session with a tab bar, navigation
|
||||
controls (back, forward, reload, address bar), and full remote control. Click into the viewport
|
||||
to take over mouse and keyboard input; press Escape to release.
|
||||
```js
|
||||
> playwright.selector($0)
|
||||
|
||||
From the grid you can also close running sessions or delete data for inactive ones.
|
||||
|
||||
## Commands
|
||||
|
||||
### Core
|
||||
|
||||
```bash
|
||||
playwright-cli open [url] # open browser, optionally navigate to url
|
||||
playwright-cli goto <url> # navigate to a url
|
||||
playwright-cli close # close the page
|
||||
playwright-cli type <text> # type text into editable element
|
||||
playwright-cli click <ref> [button] # perform click on a web page
|
||||
playwright-cli dblclick <ref> [button] # perform double click on a web page
|
||||
playwright-cli fill <ref> <text> # fill text into editable element
|
||||
playwright-cli fill <ref> <text> --submit # fill and press Enter
|
||||
playwright-cli drag <startRef> <endRef> # perform drag and drop between two elements
|
||||
playwright-cli drop <ref> --path=<file> # drop files onto an element (from outside the page)
|
||||
playwright-cli drop <ref> --data="k=v" # drop data onto an element
|
||||
playwright-cli hover <ref> # hover over element on page
|
||||
playwright-cli select <ref> <val> # select an option in a dropdown
|
||||
playwright-cli upload <file> # upload one or multiple files
|
||||
playwright-cli check <ref> # check a checkbox or radio button
|
||||
playwright-cli uncheck <ref> # uncheck a checkbox or radio button
|
||||
playwright-cli snapshot # capture page snapshot to obtain element ref
|
||||
playwright-cli snapshot --filename=f # save snapshot to specific file
|
||||
playwright-cli snapshot <ref> # snapshot a specific element
|
||||
playwright-cli snapshot --depth=N # limit snapshot depth for efficiency
|
||||
playwright-cli find <text> # search the snapshot for text, returns matching nodes
|
||||
playwright-cli find --regex <pattern> # search the snapshot with a regexp
|
||||
playwright-cli eval <func> [ref] # evaluate javascript expression on page or element
|
||||
playwright-cli dialog-accept [prompt] # accept a dialog
|
||||
playwright-cli dialog-dismiss # dismiss a dialog
|
||||
playwright-cli resize <w> <h> # resize the browser window
|
||||
"div[id="glow-ingress-block"] >> text=/.*Hello.*/"
|
||||
```
|
||||
|
||||
### Navigation
|
||||
## Take screenshot
|
||||
|
||||
```bash
|
||||
playwright-cli go-back # go back to the previous page
|
||||
playwright-cli go-forward # go forward to the next page
|
||||
playwright-cli reload # reload the current page
|
||||
```sh
|
||||
# See command help
|
||||
$ npx playwright-cli screenshot --help
|
||||
```
|
||||
|
||||
### Keyboard
|
||||
|
||||
```bash
|
||||
playwright-cli press <key> # press a key on the keyboard, `a`, `arrowleft`
|
||||
playwright-cli keydown <key> # press a key down on the keyboard
|
||||
playwright-cli keyup <key> # press a key up on the keyboard
|
||||
```sh
|
||||
# Wait 3 seconds before capturing a screenshot after page loads ('load' event fires)
|
||||
npx playwright-cli \
|
||||
--device="iPhone 11" \
|
||||
--color-scheme=dark \
|
||||
screenshot \
|
||||
--wait-for-timeout=3000 \
|
||||
twitter.com twitter-iphone.png
|
||||
```
|
||||
|
||||
### Mouse
|
||||
|
||||
```bash
|
||||
playwright-cli mousemove <x> <y> # move mouse to a given position
|
||||
playwright-cli mousedown [button] # press mouse down
|
||||
playwright-cli mouseup [button] # press mouse up
|
||||
playwright-cli mousewheel <dx> <dy> # scroll mouse wheel
|
||||
```sh
|
||||
# Capture a full page screenshot
|
||||
npx playwright-cli screenshot --full-page en.wikipedia.org wiki-full.png
|
||||
```
|
||||
|
||||
### Save as
|
||||
## Generate PDF
|
||||
|
||||
```bash
|
||||
playwright-cli screenshot [ref] # screenshot of the current page or element
|
||||
playwright-cli screenshot --filename=f # save screenshot with specific filename
|
||||
playwright-cli screenshot --hires # capture at full device pixel ratio
|
||||
playwright-cli pdf # save page as pdf
|
||||
playwright-cli pdf --filename=page.pdf # save pdf with specific filename
|
||||
PDF generation only works in Headless Chromium.
|
||||
|
||||
```sh
|
||||
# See command help
|
||||
$ npx playwright-cli pdf https://en.wikipedia.org/wiki/PDF wiki.pdf
|
||||
```
|
||||
|
||||
### Tabs
|
||||
|
||||
```bash
|
||||
playwright-cli tab-list # list all tabs
|
||||
playwright-cli tab-new [url] # create a new tab
|
||||
playwright-cli tab-close [index] # close a browser tab
|
||||
playwright-cli tab-select <index> # select a browser tab
|
||||
```
|
||||
|
||||
### Storage
|
||||
|
||||
```bash
|
||||
playwright-cli state-save [filename] # save storage state
|
||||
playwright-cli state-load <filename> # load storage state
|
||||
|
||||
# Cookies
|
||||
playwright-cli cookie-list [--domain] # list cookies
|
||||
playwright-cli cookie-get <name> # get a cookie
|
||||
playwright-cli cookie-set <name> <val> # set a cookie
|
||||
playwright-cli cookie-delete <name> # delete a cookie
|
||||
playwright-cli cookie-clear # clear all cookies
|
||||
|
||||
# LocalStorage
|
||||
playwright-cli localstorage-list # list localStorage entries
|
||||
playwright-cli localstorage-get <key> # get localStorage value
|
||||
playwright-cli localstorage-set <k> <v> # set localStorage value
|
||||
playwright-cli localstorage-delete <k> # delete localStorage entry
|
||||
playwright-cli localstorage-clear # clear all localStorage
|
||||
|
||||
# SessionStorage
|
||||
playwright-cli sessionstorage-list # list sessionStorage entries
|
||||
playwright-cli sessionstorage-get <k> # get sessionStorage value
|
||||
playwright-cli sessionstorage-set <k> <v> # set sessionStorage value
|
||||
playwright-cli sessionstorage-delete <k> # delete sessionStorage entry
|
||||
playwright-cli sessionstorage-clear # clear all sessionStorage
|
||||
```
|
||||
|
||||
### Network
|
||||
|
||||
```bash
|
||||
playwright-cli route <pattern> [opts] # mock network requests
|
||||
playwright-cli route-list # list active routes
|
||||
playwright-cli unroute [pattern] # remove route(s)
|
||||
```
|
||||
|
||||
### DevTools
|
||||
|
||||
```bash
|
||||
playwright-cli console [min-level] # list console messages
|
||||
playwright-cli requests # list all network requests since loading the page
|
||||
playwright-cli request <index> # show details for a specific request
|
||||
playwright-cli run-code <code> # run playwright code snippet
|
||||
playwright-cli run-code --filename=f # run playwright code from a file
|
||||
playwright-cli tracing-start # start trace recording
|
||||
playwright-cli tracing-stop # stop trace recording
|
||||
playwright-cli recording-start # record user actions in the browser
|
||||
playwright-cli recording-stop # stop recording, print actions as Playwright code
|
||||
playwright-cli video-start [filename] # start video recording
|
||||
playwright-cli video-chapter <title> # add a chapter marker to the video
|
||||
playwright-cli video-show-actions # annotate each action with a callout in the video
|
||||
playwright-cli video-hide-actions # stop annotating actions in the video
|
||||
playwright-cli video-stop # stop video recording
|
||||
playwright-cli show # open the visual dashboard
|
||||
playwright-cli show --annotate # launch dashboard for UI review / design feedback
|
||||
playwright-cli generate-locator <ref> # generate a playwright locator for an element
|
||||
playwright-cli highlight <ref> # show a persistent highlight overlay
|
||||
playwright-cli highlight <ref> --style= # highlight with a custom CSS style
|
||||
playwright-cli highlight <ref> --hide # hide highlight on a specific element
|
||||
playwright-cli highlight --hide # hide all page highlights
|
||||
```
|
||||
|
||||
### Open parameters
|
||||
|
||||
```bash
|
||||
playwright-cli open --browser=chrome # use specific browser
|
||||
playwright-cli open --mobile # emulate a generic mobile device
|
||||
playwright-cli open --device="iPhone 15" # emulate a specific device
|
||||
playwright-cli attach --extension=chrome # connect via Playwright Extension
|
||||
playwright-cli attach --cdp=chrome # attach to running Chrome/Edge by channel
|
||||
playwright-cli attach --cdp=<url> # attach via CDP endpoint
|
||||
playwright-cli detach # detach an attached session, leaves the external browser running
|
||||
playwright-cli open --persistent # use persistent profile
|
||||
playwright-cli open --profile=<path> # use custom profile directory
|
||||
playwright-cli open --config=file.json # use config file
|
||||
playwright-cli close # close the browser
|
||||
playwright-cli delete-data # delete user data for default session
|
||||
```
|
||||
|
||||
### Snapshots
|
||||
|
||||
After each command, playwright-cli provides a snapshot of the current browser state.
|
||||
|
||||
```bash
|
||||
> playwright-cli goto https://example.com
|
||||
### Page
|
||||
- Page URL: https://example.com/
|
||||
- Page Title: Example Domain
|
||||
### Snapshot
|
||||
[Snapshot](.playwright-cli/page-2026-02-14T19-22-42-679Z.yml)
|
||||
```
|
||||
|
||||
You can also take a snapshot on demand using `playwright-cli snapshot` command. All the options below can be combined as needed.
|
||||
|
||||
```bash
|
||||
# default - save to a file with timestamp-based name
|
||||
playwright-cli snapshot
|
||||
|
||||
# save to file, use when snapshot is a part of the workflow result
|
||||
playwright-cli snapshot --filename=after-click.yaml
|
||||
|
||||
# snapshot an element instead of the whole page
|
||||
playwright-cli snapshot "#main"
|
||||
|
||||
# limit snapshot depth for efficiency, take a partial snapshot afterwards
|
||||
playwright-cli snapshot --depth=4
|
||||
playwright-cli snapshot e34
|
||||
|
||||
# include each element's bounding box as [box=x,y,width,height]
|
||||
playwright-cli snapshot --boxes
|
||||
|
||||
# search a large snapshot instead of capturing it all — returns matching nodes
|
||||
# with 3 lines of context around each match (like grep -C)
|
||||
playwright-cli find "Add to cart"
|
||||
playwright-cli find --regex "\\$[0-9]+\\.[0-9]{2}"
|
||||
# wrap the regexp in slashes to add flags, e.g. /i for case-insensitive
|
||||
playwright-cli find --regex "/sign (in|up)/i"
|
||||
```
|
||||
|
||||
### Targeting elements
|
||||
|
||||
By default, use refs from the snapshot to interact with page elements.
|
||||
|
||||
```bash
|
||||
# get snapshot with refs
|
||||
playwright-cli snapshot
|
||||
|
||||
# interact using a ref
|
||||
playwright-cli click e15
|
||||
```
|
||||
|
||||
You can also use css selectors or Playwright locators.
|
||||
|
||||
```bash
|
||||
# css selector
|
||||
playwright-cli click "#main > button.submit"
|
||||
|
||||
# role locator
|
||||
playwright-cli click "getByRole('button', { name: 'Submit' })"
|
||||
|
||||
# test id
|
||||
playwright-cli click "getByTestId('submit-button')"
|
||||
```
|
||||
|
||||
### Sessions
|
||||
|
||||
```bash
|
||||
playwright-cli -s=name <cmd> # run command in named session
|
||||
playwright-cli -s=name close # stop a named browser
|
||||
playwright-cli -s=name delete-data # delete user data for named browser
|
||||
playwright-cli list # list all sessions
|
||||
playwright-cli close-all # close all browsers
|
||||
playwright-cli kill-all # forcefully kill all browser processes
|
||||
```
|
||||
|
||||
### Local installation
|
||||
|
||||
If global `playwright-cli` command is not available, try a local version via `npx playwright cli`:
|
||||
|
||||
```bash
|
||||
npx --no-install playwright --version
|
||||
```
|
||||
|
||||
When local version is available, use `npx playwright cli` in all commands. Otherwise, install `playwright-cli` as a global command:
|
||||
|
||||
```bash
|
||||
npm install -g @playwright/cli@latest
|
||||
```
|
||||
|
||||
## Configuration file
|
||||
|
||||
The Playwright CLI can be configured using a JSON configuration file. You can specify the configuration file using the `--config` command line option:
|
||||
|
||||
```bash
|
||||
playwright-cli --config path/to/config.json open example.com
|
||||
```
|
||||
|
||||
Playwright CLI will load config from `.playwright/cli.config.json` by default so that you did not need to specify it every time.
|
||||
|
||||
<details>
|
||||
<summary>Configuration file schema</summary>
|
||||
|
||||
```typescript
|
||||
{
|
||||
/**
|
||||
* The browser to use.
|
||||
*/
|
||||
browser?: {
|
||||
/**
|
||||
* The type of browser to use.
|
||||
*/
|
||||
browserName?: 'chromium' | 'firefox' | 'webkit';
|
||||
|
||||
/**
|
||||
* Keep the browser profile in memory, do not save it to disk.
|
||||
*/
|
||||
isolated?: boolean;
|
||||
|
||||
/**
|
||||
* Path to a user data directory for browser profile persistence.
|
||||
* Temporary directory is created by default.
|
||||
*/
|
||||
userDataDir?: string;
|
||||
|
||||
/**
|
||||
* Launch options passed to
|
||||
* @see https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context
|
||||
*
|
||||
* This is useful for settings options like `channel`, `headless`, `executablePath`, etc.
|
||||
*/
|
||||
launchOptions?: playwright.LaunchOptions;
|
||||
|
||||
/**
|
||||
* Context options for the browser context.
|
||||
*
|
||||
* This is useful for settings options like `viewport`.
|
||||
*/
|
||||
contextOptions?: playwright.BrowserContextOptions;
|
||||
|
||||
/**
|
||||
* Chrome DevTools Protocol endpoint to connect to an existing browser instance in case of Chromium family browsers.
|
||||
*/
|
||||
cdpEndpoint?: string;
|
||||
|
||||
/**
|
||||
* CDP headers to send with the connect request.
|
||||
*/
|
||||
cdpHeaders?: Record<string, string>;
|
||||
|
||||
/**
|
||||
* Timeout in milliseconds for connecting to CDP endpoint. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
|
||||
*/
|
||||
cdpTimeout?: number;
|
||||
|
||||
/**
|
||||
* Remote endpoint to connect to an existing Playwright server.
|
||||
*/
|
||||
remoteEndpoint?: string;
|
||||
|
||||
/**
|
||||
* Paths to TypeScript files to add as initialization scripts for Playwright page.
|
||||
*/
|
||||
initPage?: string[];
|
||||
|
||||
/**
|
||||
* Paths to JavaScript files to add as initialization scripts.
|
||||
* The scripts will be evaluated in every page before any of the page's scripts.
|
||||
*/
|
||||
initScript?: string[];
|
||||
},
|
||||
|
||||
/**
|
||||
* If specified, saves the Playwright video of the session into the output directory.
|
||||
*/
|
||||
saveVideo?: {
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The directory to save output files.
|
||||
*/
|
||||
outputDir?: string;
|
||||
|
||||
/**
|
||||
* Whether to save snapshots, console messages, network logs and other session logs to a file or to the standard output. Defaults to "stdout".
|
||||
*/
|
||||
outputMode?: 'file' | 'stdout';
|
||||
|
||||
console?: {
|
||||
/**
|
||||
* The level of console messages to return. Each level includes the messages of more severe levels. Defaults to "info".
|
||||
*/
|
||||
level?: 'error' | 'warning' | 'info' | 'debug';
|
||||
},
|
||||
|
||||
network?: {
|
||||
/**
|
||||
* List of origins to allow the browser to request. Default is to allow all. Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.
|
||||
*/
|
||||
allowedOrigins?: string[];
|
||||
|
||||
/**
|
||||
* List of origins to block the browser to request. Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.
|
||||
*/
|
||||
blockedOrigins?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Specify the attribute to use for test ids, defaults to "data-testid".
|
||||
*/
|
||||
testIdAttribute?: string;
|
||||
|
||||
timeouts?: {
|
||||
/*
|
||||
* Configures default action timeout: https://playwright.dev/docs/api/class-page#page-set-default-timeout. Defaults to 5000ms.
|
||||
*/
|
||||
action?: number;
|
||||
|
||||
/*
|
||||
* Configures default navigation timeout: https://playwright.dev/docs/api/class-page#page-set-default-navigation-timeout. Defaults to 60000ms.
|
||||
*/
|
||||
navigation?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether to allow file uploads from anywhere on the file system.
|
||||
* By default (false), file uploads are restricted to paths within the MCP roots only.
|
||||
*/
|
||||
allowUnrestrictedFileAccess?: boolean;
|
||||
|
||||
/**
|
||||
* Specify the language to use for code generation.
|
||||
*/
|
||||
codegen?: 'typescript' | 'none';
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Configuration via env</summary>
|
||||
|
||||
| Environment |
|
||||
|-------------|
|
||||
| `PLAYWRIGHT_MCP_ALLOWED_HOSTS` comma-separated list of hosts this server is allowed to serve from. Defaults to the host the server is bound to. Pass '*' to disable the host check. |
|
||||
| `PLAYWRIGHT_MCP_ALLOWED_ORIGINS` semicolon-separated list of TRUSTED origins to allow the browser to request. Default is to allow all. Important: *does not* serve as a security boundary and *does not* affect redirects. |
|
||||
| `PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS` allow access to files outside of the workspace roots. Also allows unrestricted access to file:// URLs. By default access to file system is restricted to workspace root directories (or cwd if no roots are configured) only, and navigation to file:// URLs is blocked. |
|
||||
| `PLAYWRIGHT_MCP_BLOCKED_ORIGINS` semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed. Important: *does not* serve as a security boundary and *does not* affect redirects. |
|
||||
| `PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS` block service workers |
|
||||
| `PLAYWRIGHT_MCP_BROWSER` browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge. |
|
||||
| `PLAYWRIGHT_MCP_CAPS` comma-separated list of additional capabilities to enable, possible values: vision, pdf. |
|
||||
| `PLAYWRIGHT_MCP_CDP_ENDPOINT` CDP endpoint to connect to. |
|
||||
| `PLAYWRIGHT_MCP_CDP_HEADERS` CDP headers to send with the connect request, multiple can be specified. |
|
||||
| `PLAYWRIGHT_MCP_CDP_TIMEOUT` timeout for the CDP connection. |
|
||||
| `PLAYWRIGHT_MCP_CONFIG` path to the configuration file. |
|
||||
| `PLAYWRIGHT_MCP_CONSOLE_LEVEL` level of console messages to return: "error", "warning", "info", "debug". Each level includes the messages of more severe levels. |
|
||||
| `PLAYWRIGHT_MCP_DEVICE` device to emulate, for example: "iPhone 15" |
|
||||
| `PLAYWRIGHT_MCP_EXECUTABLE_PATH` path to the browser executable. |
|
||||
| `PLAYWRIGHT_MCP_EXTENSION` Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed. |
|
||||
| `PLAYWRIGHT_MCP_GRANT_PERMISSIONS` List of permissions to grant to the browser context, for example "geolocation", "clipboard-read", "clipboard-write". |
|
||||
| `PLAYWRIGHT_MCP_HEADLESS` whether to run browser in headless mode, headless by default. |
|
||||
| `PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS` ignore https errors |
|
||||
| `PLAYWRIGHT_MCP_INIT_PAGE` path to TypeScript file to evaluate on Playwright page object |
|
||||
| `PLAYWRIGHT_MCP_INIT_SCRIPT` path to JavaScript file to add as an initialization script. The script will be evaluated in every page before any of the page's scripts. Can be specified multiple times. |
|
||||
| `PLAYWRIGHT_MCP_ISOLATED` keep the browser profile in memory, do not save it to disk. |
|
||||
| `PLAYWRIGHT_MCP_SANDBOX` whether to enable the browser sandbox. |
|
||||
| `PLAYWRIGHT_MCP_OUTPUT_DIR` path to the directory for output files. |
|
||||
| `PLAYWRIGHT_MCP_PROXY_BYPASS` comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com" |
|
||||
| `PLAYWRIGHT_MCP_PROXY_SERVER` specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080" |
|
||||
| `PLAYWRIGHT_MCP_SAVE_TRACE` Whether to save the Playwright Trace of the session into the output directory. |
|
||||
| `PLAYWRIGHT_MCP_SAVE_VIDEO` Whether to save the video of the session into the output directory. For example "--save-video=800x600" |
|
||||
| `PLAYWRIGHT_MCP_SECRETS_FILE` path to a file containing secrets in the dotenv format |
|
||||
| `PLAYWRIGHT_MCP_STORAGE_STATE` path to the storage state file for isolated sessions. |
|
||||
| `PLAYWRIGHT_MCP_TEST_ID_ATTRIBUTE` specify the attribute to use for test ids, defaults to "data-testid" |
|
||||
| `PLAYWRIGHT_MCP_TIMEOUT_ACTION` specify action timeout in milliseconds, defaults to 5000ms |
|
||||
| `PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION` specify navigation timeout in milliseconds, defaults to 60000ms |
|
||||
| `PLAYWRIGHT_MCP_USER_AGENT` specify user agent string |
|
||||
| `PLAYWRIGHT_MCP_USER_DATA_DIR` path to the user data directory. If not specified, a temporary directory will be created. |
|
||||
| `PLAYWRIGHT_MCP_VIEWPORT_SIZE` specify browser viewport size in pixels, for example "1280x720" |
|
||||
</details>
|
||||
|
||||
## Specific tasks
|
||||
|
||||
The installed skill includes detailed reference guides for common tasks:
|
||||
|
||||
* **Running and Debugging Playwright tests** — run, debug and manage Playwright test suites
|
||||
* **Request mocking** — intercept and mock network requests
|
||||
* **Running Playwright code** — execute arbitrary Playwright scripts
|
||||
* **Browser session management** — manage multiple browser sessions
|
||||
* **Storage state (cookies, localStorage)** — persist and restore browser state
|
||||
* **Test generation (plan / generate / heal)** — generate Playwright tests from a spec or interactions
|
||||
* **Tracing** — record and inspect execution traces
|
||||
* **Video recording** — capture browser session videos
|
||||
* **Inspecting element attributes** — get element id, class, or any attribute not visible in the snapshot
|
||||
## Known limitations
|
||||
Opening WebKit Web Inspector will disconnect Playwright from the browser. In such cases, code generation will stop.
|
||||
|
||||
+34
-7
@@ -1,14 +1,41 @@
|
||||
<!-- BEGIN MICROSOFT SECURITY.MD V1.0.0 BLOCK -->
|
||||
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.5 BLOCK -->
|
||||
|
||||
## Security
|
||||
|
||||
Microsoft takes the security of our software products and services seriously, which
|
||||
includes all source code repositories in our GitHub organizations.
|
||||
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
|
||||
|
||||
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below.
|
||||
|
||||
## Reporting Security Issues
|
||||
|
||||
**Please do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
For security reporting information, locations, contact information, and policies,
|
||||
please review the latest guidance for Microsoft repositories at
|
||||
[https://aka.ms/SECURITY.md](https://aka.ms/SECURITY.md).
|
||||
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report).
|
||||
|
||||
<!-- END MICROSOFT SECURITY.MD BLOCK -->
|
||||
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc).
|
||||
|
||||
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
|
||||
|
||||
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
|
||||
|
||||
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
|
||||
* Full paths of source file(s) related to the manifestation of the issue
|
||||
* The location of the affected source code (tag/branch/commit or direct URL)
|
||||
* Any special configuration required to reproduce the issue
|
||||
* Step-by-step instructions to reproduce the issue
|
||||
* Proof-of-concept or exploit code (if possible)
|
||||
* Impact of the issue, including how an attacker might exploit the issue
|
||||
|
||||
This information will help us triage your report more quickly.
|
||||
|
||||
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs.
|
||||
|
||||
## Preferred Languages
|
||||
|
||||
We prefer all communications to be in English.
|
||||
|
||||
## Policy
|
||||
|
||||
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd).
|
||||
|
||||
<!-- END MICROSOFT SECURITY.MD BLOCK -->
|
||||
Regular → Executable
+3
-9
@@ -1,3 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
@@ -14,12 +16,4 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './tests',
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env.CI,
|
||||
workers: process.env.CI ? 2 : undefined,
|
||||
reporter: 'list',
|
||||
});
|
||||
require('./lib/cli.js');
|
||||
Generated
+6005
-75
File diff suppressed because it is too large
Load Diff
+19
-19
@@ -1,31 +1,31 @@
|
||||
{
|
||||
"name": "@playwright/cli",
|
||||
"version": "0.1.19",
|
||||
"name": "playwright-cli",
|
||||
"version": "0.5.2",
|
||||
"description": "Playwright CLI",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/microsoft/playwright-cli.git"
|
||||
},
|
||||
"repository": "github:Microsoft/playwright-cli",
|
||||
"homepage": "https://playwright.dev",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"scripts": {
|
||||
"test": "test-runner test/",
|
||||
"build": "node utils/runWebpack.js --mode='development' && tsc -p .",
|
||||
"watch": "node utils/runWebpack.js --mode='development' --watch --silent | tsc -w -p ."
|
||||
},
|
||||
"bin": {
|
||||
"playwright-cli": "./index.js"
|
||||
},
|
||||
"author": {
|
||||
"name": "Microsoft Corporation"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"scripts": {
|
||||
"test": "playwright test"
|
||||
"dependencies": {
|
||||
"commander": "^6.1.0",
|
||||
"highlight.js": "^10.1.2",
|
||||
"playwright": "~1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.63.0-alpha-2026-08-31",
|
||||
"@types/node": "^25.2.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"playwright": "1.63.0-alpha-2026-08-31",
|
||||
"playwright-core": "1.63.0-alpha-2026-08-31"
|
||||
},
|
||||
"bin": {
|
||||
"playwright-cli": "playwright-cli.js"
|
||||
"@playwright/test-runner": "^0.3.4",
|
||||
"ts-loader": "^8.0.3",
|
||||
"typescript": "^4.0.2",
|
||||
"webpack": "^4.44.1",
|
||||
"webpack-cli": "^3.3.12"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// @ts-check
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const { program } = require('playwright-core/lib/tools/cli-client/program');
|
||||
const coreBundle = require('playwright-core/lib/coreBundle');
|
||||
const { tools, registry } = coreBundle;
|
||||
const { checkInstalledSkills, frame } = require('./skillCheck');
|
||||
|
||||
const packageJson = require('./package.json');
|
||||
|
||||
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
main();
|
||||
|
||||
async function main() {
|
||||
await checkForUpdates().catch(() => {});
|
||||
program({ embedderVersion: packageJson.version });
|
||||
}
|
||||
|
||||
async function checkForUpdates() {
|
||||
if (process.env.NO_UPDATE_NOTIFIER || process.env.CI)
|
||||
return;
|
||||
|
||||
const cache = readCache();
|
||||
const stale = !cache || (Date.now() - cache.lastCheck) > ONE_DAY_MS;
|
||||
if (!stale)
|
||||
return;
|
||||
writeCache({ lastCheck: Date.now() });
|
||||
|
||||
const command = process.argv.slice(2).find(arg => !arg.startsWith('-'));
|
||||
if (command !== 'install')
|
||||
checkInstalledSkills();
|
||||
|
||||
const latest = await fetchLatestVersion();
|
||||
if (latest && tools.compareSemver(latest, packageJson.version) > 0)
|
||||
printNotice(packageJson.version, latest);
|
||||
}
|
||||
|
||||
async function fetchLatestVersion() {
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 1500);
|
||||
try {
|
||||
const res = await fetch(`https://registry.npmjs.org/${packageJson.name}/latest`, { signal: controller.signal });
|
||||
if (!res.ok)
|
||||
return undefined;
|
||||
const json = await res.json();
|
||||
return typeof json.version === 'string' ? json.version : undefined;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} current
|
||||
* @param {string} latest
|
||||
*/
|
||||
function printNotice(current, latest) {
|
||||
process.stderr.write('\n' + frame([
|
||||
`Update available for ${packageJson.name}: ${current} → ${latest}`,
|
||||
`Run \`npm install -g ${packageJson.name}@latest\` (global) or`,
|
||||
`\`npm install --save-dev ${packageJson.name}@latest\` (local) to update.`,
|
||||
]) + '\n');
|
||||
}
|
||||
|
||||
function cacheFile() {
|
||||
const dir = process.env.PLAYWRIGHT_CLI_INSTALLATION_FOR_TEST || registry.defaultRegistryDirectory();
|
||||
return path.join(dir, 'cli-update-check.json');
|
||||
}
|
||||
|
||||
function readCache() {
|
||||
const file = cacheFile();
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
if (typeof data.lastCheck === 'number')
|
||||
return data;
|
||||
} catch {
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} data
|
||||
*/
|
||||
function writeCache(data) {
|
||||
const file = cacheFile();
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, JSON.stringify(data));
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
const { execSync } = require('child_process');
|
||||
const fs = require('fs/promises');
|
||||
const path = require('path');
|
||||
|
||||
const rootDir = path.resolve(__dirname, '..');
|
||||
const skillsDir = path.join(rootDir, 'skills');
|
||||
|
||||
function run(command, options = {}) {
|
||||
console.log(`Running: ${command}`);
|
||||
execSync(command, { stdio: 'inherit', cwd: rootDir, ...options });
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// 2. Run playwright-cli install-skills
|
||||
console.log('\n=== Running playwright-cli install --skills ===\n');
|
||||
run('node playwright-cli.js install --skills');
|
||||
|
||||
// 3. Move generated skills into the existing skills folder
|
||||
console.log('\n=== Updating skills folder ===\n');
|
||||
const generatedSkillsDir = path.join(rootDir, '.claude', 'skills', 'playwright-cli');
|
||||
const targetSkillsDir = path.join(skillsDir, 'playwright-cli');
|
||||
|
||||
try {
|
||||
await fs.access(generatedSkillsDir);
|
||||
// Remove existing skills and copy new ones
|
||||
await fs.rm(targetSkillsDir, { recursive: true, force: true });
|
||||
await fs.cp(generatedSkillsDir, targetSkillsDir, { recursive: true });
|
||||
console.log(`Copied skills from ${generatedSkillsDir} to ${targetSkillsDir}`);
|
||||
|
||||
// Clean up generated skills directory
|
||||
await fs.rm(generatedSkillsDir, { recursive: true });
|
||||
console.log('Cleaned up generated skills directory');
|
||||
} catch {
|
||||
console.warn('Warning: Generated skills directory not found at', generatedSkillsDir);
|
||||
}
|
||||
console.log('\n=== Update complete! ===\n');
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,79 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// @ts-check
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function bundledSkillFile() {
|
||||
const corePath = require.resolve('playwright-core/package.json');
|
||||
return path.join(path.dirname(corePath), 'lib', 'tools', 'skills', 'playwright-cli', 'SKILL.md');
|
||||
}
|
||||
|
||||
function installedSkillTargets() {
|
||||
const cwd = process.cwd();
|
||||
return [
|
||||
{ dir: path.join(cwd, '.claude', 'skills', 'playwright-cli'), command: 'playwright-cli install --skills' },
|
||||
{ dir: path.join(cwd, '.agents', 'skills', 'playwright-cli'), command: 'playwright-cli install --skills=agents' },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} file
|
||||
* @returns
|
||||
*/
|
||||
function readSkill(file) {
|
||||
// Normalize line endings, they could be affected by git or editor settings.
|
||||
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n') : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} lines
|
||||
* @returns {string}
|
||||
*/
|
||||
function frame(lines) {
|
||||
const width = Math.max(...lines.map(line => line.length));
|
||||
const top = '╔' + '═'.repeat(width + 2) + '╗';
|
||||
const bottom = '╚' + '═'.repeat(width + 2) + '╝';
|
||||
const body = lines.map(line => `║ ${line.padEnd(width)} ║`);
|
||||
return [top, ...body, bottom].join('\n') + '\n';
|
||||
}
|
||||
|
||||
function checkInstalledSkills() {
|
||||
try {
|
||||
const bundled = readSkill(bundledSkillFile());
|
||||
if (!bundled)
|
||||
return;
|
||||
for (const target of installedSkillTargets()) {
|
||||
const installed = readSkill(path.join(target.dir, 'SKILL.md'));
|
||||
if (installed === null)
|
||||
continue;
|
||||
if (installed !== bundled) {
|
||||
process.stderr.write(frame([
|
||||
`The playwright-cli skill at '${path.relative(process.cwd(), target.dir)}'`,
|
||||
`does not match the tool version.`,
|
||||
``,
|
||||
`Run \`${target.command}\``,
|
||||
`to install the up-to-date skill.`,
|
||||
]));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { checkInstalledSkills, frame };
|
||||
@@ -1,425 +0,0 @@
|
||||
---
|
||||
name: playwright-cli
|
||||
description: Automate browser interactions, test web pages and work with Playwright tests.
|
||||
allowed-tools: Bash(playwright-cli:*) Bash(npx:*) Bash(npm:*)
|
||||
---
|
||||
|
||||
# Browser Automation with playwright-cli
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
# open new browser
|
||||
playwright-cli open
|
||||
# navigate to a page
|
||||
playwright-cli goto https://playwright.dev
|
||||
# interact with the page using refs from the snapshot
|
||||
playwright-cli click e15
|
||||
playwright-cli type "page.click"
|
||||
playwright-cli press Enter
|
||||
# take a screenshot (rarely used, as snapshot is more common)
|
||||
playwright-cli screenshot
|
||||
# close the browser
|
||||
playwright-cli close
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
### Core
|
||||
|
||||
```bash
|
||||
playwright-cli open
|
||||
# open and navigate right away
|
||||
playwright-cli open https://example.com/
|
||||
playwright-cli goto https://playwright.dev
|
||||
playwright-cli type "search query"
|
||||
playwright-cli click e3
|
||||
playwright-cli dblclick e7
|
||||
# --submit presses Enter after filling the element
|
||||
playwright-cli fill e5 "user@example.com" --submit
|
||||
playwright-cli drag e2 e8
|
||||
# drop files or data onto an element (from outside the page)
|
||||
playwright-cli drop e4 --path=./image.png
|
||||
playwright-cli drop e4 --data="text/plain=hello world"
|
||||
playwright-cli hover e4
|
||||
playwright-cli select e9 "option-value"
|
||||
playwright-cli upload ./document.pdf
|
||||
playwright-cli check e12
|
||||
playwright-cli uncheck e12
|
||||
playwright-cli snapshot
|
||||
# search the snapshot for text or a regexp, returns matching nodes with surrounding context
|
||||
playwright-cli find "Sign in"
|
||||
playwright-cli find --regex "Sign (in|up)"
|
||||
# wrap the regexp in slashes to add flags, e.g. /i for case-insensitive
|
||||
playwright-cli find --regex "/sign (in|up)/i"
|
||||
playwright-cli eval "document.title"
|
||||
playwright-cli eval "el => el.textContent" e5
|
||||
# get element id, class, or any attribute not visible in the snapshot
|
||||
playwright-cli eval "el => el.id" e5
|
||||
playwright-cli eval "el => el.getAttribute('data-testid')" e5
|
||||
playwright-cli dialog-accept
|
||||
playwright-cli dialog-accept "confirmation text"
|
||||
playwright-cli dialog-dismiss
|
||||
playwright-cli resize 1920 1080
|
||||
playwright-cli close
|
||||
```
|
||||
|
||||
### Navigation
|
||||
|
||||
```bash
|
||||
playwright-cli go-back
|
||||
playwright-cli go-forward
|
||||
playwright-cli reload
|
||||
```
|
||||
|
||||
### Keyboard
|
||||
|
||||
```bash
|
||||
playwright-cli press Enter
|
||||
playwright-cli press ArrowDown
|
||||
playwright-cli keydown Shift
|
||||
playwright-cli keyup Shift
|
||||
```
|
||||
|
||||
### Mouse
|
||||
|
||||
```bash
|
||||
playwright-cli mousemove 150 300
|
||||
playwright-cli mousedown
|
||||
playwright-cli mousedown right
|
||||
playwright-cli mouseup
|
||||
playwright-cli mouseup right
|
||||
playwright-cli mousewheel 0 100
|
||||
```
|
||||
|
||||
### Save as
|
||||
|
||||
```bash
|
||||
playwright-cli screenshot
|
||||
playwright-cli screenshot e5
|
||||
playwright-cli screenshot --filename=page.png
|
||||
playwright-cli screenshot --hires
|
||||
playwright-cli pdf --filename=page.pdf
|
||||
```
|
||||
|
||||
### Tabs
|
||||
|
||||
```bash
|
||||
playwright-cli tab-list
|
||||
playwright-cli tab-new
|
||||
playwright-cli tab-new https://example.com/page
|
||||
playwright-cli tab-close
|
||||
playwright-cli tab-close 2
|
||||
playwright-cli tab-select 0
|
||||
```
|
||||
|
||||
### Storage
|
||||
|
||||
```bash
|
||||
playwright-cli state-save
|
||||
playwright-cli state-save auth.json
|
||||
playwright-cli state-load auth.json
|
||||
|
||||
# Cookies
|
||||
playwright-cli cookie-list
|
||||
playwright-cli cookie-list --domain=example.com
|
||||
playwright-cli cookie-get session_id
|
||||
playwright-cli cookie-set session_id abc123
|
||||
playwright-cli cookie-set session_id abc123 --domain=example.com --httpOnly --secure
|
||||
playwright-cli cookie-delete session_id
|
||||
playwright-cli cookie-clear
|
||||
|
||||
# LocalStorage
|
||||
playwright-cli localstorage-list
|
||||
playwright-cli localstorage-get theme
|
||||
playwright-cli localstorage-set theme dark
|
||||
playwright-cli localstorage-delete theme
|
||||
playwright-cli localstorage-clear
|
||||
|
||||
# SessionStorage
|
||||
playwright-cli sessionstorage-list
|
||||
playwright-cli sessionstorage-get step
|
||||
playwright-cli sessionstorage-set step 3
|
||||
playwright-cli sessionstorage-delete step
|
||||
playwright-cli sessionstorage-clear
|
||||
```
|
||||
|
||||
### Network
|
||||
|
||||
```bash
|
||||
playwright-cli route "**/*.jpg" --status=404
|
||||
playwright-cli route "https://api.example.com/**" --body='{"mock": true}'
|
||||
playwright-cli route-list
|
||||
playwright-cli unroute "**/*.jpg"
|
||||
playwright-cli unroute
|
||||
```
|
||||
|
||||
### DevTools
|
||||
|
||||
```bash
|
||||
playwright-cli console
|
||||
playwright-cli console warning
|
||||
playwright-cli requests
|
||||
playwright-cli request 5
|
||||
playwright-cli run-code "async page => await page.context().grantPermissions(['geolocation'])"
|
||||
playwright-cli run-code --filename=script.js
|
||||
playwright-cli tracing-start
|
||||
playwright-cli tracing-stop
|
||||
|
||||
# record user actions in the browser, print them as Playwright code on stop
|
||||
playwright-cli recording-start
|
||||
playwright-cli recording-stop
|
||||
|
||||
playwright-cli video-start video.webm
|
||||
playwright-cli video-chapter "Chapter Title" --description="Details" --duration=2000
|
||||
playwright-cli video-stop
|
||||
|
||||
# annotate each subsequent action (click, type, ...) with a callout naming the action and highlighting the target
|
||||
playwright-cli video-show-actions --duration=600 --position=top-right
|
||||
playwright-cli video-hide-actions
|
||||
|
||||
# launch the dashboard for UI review / design feedback — user annotates the page, you receive the annotated screenshot, snapshot, and notes
|
||||
playwright-cli show --annotate
|
||||
|
||||
# generate a Playwright locator for an element from its ref or selector
|
||||
playwright-cli generate-locator e5 --raw
|
||||
|
||||
# show a persistent highlight overlay for an element, optionally with a custom style
|
||||
playwright-cli highlight e5
|
||||
playwright-cli highlight e5 --style="outline: 3px dashed red"
|
||||
# hide a single element highlight, or all page highlights when no target is given
|
||||
playwright-cli highlight e5 --hide
|
||||
playwright-cli highlight --hide
|
||||
```
|
||||
|
||||
## Raw output
|
||||
|
||||
The global `--raw` option strips page status, generated code, and snapshot sections from the output, returning only the result value. Use it to pipe command output into other tools. Commands that don't produce output return nothing.
|
||||
|
||||
```bash
|
||||
playwright-cli --raw eval "JSON.stringify(performance.timing)" | jq '.loadEventEnd - .navigationStart'
|
||||
playwright-cli --raw eval "JSON.stringify([...document.querySelectorAll('a')].map(a => a.href))" > links.json
|
||||
playwright-cli --raw snapshot > before.yml
|
||||
playwright-cli click e5
|
||||
playwright-cli --raw snapshot > after.yml
|
||||
diff before.yml after.yml
|
||||
TOKEN=$(playwright-cli --raw cookie-get session_id)
|
||||
playwright-cli --raw localstorage-get theme
|
||||
```
|
||||
|
||||
For structured output wrapping every reply as JSON, pass --json
|
||||
```bash
|
||||
playwright-cli list --json
|
||||
```
|
||||
|
||||
## Open parameters
|
||||
```bash
|
||||
# Use specific browser when creating session
|
||||
playwright-cli open --browser=chrome
|
||||
playwright-cli open --browser=firefox
|
||||
playwright-cli open --browser=webkit
|
||||
playwright-cli open --browser=msedge
|
||||
|
||||
# Emulate a generic mobile device (Pixel 10 for Chromium, iPhone 17 for WebKit).
|
||||
# Prefer this when a mobile layout is acceptable: mobile pages are usually
|
||||
# lighter, so snapshots are smaller and cheaper.
|
||||
playwright-cli open --mobile
|
||||
playwright-cli open --device="iPhone 15"
|
||||
|
||||
# Use persistent profile (by default profile is in-memory)
|
||||
playwright-cli open --persistent
|
||||
# Use persistent profile with custom directory
|
||||
playwright-cli open --profile=/path/to/profile
|
||||
|
||||
# Connect to browser via Playwright Extension
|
||||
playwright-cli attach --extension=chrome
|
||||
|
||||
# Connect to a running Chrome or Edge by channel name
|
||||
playwright-cli attach --cdp=chrome
|
||||
playwright-cli attach --cdp=msedge
|
||||
|
||||
# Connect to a running browser via CDP endpoint
|
||||
playwright-cli attach --cdp=http://localhost:9222
|
||||
|
||||
# Start with config file
|
||||
playwright-cli open --config=my-config.json
|
||||
|
||||
# Close the browser
|
||||
playwright-cli close
|
||||
# Detach from an attached browser (leaves the external browser running)
|
||||
playwright-cli -s=msedge detach
|
||||
# Delete user data for the default session
|
||||
playwright-cli delete-data
|
||||
```
|
||||
|
||||
## URLs with `&` on Windows
|
||||
|
||||
On Windows, `cmd.exe` and PowerShell treat `&` as a command separator, so URLs with multiple query parameters get truncated before `playwright-cli` runs. Escape `&` with `^&` in `cmd.exe`, or use `--%` in PowerShell:
|
||||
|
||||
```batch
|
||||
playwright-cli goto "https://example.com/?a=1^&b=2"
|
||||
```
|
||||
|
||||
```powershell
|
||||
playwright-cli --% goto "https://example.com/?a=1&b=2"
|
||||
```
|
||||
|
||||
## Snapshots
|
||||
|
||||
After each command, playwright-cli provides a snapshot of the current browser state.
|
||||
|
||||
```bash
|
||||
> playwright-cli goto https://example.com
|
||||
### Page
|
||||
- Page URL: https://example.com/
|
||||
- Page Title: Example Domain
|
||||
### Snapshot
|
||||
[Snapshot](.playwright-cli/page-2026-02-14T19-22-42-679Z.yml)
|
||||
```
|
||||
|
||||
You can also take a snapshot on demand using `playwright-cli snapshot` command. All the options below can be combined as needed.
|
||||
|
||||
```bash
|
||||
# default - save to a file with timestamp-based name
|
||||
playwright-cli snapshot
|
||||
|
||||
# save to file, use when snapshot is a part of the workflow result
|
||||
playwright-cli snapshot --filename=after-click.yaml
|
||||
|
||||
# snapshot an element instead of the whole page
|
||||
playwright-cli snapshot "#main"
|
||||
|
||||
# limit snapshot depth for efficiency, take a partial snapshot afterwards
|
||||
playwright-cli snapshot --depth=4
|
||||
playwright-cli snapshot e34
|
||||
|
||||
# include each element's bounding box as [box=x,y,width,height]
|
||||
playwright-cli snapshot --boxes
|
||||
|
||||
# search a large snapshot instead of capturing it all — returns matching nodes
|
||||
# with 3 lines of context around each match (like grep -C)
|
||||
playwright-cli find "Add to cart"
|
||||
playwright-cli find --regex "\\$[0-9]+\\.[0-9]{2}"
|
||||
```
|
||||
|
||||
## Targeting elements
|
||||
|
||||
By default, use refs from the snapshot to interact with page elements.
|
||||
|
||||
```bash
|
||||
# get snapshot with refs
|
||||
playwright-cli snapshot
|
||||
|
||||
# interact using a ref
|
||||
playwright-cli click e15
|
||||
```
|
||||
|
||||
You can also use css selectors or Playwright locators.
|
||||
|
||||
```bash
|
||||
# css selector
|
||||
playwright-cli click "#main > button.submit"
|
||||
|
||||
# role locator
|
||||
playwright-cli click "getByRole('button', { name: 'Submit' })"
|
||||
|
||||
# test id
|
||||
playwright-cli click "getByTestId('submit-button')"
|
||||
```
|
||||
|
||||
## Browser Sessions
|
||||
|
||||
```bash
|
||||
# create new browser session named "mysession" with persistent profile
|
||||
playwright-cli -s=mysession open example.com --persistent
|
||||
# same with manually specified profile directory (use when requested explicitly)
|
||||
playwright-cli -s=mysession open example.com --profile=/path/to/profile
|
||||
playwright-cli -s=mysession click e6
|
||||
playwright-cli -s=mysession close # stop a named browser
|
||||
playwright-cli -s=mysession delete-data # delete user data for persistent session
|
||||
|
||||
playwright-cli list
|
||||
# Close all browsers
|
||||
playwright-cli close-all
|
||||
# Forcefully kill all browser processes
|
||||
playwright-cli kill-all
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
If global `playwright-cli` command is not available, try a local version via `npx playwright cli`:
|
||||
|
||||
```bash
|
||||
npx --no-install playwright --version
|
||||
```
|
||||
|
||||
When local version is available, use `npx playwright cli` in all commands. Otherwise, install `playwright-cli` as a global command:
|
||||
|
||||
```bash
|
||||
npm install -g @playwright/cli@latest
|
||||
```
|
||||
|
||||
## Example: Form submission
|
||||
|
||||
```bash
|
||||
playwright-cli open https://example.com/form
|
||||
playwright-cli snapshot
|
||||
|
||||
playwright-cli fill e1 "user@example.com"
|
||||
playwright-cli fill e2 "password123"
|
||||
playwright-cli click e3
|
||||
playwright-cli snapshot
|
||||
playwright-cli close
|
||||
```
|
||||
|
||||
## Example: Multi-tab workflow
|
||||
|
||||
```bash
|
||||
playwright-cli open https://example.com
|
||||
playwright-cli tab-new https://example.com/other
|
||||
playwright-cli tab-list
|
||||
playwright-cli tab-select 0
|
||||
playwright-cli snapshot
|
||||
playwright-cli close
|
||||
```
|
||||
|
||||
## Example: Debugging with DevTools
|
||||
|
||||
```bash
|
||||
playwright-cli open https://example.com
|
||||
playwright-cli click e4
|
||||
playwright-cli fill e7 "test"
|
||||
playwright-cli console
|
||||
playwright-cli requests
|
||||
playwright-cli close
|
||||
```
|
||||
|
||||
```bash
|
||||
playwright-cli open https://example.com
|
||||
playwright-cli tracing-start
|
||||
playwright-cli click e4
|
||||
playwright-cli fill e7 "test"
|
||||
playwright-cli tracing-stop
|
||||
playwright-cli close
|
||||
```
|
||||
|
||||
## Example: Interactive session
|
||||
|
||||
Ask the user for UI review or design feedback. The user draws boxes on the live page and types comments; you receive the annotated screenshot, the snapshot of the marked region, and the user's notes. Use this whenever the user asks for "UI review", "design feedback", or to "ask the user what they think / want / mean":
|
||||
|
||||
```bash
|
||||
playwright-cli open https://example.com
|
||||
playwright-cli show --annotate
|
||||
```
|
||||
|
||||
## Specific tasks
|
||||
|
||||
* **Running and Debugging Playwright tests** [references/playwright-tests.md](references/playwright-tests.md)
|
||||
* **Request mocking** [references/request-mocking.md](references/request-mocking.md)
|
||||
* **Running Playwright code** [references/running-code.md](references/running-code.md)
|
||||
* **Browser session management** [references/session-management.md](references/session-management.md)
|
||||
* **Storage state (cookies, localStorage)** [references/storage-state.md](references/storage-state.md)
|
||||
* **Test generation (plan / generate / heal)** [references/test-generation.md](references/test-generation.md)
|
||||
* **Tracing** [references/tracing.md](references/tracing.md)
|
||||
* **Video recording** [references/video-recording.md](references/video-recording.md)
|
||||
* **Inspecting element attributes** [references/element-attributes.md](references/element-attributes.md)
|
||||
@@ -1,23 +0,0 @@
|
||||
# Inspecting Element Attributes
|
||||
|
||||
When the snapshot doesn't show an element's `id`, `class`, `data-*` attributes, or other DOM properties, use `eval` to inspect them.
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
playwright-cli snapshot
|
||||
# snapshot shows a button as e7 but doesn't reveal its id or data attributes
|
||||
|
||||
# get the element's id
|
||||
playwright-cli eval "el => el.id" e7
|
||||
|
||||
# get all CSS classes
|
||||
playwright-cli eval "el => el.className" e7
|
||||
|
||||
# get a specific attribute
|
||||
playwright-cli eval "el => el.getAttribute('data-testid')" e7
|
||||
playwright-cli eval "el => el.getAttribute('aria-label')" e7
|
||||
|
||||
# get a computed style property
|
||||
playwright-cli eval "el => getComputedStyle(el).display" e7
|
||||
```
|
||||
@@ -1,39 +0,0 @@
|
||||
# Running Playwright Tests
|
||||
|
||||
To run Playwright tests, use the `npx playwright test` command, or a package manager script. To avoid opening the interactive html report, use `PLAYWRIGHT_HTML_OPEN=never` environment variable.
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
PLAYWRIGHT_HTML_OPEN=never npx playwright test
|
||||
|
||||
# Run all tests through a custom npm script
|
||||
PLAYWRIGHT_HTML_OPEN=never npm run special-test-command
|
||||
```
|
||||
|
||||
# Debugging Playwright Tests
|
||||
|
||||
To debug a failing Playwright test, run it with `--debug=cli` option. This command will pause the test at the start and print the debugging instructions.
|
||||
|
||||
**IMPORTANT**: run the command in the background and check the output until "Debugging Instructions" is printed. Make sure to stop the command after you have finished.
|
||||
|
||||
Once instructions containing a session name are printed, use `playwright-cli` to attach the session and explore the page.
|
||||
|
||||
```bash
|
||||
# Run the test
|
||||
PLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli
|
||||
# ...
|
||||
# ... debugging instructions for "tw-abcdef" session ...
|
||||
# ...
|
||||
|
||||
# Attach to the test
|
||||
playwright-cli attach tw-abcdef
|
||||
```
|
||||
|
||||
Keep the test running in the background while you explore and look for a fix.
|
||||
The test is paused at the start, so you should step over or pause at a particular location
|
||||
where the problem is most likely to be.
|
||||
|
||||
Every action you perform with `playwright-cli` generates corresponding Playwright TypeScript code.
|
||||
This code appears in the output and can be copied directly into the test. Most of the time, a specific locator or an expectation should be updated, but it could also be a bug in the app. Use your judgement.
|
||||
|
||||
After fixing the test, stop the background test run. Rerun to check that test passes.
|
||||
@@ -1,87 +0,0 @@
|
||||
# Request Mocking
|
||||
|
||||
Intercept, mock, modify, and block network requests.
|
||||
|
||||
## CLI Route Commands
|
||||
|
||||
```bash
|
||||
# Mock with custom status
|
||||
playwright-cli route "**/*.jpg" --status=404
|
||||
|
||||
# Mock with JSON body
|
||||
playwright-cli route "**/api/users" --body='[{"id":1,"name":"Alice"}]' --content-type=application/json
|
||||
|
||||
# Mock with custom headers
|
||||
playwright-cli route "**/api/data" --body='{"ok":true}' --header="X-Custom: value"
|
||||
|
||||
# Remove headers from requests
|
||||
playwright-cli route "**/*" --remove-header=cookie,authorization
|
||||
|
||||
# List active routes
|
||||
playwright-cli route-list
|
||||
|
||||
# Remove a route or all routes
|
||||
playwright-cli unroute "**/*.jpg"
|
||||
playwright-cli unroute
|
||||
```
|
||||
|
||||
## URL Patterns
|
||||
|
||||
```
|
||||
**/api/users - Exact path match
|
||||
**/api/*/details - Wildcard in path
|
||||
**/*.{png,jpg,jpeg} - Match file extensions
|
||||
**/search?q=* - Match query parameters
|
||||
```
|
||||
|
||||
## Advanced Mocking with run-code
|
||||
|
||||
For conditional responses, request body inspection, response modification, or delays:
|
||||
|
||||
### Conditional Response Based on Request
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
await page.route('**/api/login', route => {
|
||||
const body = route.request().postDataJSON();
|
||||
if (body.username === 'admin') {
|
||||
route.fulfill({ body: JSON.stringify({ token: 'mock-token' }) });
|
||||
} else {
|
||||
route.fulfill({ status: 401, body: JSON.stringify({ error: 'Invalid' }) });
|
||||
}
|
||||
});
|
||||
}"
|
||||
```
|
||||
|
||||
### Modify Real Response
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
await page.route('**/api/user', async route => {
|
||||
const response = await route.fetch();
|
||||
const json = await response.json();
|
||||
json.isPremium = true;
|
||||
await route.fulfill({ response, json });
|
||||
});
|
||||
}"
|
||||
```
|
||||
|
||||
### Simulate Network Failures
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
await page.route('**/api/offline', route => route.abort('internetdisconnected'));
|
||||
}"
|
||||
# Options: connectionrefused, timedout, connectionreset, internetdisconnected
|
||||
```
|
||||
|
||||
### Delayed Response
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
await page.route('**/api/slow', async route => {
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
route.fulfill({ body: JSON.stringify({ data: 'loaded' }) });
|
||||
});
|
||||
}"
|
||||
```
|
||||
@@ -1,241 +0,0 @@
|
||||
# Running Custom Playwright Code
|
||||
|
||||
Use `run-code` to execute arbitrary Playwright code for advanced scenarios not covered by CLI commands.
|
||||
|
||||
## Syntax
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
// Your Playwright code here
|
||||
// Access page.context() for browser context operations
|
||||
}"
|
||||
```
|
||||
|
||||
You can also load the function from a file:
|
||||
|
||||
```bash
|
||||
playwright-cli run-code --filename=./my-script.js
|
||||
```
|
||||
|
||||
|
||||
The code must be a single function expression, it is wrapped in `(...)` and evaluated.
|
||||
import/export/require syntax is not supported.
|
||||
|
||||
## Geolocation
|
||||
|
||||
```bash
|
||||
# Grant geolocation permission and set location
|
||||
playwright-cli run-code "async page => {
|
||||
await page.context().grantPermissions(['geolocation']);
|
||||
await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
|
||||
}"
|
||||
|
||||
# Set location to London
|
||||
playwright-cli run-code "async page => {
|
||||
await page.context().grantPermissions(['geolocation']);
|
||||
await page.context().setGeolocation({ latitude: 51.5074, longitude: -0.1278 });
|
||||
}"
|
||||
|
||||
# Clear geolocation override
|
||||
playwright-cli run-code "async page => {
|
||||
await page.context().clearPermissions();
|
||||
}"
|
||||
```
|
||||
|
||||
## Permissions
|
||||
|
||||
```bash
|
||||
# Grant multiple permissions
|
||||
playwright-cli run-code "async page => {
|
||||
await page.context().grantPermissions([
|
||||
'geolocation',
|
||||
'notifications',
|
||||
'camera',
|
||||
'microphone'
|
||||
]);
|
||||
}"
|
||||
|
||||
# Grant permissions for specific origin
|
||||
playwright-cli run-code "async page => {
|
||||
await page.context().grantPermissions(['clipboard-read'], {
|
||||
origin: 'https://example.com'
|
||||
});
|
||||
}"
|
||||
```
|
||||
|
||||
## Media Emulation
|
||||
|
||||
```bash
|
||||
# Emulate dark color scheme
|
||||
playwright-cli run-code "async page => {
|
||||
await page.emulateMedia({ colorScheme: 'dark' });
|
||||
}"
|
||||
|
||||
# Emulate light color scheme
|
||||
playwright-cli run-code "async page => {
|
||||
await page.emulateMedia({ colorScheme: 'light' });
|
||||
}"
|
||||
|
||||
# Emulate reduced motion
|
||||
playwright-cli run-code "async page => {
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' });
|
||||
}"
|
||||
|
||||
# Emulate print media
|
||||
playwright-cli run-code "async page => {
|
||||
await page.emulateMedia({ media: 'print' });
|
||||
}"
|
||||
```
|
||||
|
||||
## Wait Strategies
|
||||
|
||||
```bash
|
||||
# Wait for network idle
|
||||
playwright-cli run-code "async page => {
|
||||
await page.waitForLoadState('networkidle');
|
||||
}"
|
||||
|
||||
# Wait for specific element
|
||||
playwright-cli run-code "async page => {
|
||||
await page.locator('.loading').waitFor({ state: 'hidden' });
|
||||
}"
|
||||
|
||||
# Wait for function to return true
|
||||
playwright-cli run-code "async page => {
|
||||
await page.waitForFunction(() => window.appReady === true);
|
||||
}"
|
||||
|
||||
# Wait with timeout
|
||||
playwright-cli run-code "async page => {
|
||||
await page.locator('.result').waitFor({ timeout: 10000 });
|
||||
}"
|
||||
```
|
||||
|
||||
## Frames and Iframes
|
||||
|
||||
```bash
|
||||
# Work with iframe
|
||||
playwright-cli run-code "async page => {
|
||||
const frame = page.locator('iframe#my-iframe').contentFrame();
|
||||
await frame.locator('button').click();
|
||||
}"
|
||||
|
||||
# Get all frames
|
||||
playwright-cli run-code "async page => {
|
||||
const frames = page.frames();
|
||||
return frames.map(f => f.url());
|
||||
}"
|
||||
```
|
||||
|
||||
## File Downloads
|
||||
|
||||
```bash
|
||||
# Handle file download
|
||||
playwright-cli run-code "async page => {
|
||||
const downloadPromise = page.waitForEvent('download');
|
||||
await page.getByRole('link', { name: 'Download' }).click();
|
||||
const download = await downloadPromise;
|
||||
await download.saveAs('./downloaded-file.pdf');
|
||||
return download.suggestedFilename();
|
||||
}"
|
||||
```
|
||||
|
||||
## Clipboard
|
||||
|
||||
```bash
|
||||
# Read clipboard (requires permission)
|
||||
playwright-cli run-code "async page => {
|
||||
await page.context().grantPermissions(['clipboard-read']);
|
||||
return await page.evaluate(() => navigator.clipboard.readText());
|
||||
}"
|
||||
|
||||
# Write to clipboard
|
||||
playwright-cli run-code "async page => {
|
||||
await page.evaluate(text => navigator.clipboard.writeText(text), 'Hello clipboard!');
|
||||
}"
|
||||
```
|
||||
|
||||
## Page Information
|
||||
|
||||
```bash
|
||||
# Get page title
|
||||
playwright-cli run-code "async page => {
|
||||
return await page.title();
|
||||
}"
|
||||
|
||||
# Get current URL
|
||||
playwright-cli run-code "async page => {
|
||||
return page.url();
|
||||
}"
|
||||
|
||||
# Get page content
|
||||
playwright-cli run-code "async page => {
|
||||
return await page.content();
|
||||
}"
|
||||
|
||||
# Get viewport size
|
||||
playwright-cli run-code "async page => {
|
||||
return page.viewportSize();
|
||||
}"
|
||||
```
|
||||
|
||||
## JavaScript Execution
|
||||
|
||||
```bash
|
||||
# Execute JavaScript and return result
|
||||
playwright-cli run-code "async page => {
|
||||
return await page.evaluate(() => {
|
||||
return {
|
||||
userAgent: navigator.userAgent,
|
||||
language: navigator.language,
|
||||
cookiesEnabled: navigator.cookieEnabled
|
||||
};
|
||||
});
|
||||
}"
|
||||
|
||||
# Pass arguments to evaluate
|
||||
playwright-cli run-code "async page => {
|
||||
const multiplier = 5;
|
||||
return await page.evaluate(m => document.querySelectorAll('li').length * m, multiplier);
|
||||
}"
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
```bash
|
||||
# Try-catch in run-code
|
||||
playwright-cli run-code "async page => {
|
||||
try {
|
||||
await page.getByRole('button', { name: 'Submit' }).click({ timeout: 1000 });
|
||||
return 'clicked';
|
||||
} catch (e) {
|
||||
return 'element not found';
|
||||
}
|
||||
}"
|
||||
```
|
||||
|
||||
## Complex Workflows
|
||||
|
||||
```bash
|
||||
# Login and save state
|
||||
playwright-cli run-code "async page => {
|
||||
await page.goto('https://example.com/login');
|
||||
await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
|
||||
await page.getByRole('textbox', { name: 'Password' }).fill('secret');
|
||||
await page.getByRole('button', { name: 'Sign in' }).click();
|
||||
await page.waitForURL('**/dashboard');
|
||||
await page.context().storageState({ path: 'auth.json' });
|
||||
return 'Login successful';
|
||||
}"
|
||||
|
||||
# Scrape data from multiple pages
|
||||
playwright-cli run-code "async page => {
|
||||
const results = [];
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
await page.goto(\`https://example.com/page/\${i}\`);
|
||||
const items = await page.locator('.item').allTextContents();
|
||||
results.push(...items);
|
||||
}
|
||||
return results;
|
||||
}"
|
||||
```
|
||||
@@ -1,225 +0,0 @@
|
||||
# Browser Session Management
|
||||
|
||||
Run multiple isolated browser sessions concurrently with state persistence.
|
||||
|
||||
## Named Browser Sessions
|
||||
|
||||
Use `-s` flag to isolate browser contexts:
|
||||
|
||||
```bash
|
||||
# Browser 1: Authentication flow
|
||||
playwright-cli -s=auth open https://app.example.com/login
|
||||
|
||||
# Browser 2: Public browsing (separate cookies, storage)
|
||||
playwright-cli -s=public open https://example.com
|
||||
|
||||
# Commands are isolated by browser session
|
||||
playwright-cli -s=auth fill e1 "user@example.com"
|
||||
playwright-cli -s=public snapshot
|
||||
```
|
||||
|
||||
## Browser Session Isolation Properties
|
||||
|
||||
Each browser session has independent:
|
||||
- Cookies
|
||||
- LocalStorage / SessionStorage
|
||||
- IndexedDB
|
||||
- Cache
|
||||
- Browsing history
|
||||
- Open tabs
|
||||
|
||||
## Browser Session Commands
|
||||
|
||||
```bash
|
||||
# List all browser sessions
|
||||
playwright-cli list
|
||||
|
||||
# Stop a browser session (close the browser)
|
||||
playwright-cli close # stop the default browser
|
||||
playwright-cli -s=mysession close # stop a named browser
|
||||
|
||||
# Stop all browser sessions
|
||||
playwright-cli close-all
|
||||
|
||||
# Forcefully kill all daemon processes (for stale/zombie processes)
|
||||
playwright-cli kill-all
|
||||
|
||||
# Delete browser session user data (profile directory)
|
||||
playwright-cli delete-data # delete default browser data
|
||||
playwright-cli -s=mysession delete-data # delete named browser data
|
||||
```
|
||||
|
||||
## Environment Variable
|
||||
|
||||
Set a default browser session name via environment variable:
|
||||
|
||||
```bash
|
||||
export PLAYWRIGHT_CLI_SESSION="mysession"
|
||||
playwright-cli open example.com # Uses "mysession" automatically
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Concurrent Scraping
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Scrape multiple sites concurrently
|
||||
|
||||
# Start all browsers
|
||||
playwright-cli -s=site1 open https://site1.com &
|
||||
playwright-cli -s=site2 open https://site2.com &
|
||||
playwright-cli -s=site3 open https://site3.com &
|
||||
wait
|
||||
|
||||
# Take snapshots from each
|
||||
playwright-cli -s=site1 snapshot
|
||||
playwright-cli -s=site2 snapshot
|
||||
playwright-cli -s=site3 snapshot
|
||||
|
||||
# Cleanup
|
||||
playwright-cli close-all
|
||||
```
|
||||
|
||||
### A/B Testing Sessions
|
||||
|
||||
```bash
|
||||
# Test different user experiences
|
||||
playwright-cli -s=variant-a open "https://app.com?variant=a"
|
||||
playwright-cli -s=variant-b open "https://app.com?variant=b"
|
||||
|
||||
# Compare
|
||||
playwright-cli -s=variant-a screenshot
|
||||
playwright-cli -s=variant-b screenshot
|
||||
```
|
||||
|
||||
### Persistent Profile
|
||||
|
||||
By default, browser profile is kept in memory only. Use `--persistent` flag on `open` to persist the browser profile to disk:
|
||||
|
||||
```bash
|
||||
# Use persistent profile (auto-generated location)
|
||||
playwright-cli open https://example.com --persistent
|
||||
|
||||
# Use persistent profile with custom directory
|
||||
playwright-cli open https://example.com --profile=/path/to/profile
|
||||
```
|
||||
|
||||
## Attaching to a Running Browser
|
||||
|
||||
Use `attach` to connect to a browser that is already running, instead of launching a new one.
|
||||
|
||||
### Attach by channel name
|
||||
|
||||
Connect to a running Chrome or Edge instance by its channel name. The browser must have remote debugging enabled — navigate to `chrome://inspect/#remote-debugging` in the target browser and check "Allow remote debugging for this browser instance".
|
||||
|
||||
```bash
|
||||
# Attach to Chrome
|
||||
playwright-cli attach --cdp=chrome
|
||||
|
||||
# Attach to Chrome Canary
|
||||
playwright-cli attach --cdp=chrome-canary
|
||||
|
||||
# Attach to Microsoft Edge
|
||||
playwright-cli attach --cdp=msedge
|
||||
|
||||
# Attach to Edge Dev
|
||||
playwright-cli attach --cdp=msedge-dev
|
||||
```
|
||||
|
||||
Supported channels: `chrome`, `chrome-beta`, `chrome-dev`, `chrome-canary`, `msedge`, `msedge-beta`, `msedge-dev`, `msedge-canary`.
|
||||
|
||||
When `--session` is not provided, the session is named after the channel (e.g. `--cdp=msedge` creates a session called `msedge`), so parallel attaches to Chrome and Edge don't collide on `default`. Pass `--session=<name>` to override.
|
||||
|
||||
### Attach via CDP endpoint
|
||||
|
||||
Connect to a browser that exposes a Chrome DevTools Protocol endpoint:
|
||||
|
||||
```bash
|
||||
playwright-cli attach --cdp=http://localhost:9222
|
||||
```
|
||||
|
||||
### Attach via browser extension
|
||||
|
||||
Connect to a browser with the Playwright extension installed:
|
||||
|
||||
```bash
|
||||
playwright-cli attach --extension
|
||||
```
|
||||
|
||||
### Detach
|
||||
|
||||
Tear down an attached session without affecting the external browser:
|
||||
|
||||
```bash
|
||||
# Detach the default attached session
|
||||
playwright-cli detach
|
||||
|
||||
# Detach a specific attached session
|
||||
playwright-cli -s=msedge detach
|
||||
```
|
||||
|
||||
`detach` only works on sessions created via `attach`. For sessions created via `open`, use `close`.
|
||||
|
||||
## Default Browser Session
|
||||
|
||||
When `-s` is omitted, commands use the default browser session:
|
||||
|
||||
```bash
|
||||
# These use the same default browser session
|
||||
playwright-cli open https://example.com
|
||||
playwright-cli snapshot
|
||||
playwright-cli close # Stops default browser
|
||||
```
|
||||
|
||||
## Browser Session Configuration
|
||||
|
||||
Configure a browser session with specific settings when opening:
|
||||
|
||||
```bash
|
||||
# Open with config file
|
||||
playwright-cli open https://example.com --config=.playwright/my-cli.json
|
||||
|
||||
# Open with specific browser
|
||||
playwright-cli open https://example.com --browser=firefox
|
||||
|
||||
# Open in headed mode
|
||||
playwright-cli open https://example.com --headed
|
||||
|
||||
# Open with persistent profile
|
||||
playwright-cli open https://example.com --persistent
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Name Browser Sessions Semantically
|
||||
|
||||
```bash
|
||||
# GOOD: Clear purpose
|
||||
playwright-cli -s=github-auth open https://github.com
|
||||
playwright-cli -s=docs-scrape open https://docs.example.com
|
||||
|
||||
# AVOID: Generic names
|
||||
playwright-cli -s=s1 open https://github.com
|
||||
```
|
||||
|
||||
### 2. Always Clean Up
|
||||
|
||||
```bash
|
||||
# Stop browsers when done
|
||||
playwright-cli -s=auth close
|
||||
playwright-cli -s=scrape close
|
||||
|
||||
# Or stop all at once
|
||||
playwright-cli close-all
|
||||
|
||||
# If browsers become unresponsive or zombie processes remain
|
||||
playwright-cli kill-all
|
||||
```
|
||||
|
||||
### 3. Delete Stale Browser Data
|
||||
|
||||
```bash
|
||||
# Remove old browser data to free disk space
|
||||
playwright-cli -s=oldsession delete-data
|
||||
```
|
||||
@@ -1,275 +0,0 @@
|
||||
# Storage Management
|
||||
|
||||
Manage cookies, localStorage, sessionStorage, and browser storage state.
|
||||
|
||||
## Storage State
|
||||
|
||||
Save and restore complete browser state including cookies and storage.
|
||||
|
||||
### Save Storage State
|
||||
|
||||
```bash
|
||||
# Save to auto-generated filename (storage-state-{timestamp}.json)
|
||||
playwright-cli state-save
|
||||
|
||||
# Save to specific filename
|
||||
playwright-cli state-save my-auth-state.json
|
||||
```
|
||||
|
||||
### Restore Storage State
|
||||
|
||||
```bash
|
||||
# Load storage state from file
|
||||
playwright-cli state-load my-auth-state.json
|
||||
|
||||
# Reload page to apply cookies
|
||||
playwright-cli open https://example.com
|
||||
```
|
||||
|
||||
### Storage State File Format
|
||||
|
||||
The saved file contains:
|
||||
|
||||
```json
|
||||
{
|
||||
"cookies": [
|
||||
{
|
||||
"name": "session_id",
|
||||
"value": "abc123",
|
||||
"domain": "example.com",
|
||||
"path": "/",
|
||||
"expires": 1893456000,
|
||||
"httpOnly": true,
|
||||
"secure": true,
|
||||
"sameSite": "Lax"
|
||||
}
|
||||
],
|
||||
"origins": [
|
||||
{
|
||||
"origin": "https://example.com",
|
||||
"localStorage": [
|
||||
{ "name": "theme", "value": "dark" },
|
||||
{ "name": "user_id", "value": "12345" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Cookies
|
||||
|
||||
### List All Cookies
|
||||
|
||||
```bash
|
||||
playwright-cli cookie-list
|
||||
```
|
||||
|
||||
### Filter Cookies by Domain
|
||||
|
||||
```bash
|
||||
playwright-cli cookie-list --domain=example.com
|
||||
```
|
||||
|
||||
### Filter Cookies by Path
|
||||
|
||||
```bash
|
||||
playwright-cli cookie-list --path=/api
|
||||
```
|
||||
|
||||
### Get Specific Cookie
|
||||
|
||||
```bash
|
||||
playwright-cli cookie-get session_id
|
||||
```
|
||||
|
||||
### Set a Cookie
|
||||
|
||||
```bash
|
||||
# Basic cookie
|
||||
playwright-cli cookie-set session abc123
|
||||
|
||||
# Cookie with options
|
||||
playwright-cli cookie-set session abc123 --domain=example.com --path=/ --httpOnly --secure --sameSite=Lax
|
||||
|
||||
# Cookie with expiration (Unix timestamp)
|
||||
playwright-cli cookie-set remember_me token123 --expires=1893456000
|
||||
```
|
||||
|
||||
### Delete a Cookie
|
||||
|
||||
```bash
|
||||
playwright-cli cookie-delete session_id
|
||||
```
|
||||
|
||||
### Clear All Cookies
|
||||
|
||||
```bash
|
||||
playwright-cli cookie-clear
|
||||
```
|
||||
|
||||
### Advanced: Multiple Cookies or Custom Options
|
||||
|
||||
For complex scenarios like adding multiple cookies at once, use `run-code`:
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
await page.context().addCookies([
|
||||
{ name: 'session_id', value: 'sess_abc123', domain: 'example.com', path: '/', httpOnly: true },
|
||||
{ name: 'preferences', value: JSON.stringify({ theme: 'dark' }), domain: 'example.com', path: '/' }
|
||||
]);
|
||||
}"
|
||||
```
|
||||
|
||||
## Local Storage
|
||||
|
||||
### List All localStorage Items
|
||||
|
||||
```bash
|
||||
playwright-cli localstorage-list
|
||||
```
|
||||
|
||||
### Get Single Value
|
||||
|
||||
```bash
|
||||
playwright-cli localstorage-get token
|
||||
```
|
||||
|
||||
### Set Value
|
||||
|
||||
```bash
|
||||
playwright-cli localstorage-set theme dark
|
||||
```
|
||||
|
||||
### Set JSON Value
|
||||
|
||||
```bash
|
||||
playwright-cli localstorage-set user_settings '{"theme":"dark","language":"en"}'
|
||||
```
|
||||
|
||||
### Delete Single Item
|
||||
|
||||
```bash
|
||||
playwright-cli localstorage-delete token
|
||||
```
|
||||
|
||||
### Clear All localStorage
|
||||
|
||||
```bash
|
||||
playwright-cli localstorage-clear
|
||||
```
|
||||
|
||||
### Advanced: Multiple Operations
|
||||
|
||||
For complex scenarios like setting multiple values at once, use `run-code`:
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
await page.evaluate(() => {
|
||||
localStorage.setItem('token', 'jwt_abc123');
|
||||
localStorage.setItem('user_id', '12345');
|
||||
localStorage.setItem('expires_at', Date.now() + 3600000);
|
||||
});
|
||||
}"
|
||||
```
|
||||
|
||||
## Session Storage
|
||||
|
||||
### List All sessionStorage Items
|
||||
|
||||
```bash
|
||||
playwright-cli sessionstorage-list
|
||||
```
|
||||
|
||||
### Get Single Value
|
||||
|
||||
```bash
|
||||
playwright-cli sessionstorage-get form_data
|
||||
```
|
||||
|
||||
### Set Value
|
||||
|
||||
```bash
|
||||
playwright-cli sessionstorage-set step 3
|
||||
```
|
||||
|
||||
### Delete Single Item
|
||||
|
||||
```bash
|
||||
playwright-cli sessionstorage-delete step
|
||||
```
|
||||
|
||||
### Clear sessionStorage
|
||||
|
||||
```bash
|
||||
playwright-cli sessionstorage-clear
|
||||
```
|
||||
|
||||
## IndexedDB
|
||||
|
||||
### List Databases
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
return await page.evaluate(async () => {
|
||||
const databases = await indexedDB.databases();
|
||||
return databases;
|
||||
});
|
||||
}"
|
||||
```
|
||||
|
||||
### Delete Database
|
||||
|
||||
```bash
|
||||
playwright-cli run-code "async page => {
|
||||
await page.evaluate(() => {
|
||||
indexedDB.deleteDatabase('myDatabase');
|
||||
});
|
||||
}"
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Authentication State Reuse
|
||||
|
||||
```bash
|
||||
# Step 1: Login and save state
|
||||
playwright-cli open https://app.example.com/login
|
||||
playwright-cli snapshot
|
||||
playwright-cli fill e1 "user@example.com"
|
||||
playwright-cli fill e2 "password123"
|
||||
playwright-cli click e3
|
||||
|
||||
# Save the authenticated state
|
||||
playwright-cli state-save auth.json
|
||||
|
||||
# Step 2: Later, restore state and skip login
|
||||
playwright-cli state-load auth.json
|
||||
playwright-cli open https://app.example.com/dashboard
|
||||
# Already logged in!
|
||||
```
|
||||
|
||||
### Save and Restore Roundtrip
|
||||
|
||||
```bash
|
||||
# Set up authentication state
|
||||
playwright-cli open https://example.com
|
||||
playwright-cli eval "() => { document.cookie = 'session=abc123'; localStorage.setItem('user', 'john'); }"
|
||||
|
||||
# Save state to file
|
||||
playwright-cli state-save my-session.json
|
||||
|
||||
# ... later, in a new session ...
|
||||
|
||||
# Restore state
|
||||
playwright-cli state-load my-session.json
|
||||
playwright-cli open https://example.com
|
||||
# Cookies and localStorage are restored!
|
||||
```
|
||||
|
||||
## Security Notes
|
||||
|
||||
- Never commit storage state files containing auth tokens
|
||||
- Add `*.auth-state.json` to `.gitignore`
|
||||
- Delete state files after automation completes
|
||||
- Use environment variables for sensitive data
|
||||
- By default, sessions run in-memory mode which is safer for sensitive operations
|
||||
@@ -1,433 +0,0 @@
|
||||
# Test generation (plan → generate → heal)
|
||||
|
||||
End-to-end workflow for authoring and maintaining Playwright tests with `playwright-cli`. Every `playwright-cli` action emits the equivalent Playwright TypeScript, and that generated code is the raw material for every test. The sections below can be used independently:
|
||||
|
||||
- **How generation works** — the core mechanic everything else relies on: actions become TypeScript, plus how to add assertions.
|
||||
- **Plan** — explore the app, produce a spec file describing what to test.
|
||||
- **Generate** — turn a spec into Playwright test files. Update the spec if it's vague or stale.
|
||||
- **Heal** — diagnose failing tests, fix the code, reconcile the spec with reality.
|
||||
|
||||
Plan / generate / heal lean on the same mechanic: run `npx playwright test --debug=cli` in the background, then `playwright-cli attach tw-XXXX` to drive the paused page interactively. See [playwright-tests.md](playwright-tests.md) for the debug/attach mechanics.
|
||||
|
||||
---
|
||||
|
||||
## 0. How generation works
|
||||
|
||||
Every action you perform with `playwright-cli` generates corresponding Playwright TypeScript code. This code appears in the output and can be copied directly into your test files.
|
||||
|
||||
```bash
|
||||
# Start a session
|
||||
playwright-cli open https://example.com/login
|
||||
|
||||
# Take a snapshot to see elements
|
||||
playwright-cli snapshot
|
||||
# Output shows: e1 [textbox "Email"], e2 [textbox "Password"], e3 [button "Sign In"]
|
||||
|
||||
# Fill form fields - generates code automatically
|
||||
playwright-cli fill e1 "user@example.com"
|
||||
# Ran Playwright code:
|
||||
# await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
|
||||
|
||||
playwright-cli fill e2 "password123"
|
||||
# Ran Playwright code:
|
||||
# await page.getByRole('textbox', { name: 'Password' }).fill('password123');
|
||||
|
||||
playwright-cli click e3
|
||||
# Ran Playwright code:
|
||||
# await page.getByRole('button', { name: 'Sign In' }).click();
|
||||
```
|
||||
|
||||
### Building a test file
|
||||
|
||||
Collect the generated code into a Playwright test:
|
||||
|
||||
```typescript
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test('login flow', async ({ page }) => {
|
||||
// Generated code from playwright-cli session:
|
||||
await page.goto('https://example.com/login');
|
||||
await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
|
||||
await page.getByRole('textbox', { name: 'Password' }).fill('password123');
|
||||
await page.getByRole('button', { name: 'Sign In' }).click();
|
||||
|
||||
// Add assertions
|
||||
await expect(page).toHaveURL(/.*dashboard/);
|
||||
});
|
||||
```
|
||||
|
||||
### Use semantic locators
|
||||
|
||||
The generated code uses role-based locators when possible, which are more resilient:
|
||||
|
||||
```typescript
|
||||
// Generated (good - semantic)
|
||||
await page.getByRole('button', { name: 'Submit' }).click();
|
||||
|
||||
// Avoid (fragile - CSS selectors)
|
||||
await page.locator('#submit-btn').click();
|
||||
```
|
||||
|
||||
### Explore before recording
|
||||
|
||||
Take snapshots to understand the page structure before recording actions:
|
||||
|
||||
```bash
|
||||
playwright-cli open https://example.com
|
||||
playwright-cli snapshot
|
||||
# Review the element structure
|
||||
playwright-cli click e5
|
||||
```
|
||||
|
||||
### Add assertions manually
|
||||
|
||||
Generated code captures actions but not assertions. Add expectations in your test using one of the recommended matchers:
|
||||
|
||||
- `toBeVisible()` — element is rendered and visible
|
||||
- `toHaveText(text)` — element text content matches
|
||||
- `toHaveValue(value) / toBeEmpty()` — input/select value matches
|
||||
- `toBeChecked() / toBeUnchecked()` — checkbox state matches
|
||||
- `toMatchAriaSnapshot(snapshot)` — page (or locator) matches a partial accessibility snapshot
|
||||
|
||||
Use `playwright-cli generate-locator <target>` to produce the locator expression for the assertion, and the snapshot/eval commands to capture the expected value.
|
||||
|
||||
When asserting text content, make sure that generated locator does not contain text from the element itself. `getByTestId()` or `getByLabel()` usually work well with asserting text. When locator is text-based, prefer `toBeVisible()` instead.
|
||||
|
||||
Snapshot to be matched does not have to contain all the information - only capture what's necessary for the assertion. You can use regular expressions for unstable values.
|
||||
|
||||
```bash
|
||||
# Get a stable locator for an element ref to use in the assertion
|
||||
playwright-cli --raw generate-locator e5
|
||||
# getByRole('button', { name: 'Submit' })
|
||||
|
||||
# Capture expected text content for toHaveText
|
||||
playwright-cli --raw eval "el => el.textContent" e5
|
||||
|
||||
# Capture expected input value for toHaveValue/toBeEmpty
|
||||
playwright-cli --raw eval "el => el.value" e5
|
||||
|
||||
# Capture expected aria snapshot for toMatchAriaSnapshot/toBeChecked
|
||||
# (whole page, or use a ref to scope to a region)
|
||||
playwright-cli --raw snapshot
|
||||
playwright-cli --raw snapshot e5
|
||||
```
|
||||
|
||||
```typescript
|
||||
// Generated action
|
||||
await page.getByRole('button', { name: 'Submit' }).click();
|
||||
|
||||
// Manual assertions using the outputs above:
|
||||
await expect(page.getByRole('alert', { name: 'Success' })).toBeVisible();
|
||||
await expect(page.getByTestId('main-header')).toHaveText('Welcome, user');
|
||||
await expect(page.getByRole('textbox', { name: 'Email' })).toHaveValue('user@example.com');
|
||||
await expect(page.getByRole('checkbox', { name: 'Enable notifications' })).toBeChecked();
|
||||
|
||||
// toMatchAriaSnapshot on the whole page, finds a matching region
|
||||
await expect(page).toMatchAriaSnapshot(`
|
||||
- heading "Welcome, user"
|
||||
- link /\\d+ new messages?/
|
||||
- button "Sign out"
|
||||
`);
|
||||
|
||||
// toMatchAriaSnapshot scoped to a region
|
||||
await expect(page.getByRole('navigation')).toMatchAriaSnapshot(`
|
||||
- link "Home"
|
||||
- link /\\d+ new messages?/
|
||||
- link "Profile"
|
||||
`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. Planning
|
||||
|
||||
Goal: produce a spec file (e.g. `specs/<feature>.plan.md`) that enumerates the scenarios to test. **Always** write the spec to a file.
|
||||
|
||||
### 1.1 Prerequisite: workspace
|
||||
|
||||
Check the workspace has Playwright installed before anything else:
|
||||
|
||||
```bash
|
||||
# Either of these confirms a workspace:
|
||||
test -f playwright.config.ts || test -f playwright.config.js
|
||||
npx --no-install playwright --version
|
||||
```
|
||||
|
||||
If there is no Playwright install, bootstrap one and let the user pick the defaults:
|
||||
|
||||
```bash
|
||||
npm init playwright@latest
|
||||
```
|
||||
|
||||
### 1.2 Prerequisite: seed test
|
||||
|
||||
A **seed test** is a minimal test that lands the page in the state every scenario starts from: navigation to the app, any required login, feature flags, etc. Scenarios assume a fresh start *after* the seed. `--debug=cli` pauses *inside* this test, so the seed is where every planning and generation session begins.
|
||||
|
||||
Minimum viable seed:
|
||||
|
||||
```ts
|
||||
// tests/seed.spec.ts
|
||||
import { test } from '@playwright/test';
|
||||
|
||||
test('seed', async ({ page }) => {
|
||||
await page.goto('https://example.com/');
|
||||
});
|
||||
```
|
||||
|
||||
Preferred — push navigation into a fixture so scenario tests reuse it:
|
||||
|
||||
```ts
|
||||
// tests/fixtures.ts
|
||||
import { test as baseTest } from '@playwright/test';
|
||||
export { expect } from '@playwright/test';
|
||||
|
||||
export const test = baseTest.extend({
|
||||
page: async ({ page }, use) => {
|
||||
await page.goto('https://example.com/');
|
||||
await use(page);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// tests/seed.spec.ts
|
||||
import { test } from './fixtures';
|
||||
|
||||
test('seed', async ({ page }) => {
|
||||
// Fixture already navigates. This empty body tells agents where to start.
|
||||
});
|
||||
```
|
||||
|
||||
If no seed exists, create one that at least navigates to the app.
|
||||
|
||||
### 1.3 Explore the app
|
||||
|
||||
Launch the app via the seed in the background and attach:
|
||||
|
||||
```bash
|
||||
PLAYWRIGHT_HTML_OPEN=never npx playwright test tests/seed.spec.ts --debug=cli
|
||||
# wait for "Debugging Instructions" and the session name tw-XXXX
|
||||
playwright-cli attach tw-XXXX
|
||||
```
|
||||
|
||||
Resume so the seed runs, then probe the app:
|
||||
|
||||
```bash
|
||||
playwright-cli resume # resume so that seed test runs fully
|
||||
playwright-cli snapshot # inventory of interactive elements
|
||||
playwright-cli click e5 # follow a flow
|
||||
playwright-cli eval "location.href" # read URL / state
|
||||
playwright-cli show --annotate # ask the user to point at something
|
||||
```
|
||||
|
||||
Map out:
|
||||
|
||||
- Interactive surfaces (forms, buttons, lists, filters, modals).
|
||||
- Primary user journeys end-to-end.
|
||||
- Edge cases: empty states, validation errors, very long input, boundary values.
|
||||
- Persistence: reload, local/session storage, URL fragments.
|
||||
- Navigation: which controls change the URL, back/forward behaviour.
|
||||
|
||||
**Important**: Do not just open the app url with playwright-cli, always go through the test to capture any custom setup done there.
|
||||
**Important**: Stop the background test when done exploring.
|
||||
|
||||
### 1.4 Write the spec file
|
||||
|
||||
Save under `specs/<feature>.plan.md`. Use this structure:
|
||||
|
||||
```markdown
|
||||
# <Feature> Test Plan
|
||||
|
||||
## Application Overview
|
||||
|
||||
<One paragraph describing what the feature does and why it matters.>
|
||||
|
||||
## Test Scenarios
|
||||
|
||||
### 1. <Group Name>
|
||||
|
||||
**Seed:** `tests/seed.spec.ts`
|
||||
|
||||
#### 1.1. <kebab-case-scenario-name>
|
||||
|
||||
**File:** `tests/<group>/<kebab-case-scenario-name>.spec.ts`
|
||||
|
||||
**Steps:**
|
||||
1. <Concrete user step>
|
||||
- expect: <observable outcome>
|
||||
- expect: <another observable outcome>
|
||||
2. <Next step>
|
||||
- expect: <outcome>
|
||||
|
||||
#### 1.2. <next-scenario>
|
||||
...
|
||||
|
||||
### 2. <Next Group>
|
||||
|
||||
**Seed:** `tests/seed.spec.ts`
|
||||
...
|
||||
```
|
||||
|
||||
Guidelines:
|
||||
|
||||
- Each scenario is independent and starts from the seed's fresh state — never chain scenarios.
|
||||
- Scenario names are kebab-case and match the test file name (`should-add-single-todo` → `should-add-single-todo.spec.ts`).
|
||||
- Cover happy path, edge cases, validation, negative flows, persistence.
|
||||
- Write steps at the user level ("Type 'Buy milk' into the input"), not the API level ("call `fill`").
|
||||
- Put observable outcomes in `- expect:` bullets; each becomes an assertion during generation.
|
||||
|
||||
---
|
||||
|
||||
## 2. Generate
|
||||
|
||||
Goal: take a spec file and produce Playwright test files. Optionally update the spec if it has drifted.
|
||||
|
||||
### 2.1 Inputs
|
||||
|
||||
- **Spec file**, e.g. `specs/basic-operations.plan.md`.
|
||||
- **Target**: either a single scenario (e.g. `1.2`), a whole group (`1`), or all.
|
||||
- **Seed file**, read from the `**Seed:**` line of the scenario's group.
|
||||
|
||||
### 2.2 Generate one scenario
|
||||
|
||||
For each target scenario, in sequence (never in parallel — scenarios share the seed session):
|
||||
|
||||
```bash
|
||||
PLAYWRIGHT_HTML_OPEN=never npx playwright test <seed-file> --debug=cli # background
|
||||
playwright-cli attach tw-XXXX
|
||||
# resume
|
||||
```
|
||||
|
||||
**Do not** just open the app url with playwright-cli, always go through the test to capture any custom setup done there.
|
||||
|
||||
Walk the scenario's `Steps:` one by one with `playwright-cli`, treating the spec as the plan and the live app as the source of truth. If a step is vague ("click the button" — which button?), references an element that no longer exists, or contradicts the app's actual behaviour, use your judgement: update the spec to match what the app really does, then keep going. Editing the spec mid-generation is expected.
|
||||
|
||||
Every action prints the equivalent Playwright TypeScript (see [How generation works](#0-how-generation-works)):
|
||||
|
||||
```bash
|
||||
playwright-cli snapshot # find refs
|
||||
playwright-cli fill e3 "John Doe" # -> page.getByRole('textbox', {...}).fill(...)
|
||||
playwright-cli press Enter
|
||||
playwright-cli click e7
|
||||
```
|
||||
|
||||
For each `- expect:` bullet, add an explicit assertion. See [How generation works](#0-how-generation-works) for details.
|
||||
|
||||
Collect the generated code and write the test file at the path given in the spec:
|
||||
|
||||
```ts
|
||||
// spec: specs/basic-operations.plan.md
|
||||
// seed: tests/seed.spec.ts
|
||||
import { test, expect } from './fixtures'; // or '@playwright/test' if no fixtures file
|
||||
|
||||
test.describe('Signing in and out', () => {
|
||||
test('should sign in', async ({ page }) => {
|
||||
// 1. Navigate to the application
|
||||
// (handled by the seed fixture)
|
||||
|
||||
// 2. Type 'John Doe' into the username field
|
||||
await page.getByRole('textbox', { name: 'username' }).fill('John Doe');
|
||||
|
||||
// 3. Type password
|
||||
await page.getByRole('textbox', { name: 'password' }).fill('TestPassword');
|
||||
|
||||
// 4. Press Enter to submit
|
||||
await page.getByRole('textbox', { name: 'password' }).press('Enter');
|
||||
|
||||
await expect(page.getByRole('heading')).toContainText('Welcome, John Doe!');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- **One test per file.** File path, describe name, and test name come verbatim from the spec (minus the ordinal).
|
||||
- Prefix each numbered step with a `// N. <step text>` comment before its actions.
|
||||
- Use the describe group name verbatim from the spec (no `1.` ordinal).
|
||||
- Import from `./fixtures` if the project has one; otherwise `@playwright/test`.
|
||||
- **Important**: close the CLI session and stop the background test before moving to the next scenario.
|
||||
|
||||
### 2.3 Generate multiple scenarios
|
||||
|
||||
Loop 2.2 over the targeted scenarios one at a time, restarting the seed between each so every test starts from a clean page. This is safe to parallelise due to unique generated session names - just make sure each test run is stopped.
|
||||
|
||||
### 2.4 Run generated tests
|
||||
|
||||
After generation, run the new tests once:
|
||||
|
||||
```bash
|
||||
PLAYWRIGHT_HTML_OPEN=never npx playwright test tests/<group>/<scenario>.spec.ts
|
||||
```
|
||||
|
||||
Any failure goes to Section 3.
|
||||
|
||||
---
|
||||
|
||||
## 3. Heal
|
||||
|
||||
Goal: fix failing tests, and update the spec if the app's intended behaviour changed.
|
||||
|
||||
### 3.1 Find failing tests
|
||||
|
||||
```bash
|
||||
PLAYWRIGHT_HTML_OPEN=never npx playwright test
|
||||
```
|
||||
|
||||
Record the list of failing `<file>:<line>` entries and process them one at a time. Do not attempt parallel fixes — shared state and the single CLI session make that fragile.
|
||||
|
||||
### 3.2 Debug one failure
|
||||
|
||||
Run the single failing test in debug mode in the background, then attach:
|
||||
|
||||
```bash
|
||||
PLAYWRIGHT_HTML_OPEN=never npx playwright test tests/<group>/<scenario>.spec.ts:<line> --debug=cli
|
||||
# wait for "Debugging Instructions" and the tw-XXXX session name
|
||||
playwright-cli attach tw-XXXX
|
||||
```
|
||||
|
||||
The test is paused at the start. Step forward or run to until just before the failing action or assertion, then diagnose:
|
||||
|
||||
```bash
|
||||
playwright-cli snapshot # did the element change / move / rename?
|
||||
playwright-cli console # app-side errors?
|
||||
playwright-cli requests # failed request? wrong payload?
|
||||
playwright-cli show --annotate # ask the user to point somewhere
|
||||
```
|
||||
|
||||
Common causes: selector drift, new wrapper element, label/ARIA rename, timing (transition, async load), assertion text updated in the app, test data leaking between runs.
|
||||
|
||||
Rehearse the corrected interaction with `playwright-cli` — the generated code in the output is what you paste back into the test.
|
||||
|
||||
### 3.3 Apply the fix
|
||||
|
||||
Edit the test file: update the locator, assertion, step order, or inputs to match the corrected behaviour. Stop the background debug run. Rerun the single test to confirm green.
|
||||
|
||||
Never skip hooks or add sleeps as a fix. Never use `networkidle`.
|
||||
|
||||
### 3.4 Reconcile with the spec
|
||||
|
||||
Open the spec referenced by the `// spec:` header in the test file and locate the scenario that matches the test.
|
||||
|
||||
- **Fix was purely technical** (locator drift, better assertion shape) and the spec's user-level behaviour still matches the app → leave the spec alone.
|
||||
- **Fix changed user-visible steps, inputs, order, or expected outcomes** that the spec describes → update the spec to match reality. Keep the scenario id and file path stable; only the step / expect lines change.
|
||||
- **Unclear whether the app change is intentional** (spec is stale) **or a regression** (test was right, app is wrong) → **stop and ask the user**. Provide:
|
||||
- the scenario id (e.g. `2.3`),
|
||||
- the spec lines that no longer match,
|
||||
- the observed app behaviour (quote a snapshot excerpt or a concrete outcome).
|
||||
|
||||
Only after the user answers, either update the spec (intentional change) or file/flag the test as covering a bug (regression).
|
||||
|
||||
### 3.5 Iteration and giving up
|
||||
|
||||
- Fix failures one at a time; rerun after each.
|
||||
- If after thorough investigation you are confident the test is correct but the app is wrong *and* the user has confirmed it's a bug: mark the test `test.fixme(...)` with a comment pointing at the user's decision or issue link. Never silently skip.
|
||||
|
||||
---
|
||||
|
||||
## Cross-references
|
||||
|
||||
| For... | See |
|
||||
|---|---|
|
||||
| `--debug=cli` / attach mechanics | [playwright-tests.md](playwright-tests.md) |
|
||||
| Mocking requests during exploration/generation | [request-mocking.md](request-mocking.md) |
|
||||
| Managing the CLI browser session | [session-management.md](session-management.md) |
|
||||
@@ -1,139 +0,0 @@
|
||||
# Tracing
|
||||
|
||||
Capture detailed execution traces for debugging and analysis. Traces include DOM snapshots, screenshots, network activity, and console logs.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```bash
|
||||
# Start trace recording
|
||||
playwright-cli tracing-start
|
||||
|
||||
# Perform actions
|
||||
playwright-cli open https://example.com
|
||||
playwright-cli click e1
|
||||
playwright-cli fill e2 "test"
|
||||
|
||||
# Stop trace recording
|
||||
playwright-cli tracing-stop
|
||||
```
|
||||
|
||||
## Trace Output Files
|
||||
|
||||
When you start tracing, Playwright creates a `.playwright-cli/traces/` directory with several files:
|
||||
|
||||
### `trace-{timestamp}.trace`
|
||||
|
||||
**Action log** - The main trace file containing:
|
||||
- Every action performed (clicks, fills, navigations)
|
||||
- DOM snapshots before and after each action
|
||||
- Screenshots at each step
|
||||
- Timing information
|
||||
- Console messages
|
||||
- Source locations
|
||||
|
||||
### `trace-{timestamp}.network`
|
||||
|
||||
**Network log** - Complete network activity:
|
||||
- All HTTP requests and responses
|
||||
- Request headers and bodies
|
||||
- Response headers and bodies
|
||||
- Timing (DNS, connect, TLS, TTFB, download)
|
||||
- Resource sizes
|
||||
- Failed requests and errors
|
||||
|
||||
### `resources/`
|
||||
|
||||
**Resources directory** - Cached resources:
|
||||
- Images, fonts, stylesheets, scripts
|
||||
- Response bodies for replay
|
||||
- Assets needed to reconstruct page state
|
||||
|
||||
## What Traces Capture
|
||||
|
||||
| Category | Details |
|
||||
|----------|---------|
|
||||
| **Actions** | Clicks, fills, hovers, keyboard input, navigations |
|
||||
| **DOM** | Full DOM snapshot before/after each action |
|
||||
| **Screenshots** | Visual state at each step |
|
||||
| **Network** | All requests, responses, headers, bodies, timing |
|
||||
| **Console** | All console.log, warn, error messages |
|
||||
| **Timing** | Precise timing for each operation |
|
||||
|
||||
## Use Cases
|
||||
|
||||
### Debugging Failed Actions
|
||||
|
||||
```bash
|
||||
playwright-cli tracing-start
|
||||
playwright-cli open https://app.example.com
|
||||
|
||||
# This click fails - why?
|
||||
playwright-cli click e5
|
||||
|
||||
playwright-cli tracing-stop
|
||||
# Open trace to see DOM state when click was attempted
|
||||
```
|
||||
|
||||
### Analyzing Performance
|
||||
|
||||
```bash
|
||||
playwright-cli tracing-start
|
||||
playwright-cli open https://slow-site.com
|
||||
playwright-cli tracing-stop
|
||||
|
||||
# View network waterfall to identify slow resources
|
||||
```
|
||||
|
||||
### Capturing Evidence
|
||||
|
||||
```bash
|
||||
# Record a complete user flow for documentation
|
||||
playwright-cli tracing-start
|
||||
|
||||
playwright-cli open https://app.example.com/checkout
|
||||
playwright-cli fill e1 "4111111111111111"
|
||||
playwright-cli fill e2 "12/25"
|
||||
playwright-cli fill e3 "123"
|
||||
playwright-cli click e4
|
||||
|
||||
playwright-cli tracing-stop
|
||||
# Trace shows exact sequence of events
|
||||
```
|
||||
|
||||
## Trace vs Video vs Screenshot
|
||||
|
||||
| Feature | Trace | Video | Screenshot |
|
||||
|---------|-------|-------|------------|
|
||||
| **Format** | .trace file | .webm video | .png/.jpeg image |
|
||||
| **DOM inspection** | Yes | No | No |
|
||||
| **Network details** | Yes | No | No |
|
||||
| **Step-by-step replay** | Yes | Continuous | Single frame |
|
||||
| **File size** | Medium | Large | Small |
|
||||
| **Best for** | Debugging | Demos | Quick capture |
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Start Tracing Before the Problem
|
||||
|
||||
```bash
|
||||
# Trace the entire flow, not just the failing step
|
||||
playwright-cli tracing-start
|
||||
playwright-cli open https://example.com
|
||||
# ... all steps leading to the issue ...
|
||||
playwright-cli tracing-stop
|
||||
```
|
||||
|
||||
### 2. Clean Up Old Traces
|
||||
|
||||
Traces can consume significant disk space:
|
||||
|
||||
```bash
|
||||
# Remove traces older than 7 days
|
||||
find .playwright-cli/traces -mtime +7 -delete
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
- Traces add overhead to automation
|
||||
- Large traces can consume significant disk space
|
||||
- Some dynamic content may not replay perfectly
|
||||
@@ -1,143 +0,0 @@
|
||||
# Video Recording
|
||||
|
||||
Capture browser automation sessions as video for debugging, documentation, or verification. Produces WebM (VP8/VP9 codec).
|
||||
|
||||
## Basic Recording
|
||||
|
||||
```bash
|
||||
# Open browser first
|
||||
playwright-cli open
|
||||
|
||||
# Start recording
|
||||
playwright-cli video-start demo.webm
|
||||
|
||||
# Add a chapter marker for section transitions
|
||||
playwright-cli video-chapter "Getting Started" --description="Opening the homepage" --duration=2000
|
||||
|
||||
# Navigate and perform actions
|
||||
playwright-cli goto https://example.com
|
||||
playwright-cli snapshot
|
||||
playwright-cli click e1
|
||||
|
||||
# Add another chapter
|
||||
playwright-cli video-chapter "Filling Form" --description="Entering test data" --duration=2000
|
||||
playwright-cli fill e2 "test input"
|
||||
|
||||
# Stop and save
|
||||
playwright-cli video-stop
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Use Descriptive Filenames
|
||||
|
||||
```bash
|
||||
# Include context in filename
|
||||
playwright-cli video-start recordings/login-flow-2024-01-15.webm
|
||||
playwright-cli video-start recordings/checkout-test-run-42.webm
|
||||
```
|
||||
|
||||
### 2. Record entire hero scripts.
|
||||
|
||||
When recording a video for the user or as a proof of work, it is best to create a code snippet and execute it with run-code.
|
||||
It allows inserting appropriate pauses between the actions and annotating the video. There are new Playwright APIs for that.
|
||||
|
||||
1) Perform scenario using CLI and take note of all locators and actions. You'll need those locators to request their bounding boxes for highlight.
|
||||
2) Create a file with the intended script for video (below). Use pressSequentially w/ delay for nice typing, make reasonable pauses.
|
||||
3) Use playwright-cli run-code --filename your-script.js
|
||||
|
||||
**Important**: Overlays are `pointer-events: none` — they do not interfere with page interactions. You can safely keep sticky overlays visible while clicking, filling, or performing any actions on the page.
|
||||
|
||||
```js
|
||||
async page => {
|
||||
await page.screencast.start({ path: 'video.webm', size: { width: 1280, height: 800 } });
|
||||
await page.goto('https://demo.playwright.dev/todomvc');
|
||||
|
||||
// Show a chapter card — blurs the page and shows a dialog.
|
||||
// Blocks until duration expires, then auto-removes.
|
||||
// Use this for simple use cases, but always feel free to hand-craft your own beautiful
|
||||
// overlay via await page.screencast.showOverlay().
|
||||
await page.screencast.showChapter('Adding Todo Items', {
|
||||
description: 'We will add several items to the todo list.',
|
||||
duration: 2000,
|
||||
});
|
||||
|
||||
// Perform action
|
||||
await page.getByRole('textbox', { name: 'What needs to be done?' }).pressSequentially('Walk the dog', { delay: 60 });
|
||||
await page.getByRole('textbox', { name: 'What needs to be done?' }).press('Enter');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Show next chapter
|
||||
await page.screencast.showChapter('Verifying Results', {
|
||||
description: 'Checking the item appeared in the list.',
|
||||
duration: 2000,
|
||||
});
|
||||
|
||||
// Add a sticky annotation that stays while you perform actions.
|
||||
// Overlays are pointer-events: none, so they won't block clicks.
|
||||
const annotation = await page.screencast.showOverlay(`
|
||||
<div style="position: absolute; top: 8px; right: 8px;
|
||||
padding: 6px 12px; background: rgba(0,0,0,0.7);
|
||||
border-radius: 8px; font-size: 13px; color: white;">
|
||||
✓ Item added successfully
|
||||
</div>
|
||||
`);
|
||||
|
||||
// Perform more actions while the annotation is visible
|
||||
await page.getByRole('textbox', { name: 'What needs to be done?' }).pressSequentially('Buy groceries', { delay: 60 });
|
||||
await page.getByRole('textbox', { name: 'What needs to be done?' }).press('Enter');
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
// Remove the annotation when done
|
||||
await annotation.dispose();
|
||||
|
||||
// You can also highlight relevant locators and provide contextual annotations.
|
||||
const bounds = await page.getByText('Walk the dog').boundingBox();
|
||||
await page.screencast.showOverlay(`
|
||||
<div style="position: absolute;
|
||||
top: ${bounds.y}px;
|
||||
left: ${bounds.x}px;
|
||||
width: ${bounds.width}px;
|
||||
height: ${bounds.height}px;
|
||||
border: 1px solid red;">
|
||||
</div>
|
||||
<div style="position: absolute;
|
||||
top: ${bounds.y + bounds.height + 5}px;
|
||||
left: ${bounds.x + bounds.width / 2}px;
|
||||
transform: translateX(-50%);
|
||||
padding: 6px;
|
||||
background: #808080;
|
||||
border-radius: 10px;
|
||||
font-size: 14px;
|
||||
color: white;">Check it out, it is right above this text
|
||||
</div>
|
||||
`, { duration: 2000 });
|
||||
|
||||
await page.screencast.stop();
|
||||
}
|
||||
```
|
||||
|
||||
Embrace creativity, overlays are powerful.
|
||||
|
||||
### Overlay API Summary
|
||||
|
||||
| Method | Use Case |
|
||||
|--------|----------|
|
||||
| `page.screencast.showChapter(title, { description?, duration?, styleSheet? })` | Full-screen chapter card with blurred backdrop — ideal for section transitions |
|
||||
| `page.screencast.showOverlay(html, { duration? })` | Custom HTML overlay — use for callouts, labels, highlights |
|
||||
| `disposable.dispose()` | Remove a sticky overlay added without duration |
|
||||
| `page.screencast.hideOverlays()` / `page.screencast.showOverlays()` | Temporarily hide/show all overlays |
|
||||
|
||||
## Tracing vs Video
|
||||
|
||||
| Feature | Video | Tracing |
|
||||
|---------|-------|---------|
|
||||
| Output | WebM file | Trace file (viewable in Trace Viewer) |
|
||||
| Shows | Visual recording | DOM snapshots, network, console, actions |
|
||||
| Use case | Demos, documentation | Debugging, analysis |
|
||||
| Size | Larger | Smaller |
|
||||
|
||||
## Limitations
|
||||
|
||||
- Recording adds slight overhead to automation
|
||||
- Large recordings can consume significant disk space
|
||||
Executable
+325
@@ -0,0 +1,325 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/* eslint-disable no-console */
|
||||
|
||||
import * as program from 'commander';
|
||||
import * as os from 'os';
|
||||
import * as playwright from 'playwright';
|
||||
import { Browser, BrowserContext, Page } from 'playwright';
|
||||
import { RecorderController } from './recorderController';
|
||||
import { ScriptController } from './scriptController';
|
||||
|
||||
program
|
||||
.version('Version ' + require('../package.json').version)
|
||||
.option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium')
|
||||
.option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"')
|
||||
.option('--device <deviceName>', 'emulate device, for example "iPhone 11"')
|
||||
.option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"')
|
||||
.option('--lang <language>', 'specify language / locale, for example "en-GB"')
|
||||
.option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"')
|
||||
.option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"')
|
||||
.option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds, defaults to 10000', "10000")
|
||||
.option('--user-agent <ua string>', 'specify user agent string')
|
||||
.option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"');
|
||||
|
||||
program
|
||||
.command('open [url]')
|
||||
.description('open page in browser specified via -b, --browser')
|
||||
.action(function(url, command) {
|
||||
open(command.parent, url, false);
|
||||
}).on('--help', function() {
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log('');
|
||||
console.log(' $ open');
|
||||
console.log(' $ -b webkit open https://example.com');
|
||||
});
|
||||
|
||||
const browsers = [
|
||||
{ alias: 'cr', name: 'Chromium', type: 'chromium' },
|
||||
{ alias: 'ff', name: 'Firefox', type: 'firefox' },
|
||||
{ alias: 'wk', name: 'WebKit', type: 'webkit' },
|
||||
];
|
||||
|
||||
for (const {alias, name, type} of browsers) {
|
||||
program
|
||||
.command(`${alias} [url]`)
|
||||
.description(`open page in ${name}`)
|
||||
.action(function(url, command) {
|
||||
open({ ...command.parent, browser: type }, url, false);
|
||||
}).on('--help', function() {
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log('');
|
||||
console.log(` $ ${alias} https://example.com`);
|
||||
});
|
||||
}
|
||||
|
||||
program
|
||||
.command('codegen [url]')
|
||||
.description('open page and generate code for user actions')
|
||||
.action(function(url, command) {
|
||||
codegen(command.parent, url);
|
||||
}).on('--help', function() {
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log('');
|
||||
console.log(' $ record');
|
||||
console.log(' $ -b webkit record https://example.com');
|
||||
});
|
||||
|
||||
program
|
||||
.command('screenshot <url> <filename>')
|
||||
.description('capture a page screenshot')
|
||||
.option('--wait-for-selector <selector>', 'wait for selector before taking a screenshot')
|
||||
.option('--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot')
|
||||
.option('--full-page', 'Whether to take a full page screenshot (entire scrollable area)')
|
||||
.action(function(url, filename, command) {
|
||||
screenshot(command.parent, command, url, filename);
|
||||
}).on('--help', function() {
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log('');
|
||||
console.log(' $ -b webkit screenshot https://example.com example.png');
|
||||
});
|
||||
|
||||
program
|
||||
.command('pdf <url> <filename>')
|
||||
.description('save page as pdf')
|
||||
.option('--wait-for-selector <selector>', 'wait for given selector before saving as pdf')
|
||||
.option('--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf')
|
||||
.action(function(url, filename, command) {
|
||||
pdf(command.parent, command, url, filename);
|
||||
}).on('--help', function() {
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log('');
|
||||
console.log(' $ pdf https://example.com example.png');
|
||||
});
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
type Options = {
|
||||
browser: string;
|
||||
colorScheme: string | undefined;
|
||||
device: string | undefined;
|
||||
geolocation: string;
|
||||
lang: string;
|
||||
proxyServer: string;
|
||||
timeout: string | undefined;
|
||||
timezone: string;
|
||||
viewportSize: string | undefined;
|
||||
userAgent: string | undefined;
|
||||
};
|
||||
|
||||
type CaptureOptions = {
|
||||
waitForSelector: string | undefined;
|
||||
waitForTimeout: string | undefined;
|
||||
fullPage: boolean;
|
||||
};
|
||||
|
||||
async function launchContext(options: Options, headless: boolean): Promise<{ browser: Browser, browserName: string, launchOptions: playwright.LaunchOptions, contextOptions: playwright.BrowserContextOptions, context: BrowserContext }> {
|
||||
validateOptions(options);
|
||||
const browserType = lookupBrowserType(options);
|
||||
const launchOptions: playwright.LaunchOptions = {
|
||||
headless,
|
||||
};
|
||||
const contextOptions: playwright.BrowserContextOptions =
|
||||
// Copy the device descriptor since we have to compare and modify the options.
|
||||
options.device ? { ...playwright.devices[options.device] } :
|
||||
// In headful mode, use host device scale factor for things to look nice.
|
||||
// In headless, keep things the way it works in Playwright by default.
|
||||
// Assume high-dpi on MacOS. TODO: this is not perfect.
|
||||
{ deviceScaleFactor: headless ? undefined : (os.platform() === 'darwin' ? 2 : 1) };
|
||||
|
||||
// Work around the WebKit GTK scrolling issue.
|
||||
if (browserType.name() === 'webkit' && process.platform === 'linux') {
|
||||
delete contextOptions.hasTouch;
|
||||
delete contextOptions.isMobile;
|
||||
}
|
||||
|
||||
if (contextOptions.isMobile && browserType.name() === 'firefox') {
|
||||
contextOptions.isMobile = undefined
|
||||
}
|
||||
|
||||
// Proxy
|
||||
|
||||
if (options.proxyServer) {
|
||||
launchOptions.proxy = {
|
||||
server: options.proxyServer
|
||||
};
|
||||
}
|
||||
|
||||
const browser = await browserType.launch(launchOptions);
|
||||
|
||||
// Viewport size
|
||||
if (options.viewportSize) {
|
||||
try {
|
||||
const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10));
|
||||
contextOptions.viewport = { width, height };
|
||||
} catch (e) {
|
||||
console.log('Invalid window size format: use "width, height", for example --window-size=800,600');
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
// Geolocation
|
||||
|
||||
if (options.geolocation) {
|
||||
try {
|
||||
const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim()));
|
||||
contextOptions.geolocation = {
|
||||
latitude,
|
||||
longitude
|
||||
};
|
||||
} catch (e) {
|
||||
console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"');
|
||||
process.exit(0);
|
||||
}
|
||||
contextOptions.permissions = ['geolocation'];
|
||||
}
|
||||
|
||||
// User agent
|
||||
|
||||
if (options.userAgent)
|
||||
contextOptions.userAgent = options.userAgent;
|
||||
|
||||
// Lang
|
||||
|
||||
if (options.lang)
|
||||
contextOptions.locale = options.lang;
|
||||
|
||||
// Color scheme
|
||||
|
||||
if (options.colorScheme)
|
||||
contextOptions.colorScheme = options.colorScheme as 'dark' | 'light';
|
||||
|
||||
// Timezone
|
||||
|
||||
if (options.timezone)
|
||||
contextOptions.timezoneId = options.timezone;
|
||||
|
||||
// Close app when the last window closes.
|
||||
|
||||
const context = await browser.newContext(contextOptions);
|
||||
context.on('page', page => {
|
||||
page.on('close', () => {
|
||||
if (browser.contexts().find(c => c.pages().length))
|
||||
return;
|
||||
// Avoid the error when the last page is closed because the browser has been closed.
|
||||
browser.close().catch(e => null);
|
||||
})
|
||||
});
|
||||
if (options.timeout) {
|
||||
context.setDefaultTimeout(parseInt(options.timeout, 10));
|
||||
context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));
|
||||
}
|
||||
|
||||
// Omit options that we add automatically for presentation purpose.
|
||||
delete launchOptions.headless;
|
||||
delete contextOptions.deviceScaleFactor;
|
||||
return { browser, browserName: browserType.name(), context, contextOptions, launchOptions };
|
||||
}
|
||||
|
||||
async function openPage(context: playwright.BrowserContext, url: string | undefined): Promise<Page> {
|
||||
const page = await context.newPage();
|
||||
if (url) {
|
||||
if (!url.startsWith('http') && !url.startsWith("file://"))
|
||||
url = 'http://' + url;
|
||||
await page.goto(url);
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
async function open(options: Options, url: string | undefined, enableRecorder: boolean) {
|
||||
const { context, browserName, launchOptions, contextOptions } = await launchContext(options, false);
|
||||
new ScriptController(browserName, launchOptions, contextOptions, context, process.stdout, enableRecorder, options.device);
|
||||
if (process.env.PWCLI_EXIT_FOR_TEST) {
|
||||
await context.close()
|
||||
process.exit(0)
|
||||
}
|
||||
await openPage(context, url);
|
||||
}
|
||||
|
||||
async function waitForPage(page: Page, captureOptions: CaptureOptions) {
|
||||
if (captureOptions.waitForSelector) {
|
||||
console.log(`Waiting for selector ${captureOptions.waitForSelector}...`);
|
||||
await page.waitForSelector(captureOptions.waitForSelector);
|
||||
}
|
||||
if (captureOptions.waitForTimeout) {
|
||||
console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`);
|
||||
await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10));
|
||||
}
|
||||
}
|
||||
|
||||
async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) {
|
||||
const { browser, context } = await launchContext(options, true);
|
||||
console.log('Navigating to ' + url);
|
||||
const page = await openPage(context, url);
|
||||
await waitForPage(page, captureOptions);
|
||||
console.log('Capturing screenshot into ' + path);
|
||||
await page.screenshot({ path, fullPage: !!captureOptions.fullPage });
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) {
|
||||
if (options.browser !== 'chromium') {
|
||||
console.error('PDF creation is only working with Chromium');
|
||||
process.exit(1);
|
||||
}
|
||||
const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true);
|
||||
console.log('Navigating to ' + url);
|
||||
const page = await openPage(context, url);
|
||||
await waitForPage(page, captureOptions);
|
||||
console.log('Saving as pdf into ' + path);
|
||||
await page.pdf({ path });
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
async function codegen(options: Options, url: string | undefined) {
|
||||
return open(options, url, true);
|
||||
}
|
||||
|
||||
function lookupBrowserType(options: Options): playwright.BrowserType<playwright.WebKitBrowser | playwright.ChromiumBrowser | playwright.FirefoxBrowser> {
|
||||
let name = options.browser;
|
||||
if (options.device) {
|
||||
const device = playwright.devices[options.device];
|
||||
name = device.defaultBrowserType;
|
||||
}
|
||||
switch (name) {
|
||||
case 'chromium': return playwright.chromium!;
|
||||
case 'webkit': return playwright.webkit!;
|
||||
case 'firefox': return playwright.firefox!;
|
||||
case 'cr': return playwright.chromium!;
|
||||
case 'wk': return playwright.webkit!;
|
||||
case 'ff': return playwright.firefox!;
|
||||
}
|
||||
program.help();
|
||||
}
|
||||
|
||||
function validateOptions(options: Options) {
|
||||
if (options.device && !(options.device in playwright.devices)) {
|
||||
console.log(`Device descriptor not found: '${options.device}', available devices are:`);
|
||||
for (let name in playwright.devices)
|
||||
console.log(` "${name}"`);
|
||||
process.exit(0);
|
||||
}
|
||||
if (options.colorScheme && !["light", "dark"].includes(options.colorScheme)) {
|
||||
console.log('Invalid color scheme, should be one of "light", "dark"');
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export class Formatter {
|
||||
private _baseIndent: string;
|
||||
private _baseOffset: string;
|
||||
private _lines: string[] = [];
|
||||
|
||||
constructor(offset = 0) {
|
||||
this._baseIndent = ' '.repeat(2);
|
||||
this._baseOffset = ' '.repeat(offset);
|
||||
}
|
||||
|
||||
prepend(text: string) {
|
||||
this._lines = text.trim().split('\n').map(line => line.trim()).concat(this._lines);
|
||||
}
|
||||
|
||||
add(text: string) {
|
||||
this._lines.push(...text.trim().split('\n').map(line => line.trim()));
|
||||
}
|
||||
|
||||
newLine() {
|
||||
this._lines.push('');
|
||||
}
|
||||
|
||||
format(): string {
|
||||
let spaces = '';
|
||||
let previousLine = '';
|
||||
return this._lines.map((line: string) => {
|
||||
if (line === '')
|
||||
return line;
|
||||
if (line.startsWith('}') || line.startsWith(']'))
|
||||
spaces = spaces.substring(this._baseIndent.length);
|
||||
|
||||
const extraSpaces = /^(for|while|if).*\(.*\)$/.test(previousLine) ? this._baseIndent : '';
|
||||
previousLine = line;
|
||||
|
||||
line = spaces + extraSpaces + line;
|
||||
if (line.endsWith('{') || line.endsWith('['))
|
||||
spaces += this._baseIndent;
|
||||
return this._baseOffset + line;
|
||||
}).join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
export function quote(text: string, char: string = '\'') {
|
||||
if (char === '\'')
|
||||
return char + text.replace(/[']/g, '\\\'') + char;
|
||||
if (char === '"')
|
||||
return char + text.replace(/["]/g, '\\"') + char;
|
||||
if (char === '`')
|
||||
return char + text.replace(/[`]/g, '\\`') + char;
|
||||
throw new Error('Invalid escape char');
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { buildSelector } from "./selectorGenerator";
|
||||
|
||||
export type ParsedSelector = {
|
||||
parts: {
|
||||
name: string,
|
||||
body: string,
|
||||
}[],
|
||||
capture?: number,
|
||||
};
|
||||
|
||||
export interface InjectedScript {
|
||||
parseSelector(selector: string): ParsedSelector;
|
||||
engines: Set<string>;
|
||||
querySelectorAll(selector: ParsedSelector, document: Document): Element[];
|
||||
};
|
||||
|
||||
export class ConsoleAPI {
|
||||
private _injectedScript: InjectedScript;
|
||||
|
||||
constructor(injectedScript: InjectedScript) {
|
||||
this._injectedScript = injectedScript;
|
||||
(window as any).playwright = {
|
||||
$: (selector: string) => this.querySelector(selector),
|
||||
$$: (selector: string) => this.querySelectorAll(selector),
|
||||
inspect: (selector: string) => this.inspect(selector),
|
||||
selector: (element: Element) => this.buildSelector(element).selector,
|
||||
};
|
||||
}
|
||||
|
||||
private _checkSelector(parsed: ParsedSelector) {
|
||||
for (const {name} of parsed.parts) {
|
||||
if (!this._injectedScript.engines.has(name))
|
||||
throw new Error(`Unknown engine "${name}"`);
|
||||
}
|
||||
}
|
||||
|
||||
querySelector(selector: string): (Element | undefined) {
|
||||
if (typeof selector !== 'string')
|
||||
throw new Error(`Usage: playwright.$('Playwright >> selector').`);
|
||||
const parsed = this._injectedScript.parseSelector(selector);
|
||||
this._checkSelector(parsed);
|
||||
const elements = this._injectedScript.querySelectorAll(parsed, document);
|
||||
return elements[0];
|
||||
}
|
||||
|
||||
querySelectorAll(selector: string): Element[] {
|
||||
if (typeof selector !== 'string')
|
||||
throw new Error(`Usage: playwright.$$('Playwright >> selector').`);
|
||||
const parsed = this._injectedScript.parseSelector(selector);
|
||||
this._checkSelector(parsed);
|
||||
return this._injectedScript.querySelectorAll(parsed, document);
|
||||
}
|
||||
|
||||
inspect(selector: string) {
|
||||
if (typeof (window as any).inspect !== 'function')
|
||||
return;
|
||||
if (typeof selector !== 'string')
|
||||
throw new Error(`Usage: playwright.inspect('Playwright >> selector').`);
|
||||
(window as any).inspect(this.querySelector(selector));
|
||||
}
|
||||
|
||||
buildSelector(element: Element): { selector: string, elements: Element[] } {
|
||||
return buildSelector(this._injectedScript, element);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
const templateCache = new Map();
|
||||
|
||||
export interface Element$ extends HTMLElement {
|
||||
$(id: string): HTMLElement;
|
||||
$$(id: string): Iterable<HTMLElement>
|
||||
}
|
||||
|
||||
const BOOLEAN_ATTRS = new Set([
|
||||
'async', 'autofocus', 'autoplay', 'checked', 'contenteditable', 'controls',
|
||||
'default', 'defer', 'disabled', 'expanded', 'formNoValidate', 'frameborder', 'hidden',
|
||||
'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate',
|
||||
'open', 'readonly', 'required', 'reversed', 'scoped', 'selected', 'typemustmatch',
|
||||
]);
|
||||
|
||||
type Sub = {
|
||||
node: Element,
|
||||
type?: string,
|
||||
nameParts?: string[],
|
||||
valueParts?: string[],
|
||||
isSimpleValue?: boolean,
|
||||
attr?: string,
|
||||
nodeIndex?: number
|
||||
};
|
||||
|
||||
export function onDOMEvent(target: EventTarget, name: string, listener: (e: any) => void, capturing = false): () => void {
|
||||
target.addEventListener(name, listener, capturing);
|
||||
return () => {
|
||||
target.removeEventListener(name, listener, capturing);
|
||||
};
|
||||
}
|
||||
|
||||
export function onDOMResize(target: HTMLElement, callback: () => void) {
|
||||
const resizeObserver = new (window as any).ResizeObserver(callback);
|
||||
resizeObserver.observe(target);
|
||||
return () => resizeObserver.disconnect();
|
||||
}
|
||||
|
||||
export function html(strings: TemplateStringsArray, ...values: any): Element$ {
|
||||
let cache = templateCache.get(strings);
|
||||
if (!cache) {
|
||||
cache = prepareTemplate(strings);
|
||||
templateCache.set(strings, cache);
|
||||
}
|
||||
const node = renderTemplate(cache.template, cache.subs, values) as any;
|
||||
if (node.querySelector) {
|
||||
node.$ = node.querySelector.bind(node);
|
||||
node.$$ = node.querySelectorAll.bind(node);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
const SPACE_REGEX = /^\s*\n\s*$/;
|
||||
const MARKER_REGEX = /---dom-template-\d+---/;
|
||||
|
||||
function prepareTemplate(strings: TemplateStringsArray) {
|
||||
const template = document.createElement('template');
|
||||
let html = '';
|
||||
for (let i = 0; i < strings.length - 1; ++i) {
|
||||
html += strings[i];
|
||||
html += `---dom-template-${i}---`;
|
||||
}
|
||||
html += strings[strings.length - 1];
|
||||
template.innerHTML = html;
|
||||
|
||||
const walker = template.ownerDocument.createTreeWalker(
|
||||
template.content, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null, false);
|
||||
const emptyTextNodes: Node[] = [];
|
||||
const subs: Sub[] = [];
|
||||
while (walker.nextNode()) {
|
||||
const node = walker.currentNode;
|
||||
if (node.nodeType === Node.ELEMENT_NODE && MARKER_REGEX.test((node as Element).tagName))
|
||||
throw new Error('Should not use a parameter as an html tag');
|
||||
|
||||
if (node.nodeType === Node.ELEMENT_NODE && (node as Element).hasAttributes()) {
|
||||
const element = node as Element;
|
||||
for (let i = 0; i < element.attributes.length; i++) {
|
||||
const name = element.attributes[i].name;
|
||||
|
||||
const nameParts = name.split(MARKER_REGEX);
|
||||
const valueParts = element.attributes[i].value.split(MARKER_REGEX);
|
||||
const isSimpleValue = valueParts.length === 2 && valueParts[0] === '' && valueParts[1] === '';
|
||||
|
||||
if (nameParts.length > 1 || valueParts.length > 1)
|
||||
subs.push({ node: element, nameParts, valueParts, isSimpleValue, attr: name});
|
||||
}
|
||||
} else if (node.nodeType === Node.TEXT_NODE && MARKER_REGEX.test((node as Text).data)) {
|
||||
const text = node as Text;
|
||||
const texts = text.data.split(MARKER_REGEX);
|
||||
text.data = texts[0];
|
||||
const anchor = node.nextSibling;
|
||||
for (let i = 1; i < texts.length; ++i) {
|
||||
const span = document.createElement('span');
|
||||
node.parentNode!.insertBefore(span, anchor);
|
||||
node.parentNode!.insertBefore(document.createTextNode(texts[i]), anchor);
|
||||
subs.push({
|
||||
node: span,
|
||||
type: 'replace-node',
|
||||
});
|
||||
}
|
||||
if (shouldRemoveTextNode(text))
|
||||
emptyTextNodes.push(text);
|
||||
} else if (node.nodeType === Node.TEXT_NODE && shouldRemoveTextNode((node as Text))) {
|
||||
emptyTextNodes.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
for (const emptyTextNode of emptyTextNodes)
|
||||
(emptyTextNode as any).remove();
|
||||
|
||||
const markedNodes = new Map();
|
||||
for (const sub of subs) {
|
||||
let index = markedNodes.get(sub.node);
|
||||
if (index === undefined) {
|
||||
index = markedNodes.size;
|
||||
sub.node.setAttribute('dom-template-marked', 'true');
|
||||
markedNodes.set(sub.node, index);
|
||||
}
|
||||
sub.nodeIndex = index;
|
||||
}
|
||||
return {template, subs};
|
||||
}
|
||||
|
||||
function shouldRemoveTextNode(node: Text) {
|
||||
if (!node.previousSibling && !node.nextSibling)
|
||||
return !node.data.length;
|
||||
return (!node.previousSibling || node.previousSibling.nodeType === Node.ELEMENT_NODE) &&
|
||||
(!node.nextSibling || node.nextSibling.nodeType === Node.ELEMENT_NODE) &&
|
||||
(!node.data.length || SPACE_REGEX.test(node.data));
|
||||
}
|
||||
|
||||
function renderTemplate(template: HTMLTemplateElement, subs: Sub[], values: (string | Node)[]): DocumentFragment | ChildNode {
|
||||
const content = template.ownerDocument.importNode(template.content, true)!;
|
||||
const boundElements = Array.from(content.querySelectorAll('[dom-template-marked]'));
|
||||
for (const node of boundElements)
|
||||
node.removeAttribute('dom-template-marked');
|
||||
|
||||
let valueIndex = 0;
|
||||
const interpolateText = (texts: string[]) => {
|
||||
let newText = texts[0];
|
||||
for (let i = 1; i < texts.length; ++i) {
|
||||
newText += values[valueIndex++];
|
||||
newText += texts[i];
|
||||
}
|
||||
return newText;
|
||||
};
|
||||
|
||||
for (const sub of subs) {
|
||||
const n = boundElements[sub.nodeIndex!];
|
||||
if (sub.attr) {
|
||||
n.removeAttribute(sub.attr);
|
||||
const name = interpolateText(sub.nameParts!);
|
||||
const value = sub.isSimpleValue ? values[valueIndex++] : interpolateText(sub.valueParts!);
|
||||
if (BOOLEAN_ATTRS.has(name))
|
||||
n.toggleAttribute(name, !!value);
|
||||
else
|
||||
n.setAttribute(name, String(value));
|
||||
} else if (sub.type === 'replace-node') {
|
||||
const replacement = values[valueIndex++];
|
||||
if (Array.isArray(replacement)) {
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (const node of replacement)
|
||||
fragment.appendChild(node);
|
||||
n.replaceWith(fragment);
|
||||
} else if (replacement instanceof Node) {
|
||||
n.replaceWith(replacement);
|
||||
} else {
|
||||
n.replaceWith(document.createTextNode(replacement || ''));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return content.firstChild && content.firstChild === content.lastChild ? content.firstChild : content;
|
||||
}
|
||||
|
||||
export function deepActiveElement() {
|
||||
let activeElement = document.activeElement;
|
||||
while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
|
||||
activeElement = activeElement.shadowRoot.activeElement;
|
||||
return activeElement;
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type * as actions from '../recorderActions';
|
||||
import { ConsoleAPI, InjectedScript } from './consoleApi';
|
||||
import { html } from './html';
|
||||
import { addEventListener, RegisteredListener, removeEventListeners } from './util';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
performPlaywrightAction: (action: actions.Action) => Promise<void>;
|
||||
recordPlaywrightAction: (action: actions.Action) => Promise<void>;
|
||||
commitLastAction: () => Promise<void>;
|
||||
}
|
||||
}
|
||||
|
||||
const scriptSymbol = Symbol('scriptSymbol');
|
||||
|
||||
export class Recorder {
|
||||
private _performingAction = false;
|
||||
private _outerGlassPaneElement: HTMLElement;
|
||||
private _glassPaneShadow: ShadowRoot;
|
||||
private _innerGlassPaneElement: HTMLElement;
|
||||
private _highlightElements: HTMLElement[] = [];
|
||||
private _tooltipElement: HTMLElement;
|
||||
private _listeners: RegisteredListener[] = [];
|
||||
private _hoveredModel: HighlightModel | null = null;
|
||||
private _hoveredElement: HTMLElement | null = null;
|
||||
private _activeModel: HighlightModel | null = null;
|
||||
private _consoleAPI: ConsoleAPI;
|
||||
private _expectProgrammaticKeyUp = false;
|
||||
|
||||
constructor(injectedScript: InjectedScript, consoleAPI: ConsoleAPI) {
|
||||
this._consoleAPI = consoleAPI;
|
||||
|
||||
this._outerGlassPaneElement = html`
|
||||
<x-pw-glass style="
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 1000000;
|
||||
pointer-events: none;
|
||||
display: flex;
|
||||
">
|
||||
</x-pw-glass>`;
|
||||
|
||||
this._tooltipElement = html`<x-pw-tooltip></x-pw-tooltip>`;
|
||||
|
||||
this._innerGlassPaneElement = html`
|
||||
<x-pw-glass-inner style="flex: auto">
|
||||
${this._tooltipElement}
|
||||
</x-pw-glass-inner>`;
|
||||
|
||||
// Use a closed shadow root to prevent selectors matching our internal previews.
|
||||
this._glassPaneShadow = this._outerGlassPaneElement.attachShadow({ mode: 'closed' });
|
||||
this._glassPaneShadow.appendChild(this._innerGlassPaneElement);
|
||||
this._glassPaneShadow.appendChild(html`
|
||||
<style>
|
||||
x-pw-tooltip {
|
||||
align-items: center;
|
||||
backdrop-filter: blur(5px);
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
border-radius: 2px;
|
||||
box-shadow: rgba(0, 0, 0, 0.1) 0px 3.6px 3.7px,
|
||||
rgba(0, 0, 0, 0.15) 0px 12.1px 12.3px,
|
||||
rgba(0, 0, 0, 0.1) 0px -2px 4px,
|
||||
rgba(0, 0, 0, 0.15) 0px -12.1px 24px,
|
||||
rgba(0, 0, 0, 0.25) 0px 54px 55px;
|
||||
color: rgb(204, 204, 204);
|
||||
display: flex;
|
||||
font-family: 'Dank Mono', 'Operator Mono', Inconsolata, 'Fira Mono',
|
||||
'SF Mono', Monaco, 'Droid Sans Mono', 'Source Code Pro', monospace;
|
||||
font-size: 12.8px;
|
||||
font-weight: normal;
|
||||
left: 0;
|
||||
line-height: 1.5;
|
||||
max-width: 600px;
|
||||
padding: 3.2px 5.12px 3.2px;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
}
|
||||
</style>
|
||||
`);
|
||||
setInterval(() => {
|
||||
this._refreshListenersIfNeeded();
|
||||
}, 100);
|
||||
this._consoleAPI = new ConsoleAPI(injectedScript);
|
||||
}
|
||||
|
||||
private _refreshListenersIfNeeded() {
|
||||
if ((document.documentElement as any)[scriptSymbol])
|
||||
return;
|
||||
(document.documentElement as any)[scriptSymbol] = true;
|
||||
removeEventListeners(this._listeners);
|
||||
this._listeners = [
|
||||
addEventListener(document, 'click', event => this._onClick(event as MouseEvent), true),
|
||||
addEventListener(document, 'input', event => this._onInput(event), true),
|
||||
addEventListener(document, 'keydown', event => this._onKeyDown(event as KeyboardEvent), true),
|
||||
addEventListener(document, 'keyup', event => this._onKeyUp(event as KeyboardEvent), true),
|
||||
addEventListener(document, 'mousedown', event => this._onMouseDown(event as MouseEvent), true),
|
||||
addEventListener(document, 'mouseup', event => this._onMouseUp(event as MouseEvent), true),
|
||||
addEventListener(document, 'mousemove', event => this._onMouseMove(event as MouseEvent), true),
|
||||
addEventListener(document, 'mouseleave', event => this._onMouseLeave(event as MouseEvent), true),
|
||||
addEventListener(document, 'focus', event => this._onFocus(event as FocusEvent), true),
|
||||
addEventListener(document, 'scroll', event => {
|
||||
this._hoveredModel = null;
|
||||
this._updateHighlight();
|
||||
}, true),
|
||||
];
|
||||
document.documentElement.appendChild(this._outerGlassPaneElement);
|
||||
if ((window as any)._recorderScriptReadyForTest)
|
||||
(window as any)._recorderScriptReadyForTest();
|
||||
}
|
||||
|
||||
private _actionInProgress(event: Event): boolean {
|
||||
// If Playwright is performing action for us, bail.
|
||||
if (this._performingAction)
|
||||
return true;
|
||||
// Consume as the first thing.
|
||||
consumeEvent(event);
|
||||
return false;
|
||||
}
|
||||
|
||||
private _consumedDueToNoModel(event: Event, model: HighlightModel | null): boolean {
|
||||
if (model)
|
||||
return false;
|
||||
consumeEvent(event);
|
||||
return true;
|
||||
}
|
||||
|
||||
private _consumedDueWrongTarget(event: Event): boolean {
|
||||
if (this._activeModel && this._activeModel.elements[0] === event.target)
|
||||
return false;
|
||||
consumeEvent(event);
|
||||
return true;
|
||||
}
|
||||
|
||||
private _onClick(event: MouseEvent) {
|
||||
if ((event.target as Element).nodeName === 'SELECT')
|
||||
return;
|
||||
if ((event.target as Element).nodeName === 'INPUT') {
|
||||
// Check/uncheck are handled in input.
|
||||
if (((event.target as HTMLInputElement).type || '').toLowerCase() === 'checkbox')
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._actionInProgress(event))
|
||||
return;
|
||||
if (this._consumedDueToNoModel(event, this._hoveredModel))
|
||||
return;
|
||||
|
||||
this._performAction({
|
||||
name: 'click',
|
||||
selector: this._hoveredModel!.selector,
|
||||
signals: [],
|
||||
button: buttonForEvent(event),
|
||||
modifiers: modifiersForEvent(event),
|
||||
clickCount: event.detail
|
||||
});
|
||||
}
|
||||
|
||||
private _onMouseDown(event: MouseEvent) {
|
||||
if (!this._performingAction)
|
||||
consumeEvent(event);
|
||||
this._activeModel = this._hoveredModel;
|
||||
}
|
||||
|
||||
private _onMouseUp(event: MouseEvent) {
|
||||
if (!this._performingAction)
|
||||
consumeEvent(event);
|
||||
}
|
||||
|
||||
private _onMouseMove(event: MouseEvent) {
|
||||
if (this._hoveredElement === event.target)
|
||||
return;
|
||||
this._hoveredElement = event.target as HTMLElement | null;
|
||||
// Mouse moved -> mark last action as committed via committing a commit action.
|
||||
this._commitActionAndUpdateModelForHoveredElement();
|
||||
}
|
||||
|
||||
private _onMouseLeave(event: MouseEvent) {
|
||||
// Leaving iframe.
|
||||
if ((event.target as Node).nodeType === Node.DOCUMENT_NODE) {
|
||||
this._hoveredElement = null;
|
||||
this._commitActionAndUpdateModelForHoveredElement();
|
||||
}
|
||||
}
|
||||
|
||||
private _onFocus(event: FocusEvent) {
|
||||
const result = document.activeElement ? this._consoleAPI.buildSelector(document.activeElement) : null;
|
||||
this._activeModel = result && result.selector ? result : null;
|
||||
if ((window as any)._highlightUpdatedForTest)
|
||||
(window as any)._highlightUpdatedForTest(result ? result.selector : null);
|
||||
}
|
||||
|
||||
private _commitActionAndUpdateModelForHoveredElement() {
|
||||
if (!this._hoveredElement) {
|
||||
this._hoveredModel = null;
|
||||
this._updateHighlight();
|
||||
return;
|
||||
}
|
||||
const hoveredElement = this._hoveredElement;
|
||||
const { selector, elements } = this._consoleAPI.buildSelector(hoveredElement);
|
||||
if ((this._hoveredModel && this._hoveredModel.selector === selector) || this._hoveredElement !== hoveredElement)
|
||||
return;
|
||||
window.commitLastAction();
|
||||
this._hoveredModel = selector ? { selector, elements } : null;
|
||||
this._updateHighlight();
|
||||
if ((window as any)._highlightUpdatedForTest)
|
||||
(window as any)._highlightUpdatedForTest(selector);
|
||||
}
|
||||
|
||||
private _updateHighlight() {
|
||||
const elements = this._hoveredModel ? this._hoveredModel.elements : [];
|
||||
|
||||
// Code below should trigger one layout and leave with the
|
||||
// destroyed layout.
|
||||
|
||||
// Destroy the layout
|
||||
this._tooltipElement.textContent = this._hoveredModel ? this._hoveredModel.selector : '';
|
||||
this._tooltipElement.style.top = '0';
|
||||
this._tooltipElement.style.left = '0';
|
||||
this._tooltipElement.style.display = 'flex';
|
||||
|
||||
// Trigger layout.
|
||||
const boxes = elements.map(e => e.getBoundingClientRect());
|
||||
const tooltipWidth = this._tooltipElement.offsetWidth;
|
||||
const tooltipHeight = this._tooltipElement.offsetHeight;
|
||||
const totalWidth = this._innerGlassPaneElement.offsetWidth;
|
||||
const totalHeight = this._innerGlassPaneElement.offsetHeight;
|
||||
|
||||
// Destroy the layout again.
|
||||
if (boxes.length) {
|
||||
const primaryBox = boxes[0];
|
||||
let anchorLeft = primaryBox.left;
|
||||
if (anchorLeft + tooltipWidth > totalWidth - 5)
|
||||
anchorLeft = totalWidth - tooltipWidth - 5;
|
||||
let anchorTop = primaryBox.bottom + 5;
|
||||
if (anchorTop + tooltipHeight > totalHeight - 5) {
|
||||
// If can't fit below, either position above...
|
||||
if (primaryBox.top > tooltipHeight + 5) {
|
||||
anchorTop = primaryBox.top - tooltipHeight - 5;
|
||||
} else {
|
||||
// Or on top in case of large element
|
||||
anchorTop = totalHeight - 5 - tooltipHeight;
|
||||
}
|
||||
}
|
||||
this._tooltipElement.style.top = anchorTop + 'px';
|
||||
this._tooltipElement.style.left = anchorLeft + 'px';
|
||||
} else {
|
||||
this._tooltipElement.style.display = 'none';
|
||||
}
|
||||
|
||||
const pool = this._highlightElements;
|
||||
this._highlightElements = [];
|
||||
for (const box of boxes) {
|
||||
const highlightElement = pool.length ? pool.shift()! : this._createHighlightElement();
|
||||
highlightElement.style.borderColor = this._highlightElements.length ? 'hotpink' : '#8929ff';
|
||||
highlightElement.style.left = box.x + 'px';
|
||||
highlightElement.style.top = box.y + 'px';
|
||||
highlightElement.style.width = box.width + 'px';
|
||||
highlightElement.style.height = box.height + 'px';
|
||||
highlightElement.style.display = 'block';
|
||||
this._highlightElements.push(highlightElement);
|
||||
}
|
||||
|
||||
for (const highlightElement of pool) {
|
||||
highlightElement.style.display = 'none';
|
||||
this._highlightElements.push(highlightElement);
|
||||
}
|
||||
}
|
||||
|
||||
private _createHighlightElement(): HTMLElement {
|
||||
const highlightElement = html`
|
||||
<x-pw-highlight style="
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border: 1px solid;
|
||||
box-sizing: border-box;">
|
||||
</x-pw-highlight>`;
|
||||
this._glassPaneShadow.appendChild(highlightElement);
|
||||
return highlightElement;
|
||||
}
|
||||
|
||||
private _onInput(event: Event) {
|
||||
if (['INPUT', 'TEXTAREA'].includes((event.target as Element).nodeName)) {
|
||||
const inputElement = event.target as HTMLInputElement;
|
||||
const elementType = (inputElement.type || '').toLowerCase()
|
||||
if (elementType === 'checkbox') {
|
||||
if (this._actionInProgress(event))
|
||||
return;
|
||||
if (this._consumedDueWrongTarget(event))
|
||||
return;
|
||||
this._performAction({
|
||||
name: inputElement.checked ? 'check' : 'uncheck',
|
||||
selector: this._activeModel!.selector,
|
||||
signals: [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (elementType === "file") {
|
||||
window.recordPlaywrightAction({
|
||||
name: 'setInputFiles',
|
||||
selector: this._activeModel!.selector,
|
||||
signals: [],
|
||||
files: [...(inputElement.files || [])].map(file => file.name),
|
||||
});
|
||||
return
|
||||
}
|
||||
|
||||
// Non-navigating actions are simply recorded by Playwright.
|
||||
if (this._consumedDueWrongTarget(event))
|
||||
return;
|
||||
window.recordPlaywrightAction({
|
||||
name: 'fill',
|
||||
selector: this._activeModel!.selector,
|
||||
signals: [],
|
||||
text: inputElement.value,
|
||||
});
|
||||
}
|
||||
|
||||
if ((event.target as Element).nodeName === 'SELECT') {
|
||||
const selectElement = event.target as HTMLSelectElement;
|
||||
if (this._actionInProgress(event))
|
||||
return;
|
||||
this._performAction({
|
||||
name: 'select',
|
||||
selector: this._hoveredModel!.selector,
|
||||
options: [...selectElement.selectedOptions].map(option => option.value),
|
||||
signals: []
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private _shouldGenerateKeyPressFor(event: KeyboardEvent): boolean {
|
||||
// Backspace, Delete are changing input, will handle it there.
|
||||
if (['Backspace', 'Delete'].includes(event.key))
|
||||
return false;
|
||||
// Ignore the QWERTZ shortcut for creating a at sign on MacOS
|
||||
if (event.key === "@" && event.code === "KeyL")
|
||||
return false
|
||||
// Allow and ignore common used shortcut for pasting.
|
||||
if (process.platform === 'darwin') {
|
||||
if (event.key === 'v' && event.metaKey)
|
||||
return false;
|
||||
} else {
|
||||
if (event.key === 'v' && event.ctrlKey)
|
||||
return false;
|
||||
if (event.key === 'Insert' && event.shiftKey)
|
||||
return false;
|
||||
}
|
||||
if (['Shift', 'Control', 'Meta', 'Alt'].includes(event.key))
|
||||
return false;
|
||||
const hasModifier = event.ctrlKey || event.altKey || event.metaKey;
|
||||
if (event.key.length === 1 && !hasModifier)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private _onKeyDown(event: KeyboardEvent) {
|
||||
if (!this._shouldGenerateKeyPressFor(event))
|
||||
return;
|
||||
if (this._actionInProgress(event)) {
|
||||
this._expectProgrammaticKeyUp = true;
|
||||
return;
|
||||
}
|
||||
if (this._consumedDueWrongTarget(event))
|
||||
return;
|
||||
this._performAction({
|
||||
name: 'press',
|
||||
selector: this._activeModel!.selector,
|
||||
signals: [],
|
||||
key: event.key,
|
||||
modifiers: modifiersForEvent(event),
|
||||
});
|
||||
}
|
||||
|
||||
private _onKeyUp(event: KeyboardEvent) {
|
||||
if (!this._shouldGenerateKeyPressFor(event))
|
||||
return;
|
||||
|
||||
// Only allow programmatic keyups, ignore user input.
|
||||
if (!this._expectProgrammaticKeyUp) {
|
||||
consumeEvent(event);
|
||||
return;
|
||||
}
|
||||
this._expectProgrammaticKeyUp = false;
|
||||
}
|
||||
|
||||
private async _performAction(action: actions.Action) {
|
||||
this._performingAction = true;
|
||||
await window.performPlaywrightAction(action);
|
||||
this._performingAction = false;
|
||||
if ((window as any)._actionPerformedForTest)
|
||||
(window as any)._actionPerformedForTest();
|
||||
}
|
||||
}
|
||||
|
||||
function modifiersForEvent(event: MouseEvent | KeyboardEvent): number {
|
||||
return (event.altKey ? 1 : 0) | (event.ctrlKey ? 2 : 0) | (event.metaKey ? 4 : 0) | (event.shiftKey ? 8 : 0);
|
||||
}
|
||||
|
||||
function buttonForEvent(event: MouseEvent): 'left' | 'middle' | 'right' {
|
||||
switch (event.which) {
|
||||
case 1: return 'left';
|
||||
case 2: return 'middle';
|
||||
case 3: return 'right';
|
||||
}
|
||||
return 'left';
|
||||
}
|
||||
|
||||
function consumeEvent(e: Event) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
}
|
||||
|
||||
type HighlightModel = {
|
||||
selector: string;
|
||||
elements: Element[];
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { ConsoleAPI, InjectedScript } from './consoleApi';
|
||||
import { Recorder } from './recorder';
|
||||
|
||||
export default class Script {
|
||||
private _consoleAPI: ConsoleAPI | undefined;
|
||||
private _recorder: Recorder | undefined;
|
||||
|
||||
constructor(injectedScript: InjectedScript, options: { enableRecorder: boolean }) {
|
||||
if ((window as any).playwright)
|
||||
return;
|
||||
this._consoleAPI = new ConsoleAPI(injectedScript);
|
||||
if (options.enableRecorder)
|
||||
this._recorder = new Recorder(injectedScript, this._consoleAPI);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const InlineSource = require('../../utils/webpack-inline-source-plugin');
|
||||
|
||||
module.exports = {
|
||||
entry: path.join(__dirname, 'script.ts'),
|
||||
devtool: 'source-map',
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
loader: 'ts-loader',
|
||||
options: {
|
||||
transpileOnly: true
|
||||
},
|
||||
exclude: /node_modules/
|
||||
}
|
||||
]
|
||||
},
|
||||
resolve: {
|
||||
extensions: [ '.tsx', '.ts', '.js' ]
|
||||
},
|
||||
output: {
|
||||
libraryTarget: 'var',
|
||||
filename: 'scriptSource.js',
|
||||
path: path.resolve(__dirname, '../../lib/packed')
|
||||
},
|
||||
plugins: [
|
||||
new InlineSource(path.join(__dirname, '..', 'generated', 'scriptSource.ts')),
|
||||
]
|
||||
};
|
||||
@@ -0,0 +1,157 @@
|
||||
import { ConsoleAPI, InjectedScript } from './consoleApi';
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { XPathEngine } from './xpathSelectorEngine';
|
||||
|
||||
export function buildSelector(injectedScript: InjectedScript, targetElement: Element): { selector: string, elements: Element[] } {
|
||||
const path: SelectorToken[] = [];
|
||||
let numberOfMatchingElements = Number.MAX_SAFE_INTEGER;
|
||||
for (let element: Element | null = targetElement; element && element !== document.documentElement; element = element.parentElement) {
|
||||
const selector = buildSelectorCandidate(injectedScript, element);
|
||||
if (!selector)
|
||||
continue;
|
||||
const fullSelector = joinSelector([selector, ...path]);
|
||||
const parsedSelector = injectedScript.parseSelector(fullSelector);
|
||||
const selectorTargets = injectedScript.querySelectorAll(parsedSelector, targetElement.ownerDocument);
|
||||
if (!selectorTargets.length)
|
||||
break;
|
||||
if (selectorTargets[0] === targetElement)
|
||||
return { selector: fullSelector, elements: selectorTargets };
|
||||
if (selectorTargets.length && numberOfMatchingElements > selectorTargets.length) {
|
||||
numberOfMatchingElements = selectorTargets.length;
|
||||
path.unshift(selector);
|
||||
}
|
||||
}
|
||||
const xpathSelector = XPathEngine.create(document.documentElement, targetElement, 'default')!;
|
||||
const parsedSelector = injectedScript.parseSelector(xpathSelector);
|
||||
return {
|
||||
selector: xpathSelector,
|
||||
elements: injectedScript.querySelectorAll(parsedSelector, targetElement.ownerDocument)
|
||||
};
|
||||
}
|
||||
|
||||
function buildSelectorCandidate(injectedScript: InjectedScript, element: Element): SelectorToken | null {
|
||||
const nodeName = element.nodeName.toLowerCase();
|
||||
for (const attribute of ['data-testid', 'data-test-id', 'data-test']) {
|
||||
if (element.hasAttribute(attribute))
|
||||
return { engine: 'css', selector: `${nodeName}[${attribute}=${quoteString(element.getAttribute(attribute)!)}]` };
|
||||
}
|
||||
for (const attribute of ['aria-label', 'role']) {
|
||||
if (element.hasAttribute(attribute))
|
||||
return { engine: 'css', selector: `${element.nodeName.toLocaleLowerCase()}[${attribute}=${quoteString(element.getAttribute(attribute)!)}]` };
|
||||
}
|
||||
if (['INPUT', 'TEXTAREA'].includes(element.nodeName)) {
|
||||
const nodeNameLowercase = element.nodeName.toLowerCase()
|
||||
if (element.getAttribute('name'))
|
||||
return { engine: 'css', selector: `${nodeNameLowercase}[name=${quoteString(element.getAttribute('name')!)}]` };
|
||||
if (element.getAttribute('placeholder'))
|
||||
return { engine: 'css', selector: `${nodeNameLowercase}[placeholder=${quoteString(element.getAttribute('placeholder')!)}]` };
|
||||
if (element.getAttribute('type'))
|
||||
return { engine: 'css', selector: `${nodeNameLowercase}[type=${quoteString(element.getAttribute('type')!)}]` };
|
||||
} else if (element.nodeName === 'IMG') {
|
||||
if (element.getAttribute('alt'))
|
||||
return { engine: 'css', selector: `img[alt=${quoteString(element.getAttribute('alt')!)}]` };
|
||||
}
|
||||
const textSelector = textSelectorForElement(element);
|
||||
if (textSelector)
|
||||
return { engine: 'text', selector: textSelector };
|
||||
|
||||
// De-prioritize id, but still use it as a last resort.
|
||||
const idAttr = element.getAttribute('id');
|
||||
if (idAttr && !isGuidLike(idAttr))
|
||||
return { engine: 'css', selector: `${nodeName}[id=${quoteString(idAttr!)}]` };
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function textSelectorForElement(node: Node): string | null {
|
||||
const maxLength = 30;
|
||||
let needsRegex = false;
|
||||
let trimmedText: string | null = null;
|
||||
for (const child of node.childNodes) {
|
||||
if (child.nodeType !== Node.TEXT_NODE)
|
||||
continue;
|
||||
if (child.textContent && child.textContent.trim()) {
|
||||
if (trimmedText)
|
||||
return null;
|
||||
trimmedText = child.textContent.trim().substr(0, maxLength);
|
||||
needsRegex = child.textContent !== trimmedText;
|
||||
} else {
|
||||
needsRegex = true;
|
||||
}
|
||||
}
|
||||
if (!trimmedText)
|
||||
return null;
|
||||
return needsRegex ? `/.*${escapeForRegex(trimmedText)}.*/` : `"${trimmedText}"`;
|
||||
}
|
||||
|
||||
function escapeForRegex(text: string): string {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
function quoteString(text: string): string {
|
||||
return `"${text.replaceAll(/"/g, '\\"')}"`;
|
||||
}
|
||||
|
||||
type SelectorToken = {
|
||||
engine: string;
|
||||
selector: string;
|
||||
};
|
||||
|
||||
function joinSelector(path: SelectorToken[]): string {
|
||||
const tokens = [];
|
||||
let lastEngine = '';
|
||||
for (const { engine, selector } of path) {
|
||||
if (tokens.length && (lastEngine !== 'css' || engine !== 'css'))
|
||||
tokens.push('>>');
|
||||
lastEngine = engine;
|
||||
if (engine === 'css')
|
||||
tokens.push(selector);
|
||||
else
|
||||
tokens.push(`${engine}=${selector}`);
|
||||
}
|
||||
return tokens.join(' ');
|
||||
}
|
||||
|
||||
function isGuidLike(id: string): boolean {
|
||||
let lastCharacterType: 'lower' | 'upper' | 'digit' | 'other' | undefined;
|
||||
let transitionCount = 0;
|
||||
for (let i = 0; i < id.length; ++i) {
|
||||
const c = id[i];
|
||||
let characterType: 'lower' | 'upper' | 'digit' | 'other';
|
||||
if (c === '-' || c === '_')
|
||||
continue;
|
||||
if (c >= 'a' && c <= 'z')
|
||||
characterType = 'lower';
|
||||
else if (c >= 'A' && c <= 'Z')
|
||||
characterType = 'upper';
|
||||
else if (c >= '0' && c <= '9')
|
||||
characterType = 'digit';
|
||||
else
|
||||
characterType = 'other';
|
||||
|
||||
if (characterType === 'lower' && lastCharacterType === 'upper') {
|
||||
lastCharacterType = characterType;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lastCharacterType && lastCharacterType !== characterType)
|
||||
++transitionCount;
|
||||
lastCharacterType = characterType;
|
||||
}
|
||||
return transitionCount >= id.length / 4;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Copyright 2017 Google Inc. All rights reserved.
|
||||
* Modifications copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export type RegisteredListener = {
|
||||
target: EventTarget;
|
||||
eventName: string;
|
||||
listener: EventListener;
|
||||
useCapture?: boolean;
|
||||
};
|
||||
|
||||
export function addEventListener(target: EventTarget, eventName: string, listener: EventListener, useCapture?: boolean): RegisteredListener {
|
||||
target.addEventListener(eventName, listener, useCapture);
|
||||
return { target, eventName, listener, useCapture };
|
||||
}
|
||||
|
||||
export function removeEventListeners(listeners: RegisteredListener[]) {
|
||||
for (const listener of listeners)
|
||||
listener.target.removeEventListener(listener.eventName, listener.listener, listener.useCapture);
|
||||
listeners.splice(0, listeners.length);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
const maxTextLength = 80;
|
||||
const minMeaningfulSelectorLegth = 100;
|
||||
type SelectorRoot = Element;
|
||||
type SelectorType = 'default' | 'notext';
|
||||
|
||||
export const XPathEngine = {
|
||||
create(root: SelectorRoot, targetElement: Element, type: SelectorType): string | undefined {
|
||||
const maybeDocument = root instanceof Document ? root : root.ownerDocument;
|
||||
if (!maybeDocument)
|
||||
return;
|
||||
const document = maybeDocument;
|
||||
|
||||
const xpathCache = new Map<string, Element[]>();
|
||||
const tokens: string[] = [];
|
||||
|
||||
function evaluateXPath(expression: string): Element[] {
|
||||
let nodes: Element[] | undefined = xpathCache.get(expression);
|
||||
if (!nodes) {
|
||||
nodes = [];
|
||||
try {
|
||||
const result = document.evaluate(expression, root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);
|
||||
for (let node = result.iterateNext(); node; node = result.iterateNext()) {
|
||||
if (node.nodeType === Node.ELEMENT_NODE)
|
||||
nodes.push(node as Element);
|
||||
}
|
||||
} catch (e) {
|
||||
}
|
||||
xpathCache.set(expression, nodes);
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
function uniqueXPathSelector(prefix?: string): string | undefined {
|
||||
const path = tokens.slice();
|
||||
if (prefix)
|
||||
path.unshift(prefix);
|
||||
let selector = '//' + path.join('/');
|
||||
while (selector.includes('///'))
|
||||
selector = selector.replace('///', '//');
|
||||
if (selector.endsWith('/'))
|
||||
selector = selector.substring(0, selector.length - 1);
|
||||
const nodes: Element[] = evaluateXPath(selector);
|
||||
if (nodes[0] === targetElement)
|
||||
return selector;
|
||||
|
||||
// If we are looking at a small set of elements with long selector, fall back to ordinal.
|
||||
if (nodes.length < 5 && selector.length > minMeaningfulSelectorLegth) {
|
||||
const index = nodes.indexOf(targetElement);
|
||||
if (index !== -1)
|
||||
return `(${selector})[${index + 1}]`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function escapeAndCap(text: string) {
|
||||
text = text.substring(0, maxTextLength);
|
||||
// XPath 1.0 does not support quote escaping.
|
||||
// 1. If there are no single quotes - use them.
|
||||
if (text.indexOf(`'`) === -1)
|
||||
return `'${text}'`;
|
||||
// 2. If there are no double quotes - use them to enclose text.
|
||||
if (text.indexOf(`"`) === -1)
|
||||
return `"${text}"`;
|
||||
// 3. Otherwise, use popular |concat| trick.
|
||||
const Q = `'`;
|
||||
return `concat(${text.split(Q).map(token => Q + token + Q).join(`, "'", `)})`;
|
||||
}
|
||||
|
||||
const defaultAttributes = new Set([ 'title', 'aria-label', 'disabled', 'role' ]);
|
||||
const importantAttributes = new Map<string, string[]>([
|
||||
[ 'form', [ 'action' ] ],
|
||||
[ 'img', [ 'alt' ] ],
|
||||
[ 'input', [ 'placeholder', 'type', 'name' ] ],
|
||||
[ 'textarea', [ 'placeholder', 'type', 'name' ] ],
|
||||
]);
|
||||
|
||||
let usedTextConditions = false;
|
||||
for (let element: Element | null = targetElement; element && element !== root; element = element.parentElement) {
|
||||
const nodeName = element.nodeName.toLowerCase();
|
||||
const tag = nodeName === 'svg' ? '*' : nodeName;
|
||||
|
||||
const tagConditions = [];
|
||||
if (nodeName === 'svg')
|
||||
tagConditions.push('local-name()="svg"');
|
||||
|
||||
const attrConditions: string[] = [];
|
||||
const importantAttrs = [ ...defaultAttributes, ...(importantAttributes.get(tag) || []) ];
|
||||
for (const attr of importantAttrs) {
|
||||
const value = element.getAttribute(attr);
|
||||
if (value && value.length < maxTextLength)
|
||||
attrConditions.push(`normalize-space(@${attr})=${escapeAndCap(value)}`);
|
||||
else if (value)
|
||||
attrConditions.push(`starts-with(normalize-space(@${attr}), ${escapeAndCap(value)})`);
|
||||
}
|
||||
|
||||
const text = document.evaluate('normalize-space(.)', element).stringValue;
|
||||
const textConditions = [];
|
||||
if (tag !== 'select' && text.length && !usedTextConditions) {
|
||||
if (text.length < maxTextLength)
|
||||
textConditions.push(`normalize-space(.)=${escapeAndCap(text)}`);
|
||||
else
|
||||
textConditions.push(`starts-with(normalize-space(.), ${escapeAndCap(text)})`);
|
||||
usedTextConditions = true;
|
||||
}
|
||||
|
||||
// Always retain the last tag.
|
||||
const conditions = [ ...tagConditions, ...textConditions, ...attrConditions ];
|
||||
const token = conditions.length ? `${tag}[${conditions.join(' and ')}]` : (tokens.length ? '' : tag);
|
||||
const selector = uniqueXPathSelector(token);
|
||||
if (selector)
|
||||
return selector;
|
||||
|
||||
const parent = element.parentElement;
|
||||
let ordinal = -1;
|
||||
if (parent) {
|
||||
const siblings = Array.from(parent.children);
|
||||
const sameTagSiblings = siblings.filter(sibling => (sibling).nodeName.toLowerCase() === nodeName);
|
||||
if (sameTagSiblings.length > 1)
|
||||
ordinal = sameTagSiblings.indexOf(element);
|
||||
}
|
||||
|
||||
// Do not include text into this token, only tag / attributes.
|
||||
// Topmost node will get all the text.
|
||||
const conditionsString = conditions.length ? `[${conditions.join(' and ')}]` : '';
|
||||
const ordinalString = ordinal >= 0 ? `[${ordinal + 1}]` : '';
|
||||
tokens.unshift(`${tag}${ordinalString}${conditionsString}`);
|
||||
}
|
||||
return uniqueXPathSelector();
|
||||
},
|
||||
|
||||
query(root: SelectorRoot, selector: string): Element | undefined {
|
||||
const document = root instanceof Document ? root : root.ownerDocument;
|
||||
if (!document)
|
||||
return;
|
||||
const it = document.evaluate(selector, root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);
|
||||
for (let node = it.iterateNext(); node; node = it.iterateNext()) {
|
||||
if (node.nodeType === Node.ELEMENT_NODE)
|
||||
return node as Element;
|
||||
}
|
||||
},
|
||||
|
||||
queryAll(root: SelectorRoot, selector: string): Element[] {
|
||||
const result: Element[] = [];
|
||||
const document = root instanceof Document ? root : root.ownerDocument;
|
||||
if (!document)
|
||||
return result;
|
||||
const it = document.evaluate(selector, root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);
|
||||
for (let node = it.iterateNext(); node; node = it.iterateNext()) {
|
||||
if (node.nodeType === Node.ELEMENT_NODE)
|
||||
result.push(node as Element);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export type ActionName =
|
||||
'check' |
|
||||
'click' |
|
||||
'closePage' |
|
||||
'fill' |
|
||||
'navigate' |
|
||||
'openPage' |
|
||||
'press' |
|
||||
'select' |
|
||||
'uncheck' |
|
||||
'setInputFiles';
|
||||
|
||||
export type ActionBase = {
|
||||
name: ActionName,
|
||||
signals: Signal[],
|
||||
}
|
||||
|
||||
export type ClickAction = ActionBase & {
|
||||
name: 'click',
|
||||
selector: string,
|
||||
button: 'left' | 'middle' | 'right',
|
||||
modifiers: number,
|
||||
clickCount: number,
|
||||
};
|
||||
|
||||
export type CheckAction = ActionBase & {
|
||||
name: 'check',
|
||||
selector: string,
|
||||
};
|
||||
|
||||
export type UncheckAction = ActionBase & {
|
||||
name: 'uncheck',
|
||||
selector: string,
|
||||
};
|
||||
|
||||
export type FillAction = ActionBase & {
|
||||
name: 'fill',
|
||||
selector: string,
|
||||
text: string,
|
||||
};
|
||||
|
||||
export type NavigateAction = ActionBase & {
|
||||
name: 'navigate',
|
||||
url: string,
|
||||
};
|
||||
|
||||
export type OpenPageAction = ActionBase & {
|
||||
name: 'openPage',
|
||||
url: string,
|
||||
};
|
||||
|
||||
export type ClosesPageAction = ActionBase & {
|
||||
name: 'closePage',
|
||||
};
|
||||
|
||||
export type PressAction = ActionBase & {
|
||||
name: 'press',
|
||||
selector: string,
|
||||
key: string,
|
||||
modifiers: number,
|
||||
};
|
||||
|
||||
export type SelectAction = ActionBase & {
|
||||
name: 'select',
|
||||
selector: string,
|
||||
options: string[],
|
||||
};
|
||||
|
||||
export type SetInputFilesAction = ActionBase & {
|
||||
name: 'setInputFiles',
|
||||
selector: string,
|
||||
files: string[],
|
||||
};
|
||||
|
||||
export type Action = ClickAction | CheckAction | ClosesPageAction | OpenPageAction | UncheckAction | FillAction | NavigateAction | PressAction | SelectAction | SetInputFilesAction;
|
||||
|
||||
// Signals.
|
||||
|
||||
export type NavigationSignal = {
|
||||
name: 'navigation',
|
||||
url: string,
|
||||
};
|
||||
|
||||
export type PopupSignal = {
|
||||
name: 'popup',
|
||||
popupAlias: string,
|
||||
};
|
||||
|
||||
export type DownloadSignal = {
|
||||
name: 'download',
|
||||
};
|
||||
|
||||
export type DialogSignal = {
|
||||
name: 'dialog',
|
||||
};
|
||||
|
||||
export type Signal = NavigationSignal | PopupSignal | DownloadSignal | DialogSignal;
|
||||
|
||||
export function actionTitle(action: Action): string {
|
||||
switch (action.name) {
|
||||
case 'openPage':
|
||||
return `Open new page`;
|
||||
case 'closePage':
|
||||
return `Close page`;
|
||||
case 'check':
|
||||
return `Check ${action.selector}`;
|
||||
case 'uncheck':
|
||||
return `Uncheck ${action.selector}`;
|
||||
case 'click': {
|
||||
if (action.clickCount === 1)
|
||||
return `Click ${action.selector}`;
|
||||
if (action.clickCount === 2)
|
||||
return `Double click ${action.selector}`;
|
||||
if (action.clickCount === 3)
|
||||
return `Triple click ${action.selector}`;
|
||||
return `${action.clickCount}× click`;
|
||||
}
|
||||
case 'fill':
|
||||
return `Fill ${action.selector}`;
|
||||
case 'setInputFiles':
|
||||
if (action.files.length === 0)
|
||||
return `Clear selected files`;
|
||||
else
|
||||
return `Upload ${action.files.length === 1 ? action.files[0] : action.files.join(", ")}`;
|
||||
case 'navigate':
|
||||
return `Go to ${action.url}`;
|
||||
case 'press':
|
||||
return `Press ${action.key}` + (action.modifiers ? ' with modifiers' : '');
|
||||
case 'select':
|
||||
return `Select ${action.selector}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import * as playwright from 'playwright';
|
||||
import { Writable } from 'stream';
|
||||
import * as actions from './recorderActions';
|
||||
import { TerminalOutput, ActionInContext } from './terminalOutput';
|
||||
import { BindingSource, toClickOptions, toModifiers } from './utils';
|
||||
|
||||
export class RecorderController {
|
||||
private _output: TerminalOutput;
|
||||
private _pageAliases = new Map<playwright.Page, string>();
|
||||
private _lastPopupOrdinal = 0;
|
||||
private _timers = new Set<NodeJS.Timeout>();
|
||||
|
||||
constructor(browserName: string, launchOptions: playwright.LaunchOptions, contextOptions: playwright.BrowserContextOptions, context: playwright.BrowserContext, output: Writable, deviceName: string | undefined) {
|
||||
this._output = new TerminalOutput(browserName, launchOptions, contextOptions, output, deviceName);
|
||||
|
||||
// Input actions that potentially lead to navigation are intercepted on the page and are
|
||||
// performed by the Playwright.
|
||||
context.exposeBinding('performPlaywrightAction',
|
||||
(source: BindingSource, action: actions.Action) => this._performAction(source.frame, source.page, action)).catch(e => {});
|
||||
|
||||
// Other non-essential actions are simply being recorded.
|
||||
context.exposeBinding('recordPlaywrightAction',
|
||||
(source: BindingSource, action: actions.Action) => this._recordAction(source.frame, source.page, action)).catch(e => {});
|
||||
|
||||
// Commits last action so that no furhter signals are added to it.
|
||||
context.exposeBinding('commitLastAction',
|
||||
(source: BindingSource, action: actions.Action) => this._output.commitLastAction()).catch(e => {});
|
||||
|
||||
context.on('page', page => this._onPage(page));
|
||||
for (const page of context.pages())
|
||||
this._onPage(page);
|
||||
|
||||
context.once('close', () => {
|
||||
for (const timer of this._timers)
|
||||
clearTimeout(timer);
|
||||
this._timers.clear();
|
||||
});
|
||||
}
|
||||
|
||||
private async _onPage(page: playwright.Page) {
|
||||
// First page is called page, others are called popup1, popup2, etc.
|
||||
page.on('close', () => {
|
||||
this._pageAliases.delete(page);
|
||||
this._output.addAction({
|
||||
pageAlias,
|
||||
frame: page.mainFrame(),
|
||||
committed: true,
|
||||
action: {
|
||||
name: 'closePage',
|
||||
signals: [],
|
||||
}
|
||||
});
|
||||
});
|
||||
page.on('framenavigated', frame => this._onFrameNavigated(frame, page));
|
||||
page.on('download', download => this._onDownload(page, download));
|
||||
page.on('popup', popup => this._onPopup(page, popup));
|
||||
page.on('dialog', dialog => this._onDialog(page, dialog));
|
||||
const suffix = this._pageAliases.size ? String(++this._lastPopupOrdinal) : '';
|
||||
const pageAlias = 'page' + suffix;
|
||||
this._pageAliases.set(page, pageAlias);
|
||||
|
||||
const isPopup = !!await page.opener();
|
||||
// Could happen due to the await above.
|
||||
if (page.isClosed())
|
||||
return;
|
||||
if (!isPopup) {
|
||||
this._output.addAction({
|
||||
pageAlias,
|
||||
frame: page.mainFrame(),
|
||||
committed: true,
|
||||
action: {
|
||||
name: 'openPage',
|
||||
url: page.url(),
|
||||
signals: [],
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async _performAction(frame: playwright.Frame, page: playwright.Page, action: actions.Action) {
|
||||
const actionInContext: ActionInContext = {
|
||||
pageAlias: this._pageAliases.get(page)!,
|
||||
frame,
|
||||
action
|
||||
};
|
||||
this._output.willPerformAction(actionInContext);
|
||||
if (action.name === 'click') {
|
||||
const { options } = toClickOptions(action);
|
||||
await frame.click(action.selector, options);
|
||||
}
|
||||
if (action.name === 'press') {
|
||||
const modifiers = toModifiers(action.modifiers);
|
||||
const shortcut = [...modifiers, action.key].join('+');
|
||||
await frame.press(action.selector, shortcut);
|
||||
}
|
||||
if (action.name === 'check')
|
||||
await frame.check(action.selector);
|
||||
if (action.name === 'uncheck')
|
||||
await frame.uncheck(action.selector);
|
||||
if (action.name === 'select')
|
||||
await frame.selectOption(action.selector, action.options);
|
||||
const timer = setTimeout(() => {
|
||||
actionInContext.committed = true;
|
||||
this._timers.delete(timer);
|
||||
}, 5000);
|
||||
this._output.didPerformAction(actionInContext);
|
||||
this._timers.add(timer);
|
||||
}
|
||||
|
||||
private async _recordAction(frame: playwright.Frame, page: playwright.Page, action: actions.Action) {
|
||||
// We are lacking frame.page() in Playwright.
|
||||
this._output.addAction({
|
||||
pageAlias: this._pageAliases.get(page)!,
|
||||
frame,
|
||||
action
|
||||
});
|
||||
}
|
||||
|
||||
private _onFrameNavigated(frame: playwright.Frame, page: playwright.Page) {
|
||||
if (frame.parentFrame())
|
||||
return;
|
||||
const pageAlias = this._pageAliases.get(page);
|
||||
this._output.signal(pageAlias!, frame, { name: 'navigation', url: frame.url() });
|
||||
}
|
||||
|
||||
private _onPopup(page: playwright.Page, popup: playwright.Page) {
|
||||
const pageAlias = this._pageAliases.get(page)!;
|
||||
const popupAlias = this._pageAliases.get(popup)!;
|
||||
this._output.signal(pageAlias, page.mainFrame(), { name: 'popup', popupAlias });
|
||||
}
|
||||
private _onDownload(page: playwright.Page, download: playwright.Download) {
|
||||
const pageAlias = this._pageAliases.get(page)!;
|
||||
this._output.signal(pageAlias, page.mainFrame(), { name: 'download' });
|
||||
}
|
||||
|
||||
private _onDialog(page: playwright.Page, download: playwright.Dialog) {
|
||||
const pageAlias = this._pageAliases.get(page)!;
|
||||
this._output.signal(pageAlias, page.mainFrame(), { name: 'dialog' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import * as playwright from 'playwright';
|
||||
import * as injectedScriptSource from './generated/scriptSource';
|
||||
import { Writable } from 'stream';
|
||||
import { RecorderController } from './recorderController';
|
||||
|
||||
export class ScriptController {
|
||||
private _recorder: RecorderController | undefined;
|
||||
|
||||
constructor(browserName: string, launchOptions: playwright.LaunchOptions, contextOptions: playwright.BrowserContextOptions, context: playwright.BrowserContext, output: Writable, enableRecorder: boolean, deviceName: string | undefined) {
|
||||
if (enableRecorder)
|
||||
this._recorder = new RecorderController(browserName, launchOptions, contextOptions, context, output, deviceName);
|
||||
context.on('page', page => this._onPage(page));
|
||||
for (const page of context.pages())
|
||||
this._onPage(page);
|
||||
}
|
||||
|
||||
private async _onPage(page: playwright.Page) {
|
||||
// Install in all frames.
|
||||
for (const frame of page.frames())
|
||||
this._ensureInstalledInFrame(frame);
|
||||
page.on('framenavigated', frame => this._ensureInstalledInFrame(frame));
|
||||
}
|
||||
|
||||
private async _ensureInstalledInFrame(frame: playwright.Frame) {
|
||||
try {
|
||||
const frameAsAny = frame as any;
|
||||
await frameAsAny._extendInjectedScript(injectedScriptSource.source, { enableRecorder: !!this._recorder });
|
||||
} catch (e) {
|
||||
const str = e.toString();
|
||||
// Cr
|
||||
if (str.includes('Execution context was destroyed'))
|
||||
return;
|
||||
// Wk
|
||||
if (str.includes('Target closed'))
|
||||
return;
|
||||
// Ff
|
||||
if (str.includes('The page has been closed'))
|
||||
return;
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import * as querystring from 'querystring';
|
||||
import * as playwright from 'playwright';
|
||||
import { Writable } from 'stream';
|
||||
import { quote, Formatter } from './formatter';
|
||||
import { Action, actionTitle, NavigationSignal, PopupSignal, Signal, DownloadSignal, DialogSignal } from './recorderActions';
|
||||
import { MouseClickOptions, toModifiers } from './utils';
|
||||
import { highlight } from 'highlight.js';
|
||||
import { Frame } from 'playwright';
|
||||
|
||||
export type ActionInContext = {
|
||||
pageAlias: string;
|
||||
frame: Frame;
|
||||
action: Action;
|
||||
committed?: boolean;
|
||||
}
|
||||
|
||||
export class TerminalOutput {
|
||||
private _currentAction: ActionInContext | undefined;
|
||||
private _lastAction: ActionInContext | undefined;
|
||||
private _lastActionText: string | undefined;
|
||||
private _out: Writable;
|
||||
|
||||
constructor(browserName: string, launchOptions: playwright.LaunchOptions, contextOptions: playwright.BrowserContextOptions, out: Writable, deviceName: string | undefined) {
|
||||
this._out = out;
|
||||
const formatter = new Formatter();
|
||||
launchOptions = { headless: false, ...launchOptions };
|
||||
|
||||
formatter.add(`
|
||||
const { ${browserName}${deviceName ? ', devices' : ''} } = require('playwright');
|
||||
|
||||
(async () => {
|
||||
const browser = await ${browserName}.launch(${formatObjectOrVoid(launchOptions)});
|
||||
const context = await browser.newContext(${formatContextOptions(contextOptions, deviceName)});
|
||||
})();`);
|
||||
this._out.write(this._highlight(formatter.format()) + '\n');
|
||||
}
|
||||
|
||||
_highlight(text: string) {
|
||||
let highlightedCode = highlight('typescript', text).value;
|
||||
highlightedCode = querystring.unescape(highlightedCode);
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-keyword">/g, '\x1b[38;5;205m');
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-built_in">/g, '\x1b[38;5;220m');
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-literal">/g, '\x1b[38;5;159m');
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-number">/g, '\x1b[38;5;78m');
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-string">/g, '\x1b[38;5;130m');
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-comment">/g, '\x1b[38;5;23m');
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-subst">/g, '\x1b[38;5;242m');
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-function">/g, '');
|
||||
highlightedCode = highlightedCode.replace(/<span class="hljs-params">/g, '');
|
||||
highlightedCode = highlightedCode.replace(/<\/span>/g, '\x1b[0m');
|
||||
highlightedCode = highlightedCode.replace(/'/g, "'");
|
||||
highlightedCode = highlightedCode.replace(/"/g, '"');
|
||||
highlightedCode = highlightedCode.replace(/>/g, '>');
|
||||
highlightedCode = highlightedCode.replace(/</g, '<');
|
||||
highlightedCode = highlightedCode.replace(/&/g, '&');
|
||||
return highlightedCode;
|
||||
}
|
||||
|
||||
addAction(action: ActionInContext) {
|
||||
this.willPerformAction(action);
|
||||
this.didPerformAction(action);
|
||||
}
|
||||
|
||||
willPerformAction(action: ActionInContext) {
|
||||
this._currentAction = action;
|
||||
}
|
||||
|
||||
didPerformAction(actionInContext: ActionInContext) {
|
||||
const { action, pageAlias } = actionInContext;
|
||||
let eraseLastAction = false;
|
||||
if (this._lastAction && this._lastAction.pageAlias === pageAlias) {
|
||||
const { action: lastAction } = this._lastAction;
|
||||
// We augment last action based on the type.
|
||||
if (this._lastAction && action.name === 'fill' && lastAction.name === 'fill') {
|
||||
if (action.selector === lastAction.selector)
|
||||
eraseLastAction = true;
|
||||
}
|
||||
if (lastAction && action.name === 'click' && lastAction.name === 'click') {
|
||||
if (action.selector === lastAction.selector && action.clickCount > lastAction.clickCount)
|
||||
eraseLastAction = true;
|
||||
}
|
||||
if (lastAction && action.name === 'navigate' && lastAction.name === 'navigate') {
|
||||
if (action.url === lastAction.url)
|
||||
return;
|
||||
}
|
||||
for (const name of ['check', 'uncheck']) {
|
||||
if (lastAction && action.name === name && lastAction.name === 'click') {
|
||||
if ((action as any).selector === (lastAction as any).selector)
|
||||
eraseLastAction = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
this._printAction(actionInContext, eraseLastAction);
|
||||
}
|
||||
|
||||
commitLastAction() {
|
||||
const action = this._lastAction;
|
||||
if (action)
|
||||
action.committed = true;
|
||||
}
|
||||
|
||||
_printAction(actionInContext: ActionInContext, eraseLastAction: boolean) {
|
||||
// We erase terminating `})();` at all times.
|
||||
let eraseLines = 1;
|
||||
if (eraseLastAction && this._lastActionText)
|
||||
eraseLines += this._lastActionText.split('\n').length;
|
||||
// And we erase the last action too if augmenting.
|
||||
for (let i = 0; i < eraseLines; ++i)
|
||||
this._out.write('\u001B[1A\u001B[2K');
|
||||
|
||||
const performingAction = !!this._currentAction;
|
||||
this._currentAction = undefined;
|
||||
this._lastAction = actionInContext;
|
||||
this._lastActionText = this._generateAction(actionInContext, performingAction);
|
||||
this._out.write(this._lastActionText + '\n})();\n');
|
||||
}
|
||||
|
||||
signal(pageAlias: string, frame: playwright.Frame, signal: Signal) {
|
||||
// Signal either arrives while action is being performed or shortly after.
|
||||
if (this._currentAction) {
|
||||
this._currentAction.action.signals.push(signal);
|
||||
return;
|
||||
}
|
||||
if (this._lastAction && !this._lastAction.committed) {
|
||||
this._lastAction.action.signals.push(signal);
|
||||
this._printAction(this._lastAction, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (signal.name === 'navigation') {
|
||||
this.addAction({
|
||||
pageAlias,
|
||||
frame,
|
||||
committed: true,
|
||||
action: {
|
||||
name: 'navigate',
|
||||
url: frame.url(),
|
||||
signals: [],
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private _generateAction(actionInContext: ActionInContext, performingAction: boolean): string {
|
||||
const { action, pageAlias, frame } = actionInContext;
|
||||
const formatter = new Formatter(2);
|
||||
formatter.newLine();
|
||||
formatter.add('// ' + actionTitle(action));
|
||||
|
||||
if (action.name === 'openPage') {
|
||||
formatter.add(`const ${pageAlias} = await context.newPage();`);
|
||||
if (action.url && action.url !== 'about:blank' && action.url !== 'chrome://newtab/')
|
||||
formatter.add(`${pageAlias}.load('${action.url}');`);
|
||||
return this._highlight(formatter.format());
|
||||
}
|
||||
|
||||
const subject = !frame.parentFrame() ? pageAlias :
|
||||
`${pageAlias}.frame(${formatObject({ url: frame.url() })})`;
|
||||
|
||||
let navigationSignal: NavigationSignal | undefined;
|
||||
let popupSignal: PopupSignal | undefined;
|
||||
let downloadSignal: DownloadSignal | undefined;
|
||||
let dialogSignal: DialogSignal | undefined;
|
||||
for (const signal of action.signals) {
|
||||
if (signal.name === 'navigation')
|
||||
navigationSignal = signal;
|
||||
else if (signal.name === 'popup')
|
||||
popupSignal = signal;
|
||||
else if (signal.name === 'download')
|
||||
downloadSignal = signal;
|
||||
else if (signal.name === 'dialog')
|
||||
dialogSignal = signal;
|
||||
}
|
||||
|
||||
if (dialogSignal) {
|
||||
formatter.add(` page.once('dialog', dialog => {
|
||||
console.log(\`Dialog message: $\{dialog.message()}\`);
|
||||
dialog.dismiss().catch(() => {});
|
||||
});`)
|
||||
}
|
||||
|
||||
const waitForNavigation = navigationSignal && !performingAction;
|
||||
const assertNavigation = navigationSignal && performingAction;
|
||||
|
||||
const emitPromiseAll = waitForNavigation || popupSignal || downloadSignal;
|
||||
if (emitPromiseAll) {
|
||||
// Generate either await Promise.all([]) or
|
||||
// const [popup1] = await Promise.all([]).
|
||||
let leftHandSide = '';
|
||||
if (popupSignal)
|
||||
leftHandSide = `const [${popupSignal.popupAlias}] = `;
|
||||
else if (downloadSignal)
|
||||
leftHandSide = `const [download] = `;
|
||||
formatter.add(`${leftHandSide}await Promise.all([`);
|
||||
}
|
||||
|
||||
// Popup signals.
|
||||
if (popupSignal)
|
||||
formatter.add(`${pageAlias}.waitForEvent('popup'),`);
|
||||
|
||||
// Navigation signal.
|
||||
if (waitForNavigation)
|
||||
formatter.add(`${pageAlias}.waitForNavigation(/*{ url: ${quote(navigationSignal!.url)} }*/),`);
|
||||
|
||||
// Download signals.
|
||||
if (downloadSignal)
|
||||
formatter.add(`${pageAlias}.waitForEvent('download'),`);
|
||||
|
||||
const prefix = (popupSignal || waitForNavigation || downloadSignal) ? '' : 'await ';
|
||||
const actionCall = this._generateActionCall(action);
|
||||
const suffix = (waitForNavigation || emitPromiseAll) ? '' : ';';
|
||||
formatter.add(`${prefix}${subject}.${actionCall}${suffix}`);
|
||||
|
||||
if (emitPromiseAll)
|
||||
formatter.add(`]);`);
|
||||
else if (assertNavigation)
|
||||
formatter.add(` // assert.equal(${pageAlias}.url(), ${quote(navigationSignal!.url)});`);
|
||||
return this._highlight(formatter.format());
|
||||
}
|
||||
|
||||
private _generateActionCall(action: Action): string {
|
||||
switch (action.name) {
|
||||
case 'openPage':
|
||||
throw Error('Not reached');
|
||||
case 'closePage':
|
||||
return 'close()';
|
||||
case 'click': {
|
||||
let method = 'click';
|
||||
if (action.clickCount === 2)
|
||||
method = 'dblclick';
|
||||
const modifiers = toModifiers(action.modifiers);
|
||||
const options: MouseClickOptions = {};
|
||||
if (action.button !== 'left')
|
||||
options.button = action.button;
|
||||
if (modifiers.length)
|
||||
options.modifiers = modifiers;
|
||||
if (action.clickCount > 2)
|
||||
options.clickCount = action.clickCount;
|
||||
const optionsString = formatOptions(options);
|
||||
return `${method}(${quote(action.selector)}${optionsString})`;
|
||||
}
|
||||
case 'check':
|
||||
return `check(${quote(action.selector)})`;
|
||||
case 'uncheck':
|
||||
return `uncheck(${quote(action.selector)})`;
|
||||
case 'fill':
|
||||
return `fill(${quote(action.selector)}, ${quote(action.text)})`;
|
||||
case 'setInputFiles':
|
||||
return `setInputFiles(${quote(action.selector)}, ${formatObject(action.files.length === 1 ? action.files[0] : action.files)})`;
|
||||
case 'press': {
|
||||
const modifiers = toModifiers(action.modifiers);
|
||||
const shortcut = [...modifiers, action.key].join('+');
|
||||
return `press(${quote(action.selector)}, ${quote(shortcut)})`;
|
||||
}
|
||||
case 'navigate':
|
||||
return `goto(${quote(action.url)})`;
|
||||
case 'select':
|
||||
return `selectOption(${quote(action.selector)}, ${formatObject(action.options.length > 1 ? action.options : action.options[0])})`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatOptions(value: any): string {
|
||||
const keys = Object.keys(value);
|
||||
if (!keys.length)
|
||||
return '';
|
||||
return ', ' + formatObject(value);
|
||||
}
|
||||
|
||||
function formatObject(value: any, indent = ' '): string {
|
||||
if (typeof value === 'string')
|
||||
return quote(value);
|
||||
if (Array.isArray(value))
|
||||
return `[${value.map(o => formatObject(o)).join(', ')}]`;
|
||||
if (typeof value === 'object') {
|
||||
const keys = Object.keys(value);
|
||||
if (!keys.length)
|
||||
return '{}';
|
||||
const tokens: string[] = [];
|
||||
for (const key of keys)
|
||||
tokens.push(`${key}: ${formatObject(value[key])}`);
|
||||
return `{\n${indent}${tokens.join(`,\n${indent}`)}\n}`;
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function formatObjectOrVoid(value: any, indent = ' '): string {
|
||||
const result = formatObject(value, indent);
|
||||
return result === '{}' ? '' : result;
|
||||
}
|
||||
|
||||
function formatContextOptions(options: playwright.BrowserContextOptions, deviceName: string | undefined): string {
|
||||
const device = deviceName && playwright.devices[deviceName];
|
||||
if (!device)
|
||||
return formatObjectOrVoid(options);
|
||||
// Filter out all the properties from the device descriptor.
|
||||
const cleanedOptions: Record<string, any> = {}
|
||||
for(const property in options)
|
||||
if ((device as any)[property] !== (options as any)[property])
|
||||
cleanedOptions[property] = (options as any)[property]
|
||||
let serializedObject = formatObjectOrVoid(cleanedOptions);
|
||||
// When there are no additional context options, we still want to spread the device inside.
|
||||
if (!serializedObject)
|
||||
serializedObject = '{\n}';
|
||||
const lines = serializedObject.split('\n');
|
||||
lines.splice(1, 0, `...devices['${deviceName}'],`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import * as playwright from 'playwright';
|
||||
import * as actions from './recorderActions';
|
||||
|
||||
let __dummy: { page: playwright.Page };
|
||||
export type MouseClickOptions = Parameters<typeof __dummy.page.click>[1];
|
||||
|
||||
// TODO: we are missing types for this in Playwright.
|
||||
export type BindingSource = { frame: playwright.Frame, page: playwright.Page };
|
||||
|
||||
export function toClickOptions(action: actions.ClickAction): { method: 'click' | 'dblclick', options: MouseClickOptions } {
|
||||
let method: 'click' | 'dblclick' = 'click';
|
||||
if (action.clickCount === 2)
|
||||
method = 'dblclick';
|
||||
const modifiers = toModifiers(action.modifiers);
|
||||
const options: MouseClickOptions = {};
|
||||
if (action.button !== 'left')
|
||||
options.button = action.button;
|
||||
if (modifiers.length)
|
||||
options.modifiers = modifiers;
|
||||
if (action.clickCount > 2)
|
||||
options.clickCount = action.clickCount;
|
||||
return { method, options };
|
||||
}
|
||||
|
||||
export function toModifiers(modifiers: number): ('Alt' | 'Control' | 'Meta' | 'Shift')[] {
|
||||
const result: ('Alt' | 'Control' | 'Meta' | 'Shift')[] = [];
|
||||
if (modifiers & 1)
|
||||
result.push('Alt');
|
||||
if (modifiers & 2)
|
||||
result.push('Control');
|
||||
if (modifiers & 4)
|
||||
result.push('Meta');
|
||||
if (modifiers & 8)
|
||||
result.push('Shift');
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
contents of the file
|
||||
@@ -0,0 +1 @@
|
||||
contents of the file
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import * as path from 'path';
|
||||
import { fixtures} from './playwright.fixtures';
|
||||
const { it, expect } = fixtures;
|
||||
|
||||
const emptyHTML = "file://" + path.join(__dirname, "assets", "empty.html")
|
||||
|
||||
it('should print the correct imports and context options', async ({ runCLI }) => {
|
||||
const cli = runCLI(['codegen', emptyHTML]);
|
||||
const expectedResult = `const { chromium } = require('playwright');
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless: false
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
})();`;
|
||||
await cli.waitFor(expectedResult);
|
||||
expect(cli.text()).toContain(expectedResult);
|
||||
});
|
||||
|
||||
it('should print the correct context options for custom settings', async ({ runCLI }) => {
|
||||
const cli = runCLI(['--color-scheme=light', 'codegen', emptyHTML]);
|
||||
const expectedResult = `const { chromium } = require('playwright');
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless: false
|
||||
});
|
||||
const context = await browser.newContext({
|
||||
colorScheme: 'light'
|
||||
});
|
||||
})();`;
|
||||
await cli.waitFor(expectedResult);
|
||||
expect(cli.text()).toContain(expectedResult);
|
||||
});
|
||||
|
||||
|
||||
it('should print the correct context options when using a device', async ({ runCLI }) => {
|
||||
const cli = runCLI(['--device=Pixel 2', 'codegen', emptyHTML])
|
||||
const expectedResult = `const { chromium, devices } = require('playwright');
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless: false
|
||||
});
|
||||
const context = await browser.newContext({
|
||||
...devices['Pixel 2'],
|
||||
});
|
||||
})();`
|
||||
await cli.waitFor(expectedResult)
|
||||
expect(cli.text()).toContain(expectedResult)
|
||||
});
|
||||
|
||||
it('should print the correct context options when using a device and additional options', async ({ runCLI }) => {
|
||||
const cli = runCLI(['--color-scheme=light', '--device=Pixel 2', 'codegen', emptyHTML]);
|
||||
const expectedResult = `const { chromium, devices } = require('playwright');
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless: false
|
||||
});
|
||||
const context = await browser.newContext({
|
||||
...devices['Pixel 2'],
|
||||
colorScheme: 'light'
|
||||
});
|
||||
})();`;
|
||||
await cli.waitFor(expectedResult);
|
||||
expect(cli.text()).toContain(expectedResult);
|
||||
});
|
||||
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* Copyright Microsoft Corporation. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import * as http from 'http'
|
||||
import * as path from 'path';
|
||||
import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
|
||||
import * as playwright from 'playwright';
|
||||
import { fixtures as baseFixtures } from '@playwright/test-runner';
|
||||
import { ScriptController } from '../lib/scriptController';
|
||||
import { Page } from 'playwright';
|
||||
|
||||
type WorkerFixtures = {
|
||||
browserType: playwright.BrowserType<playwright.Browser>;
|
||||
browserName: string;
|
||||
browser: playwright.Browser;
|
||||
httpServer: httpServer;
|
||||
};
|
||||
|
||||
type TestFixtures = {
|
||||
contextWrapper: { context: playwright.BrowserContext, output: WritableBuffer };
|
||||
page: playwright.Page;
|
||||
recorder: Recorder;
|
||||
runCLI: (args: string[]) => CLIMock;
|
||||
};
|
||||
|
||||
export const fixtures = baseFixtures.extend<WorkerFixtures, TestFixtures>();
|
||||
|
||||
interface httpServer {
|
||||
setHandler: (handler: http.RequestListener) => void
|
||||
PREFIX: string
|
||||
}
|
||||
|
||||
export function isChromium() {
|
||||
return baseFixtures.parameters.browserName === 'chromium';
|
||||
}
|
||||
|
||||
export function isFirefox() {
|
||||
return baseFixtures.parameters.browserName === 'firefox';
|
||||
}
|
||||
|
||||
export function isWebKit() {
|
||||
return baseFixtures.parameters.browserName === 'webkit';
|
||||
}
|
||||
|
||||
export function isMac() {
|
||||
return process.platform === 'darwin';
|
||||
}
|
||||
|
||||
fixtures.registerWorkerFixture('browserType', async ({ browserName }, test) => {
|
||||
const browserType = playwright[browserName];
|
||||
await test(browserType);
|
||||
});
|
||||
|
||||
fixtures.registerWorkerFixture('browserName', async ({ }, test) => {
|
||||
await test(process.env.BROWSER || 'chromium');
|
||||
});
|
||||
|
||||
fixtures.registerWorkerFixture('browser', async ({ browserType }, test) => {
|
||||
const browser = await browserType.launch({
|
||||
headless: !process.env.HEADFUL
|
||||
});
|
||||
await test(browser);
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
fixtures.registerWorkerFixture('httpServer', async ({parallelIndex}, runTest) => {
|
||||
let handler = (req: http.IncomingMessage, res: http.ServerResponse) => res.end()
|
||||
const port = 8907 + parallelIndex * 2;
|
||||
const server = http.createServer((req: http.IncomingMessage, res: http.ServerResponse)=> handler(req, res)).listen(port);
|
||||
await runTest({
|
||||
setHandler: newHandler => handler = newHandler,
|
||||
PREFIX: `http://127.0.0.1:${port}`,
|
||||
})
|
||||
server.close()
|
||||
})
|
||||
|
||||
fixtures.registerFixture('contextWrapper', async ({ browser }, runTest, info) => {
|
||||
const context = await browser.newContext();
|
||||
const output = new WritableBuffer();
|
||||
new ScriptController('chromium', {}, {}, context, output, true);
|
||||
await runTest({ context, output });
|
||||
await context.close();
|
||||
});
|
||||
|
||||
fixtures.registerFixture('recorder', async ({ contextWrapper }, runTest) => {
|
||||
const page = await contextWrapper.context.newPage();
|
||||
if (process.env.PWCONSOLE)
|
||||
page.on('console', console.log);
|
||||
await runTest(new Recorder(page, contextWrapper.output));
|
||||
await page.close();
|
||||
});
|
||||
|
||||
fixtures.registerFixture('page', async ({ recorder }, runTest) => {
|
||||
await runTest(recorder.page);
|
||||
});
|
||||
|
||||
function removeAnsiColors(input: string): string {
|
||||
const pattern = [
|
||||
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
|
||||
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
|
||||
].join('|');
|
||||
return input.replace(new RegExp(pattern, 'g'), '');
|
||||
}
|
||||
|
||||
class WritableBuffer {
|
||||
lines: string[];
|
||||
private _callback: () => void;
|
||||
_text: string;
|
||||
|
||||
constructor() {
|
||||
this.lines = [];
|
||||
}
|
||||
|
||||
write(chunk: string) {
|
||||
if (chunk === '\u001B[F\u001B[2K') {
|
||||
this.lines.pop();
|
||||
return;
|
||||
}
|
||||
this.lines.push(...chunk.split('\n'));
|
||||
if (this._callback && chunk.includes(this._text))
|
||||
this._callback();
|
||||
}
|
||||
|
||||
_waitFor(text: string): Promise<void> {
|
||||
if (this.lines.join('\n').includes(text))
|
||||
return Promise.resolve();
|
||||
this._text = text;
|
||||
return new Promise(f => this._callback = f);
|
||||
}
|
||||
|
||||
data() {
|
||||
return this.lines.join('\n');
|
||||
}
|
||||
|
||||
text() {
|
||||
return removeAnsiColors(this.data())
|
||||
}
|
||||
}
|
||||
|
||||
class Recorder {
|
||||
page: playwright.Page;
|
||||
_output: WritableBuffer;
|
||||
_highlightCallback: Function
|
||||
_highlightInstalled: boolean
|
||||
_actionReporterInstalled: boolean
|
||||
_actionPerformedCallback: Function
|
||||
|
||||
constructor(page: playwright.Page, output: WritableBuffer) {
|
||||
this.page = page;
|
||||
this._output = output;
|
||||
this._highlightCallback = () => { };
|
||||
this._highlightInstalled = false;
|
||||
this._actionReporterInstalled = false;
|
||||
this._actionPerformedCallback = () => { };
|
||||
}
|
||||
|
||||
async setContentAndWait(content: string, url: string = 'about:blank') {
|
||||
await this.setPageContentAndWait(this.page, content, url);
|
||||
}
|
||||
|
||||
async setPageContentAndWait(page: Page, content: string, url: string = 'about:blank') {
|
||||
let callback;
|
||||
const result = new Promise(f => callback = f);
|
||||
await page.goto(url);
|
||||
await page.exposeBinding('_recorderScriptReadyForTest', (source, arg) => callback(arg));
|
||||
await Promise.all([
|
||||
result,
|
||||
page.setContent(content)
|
||||
]);
|
||||
}
|
||||
|
||||
async waitForOutput(text: string): Promise<void> {
|
||||
await this._output._waitFor(text);
|
||||
}
|
||||
|
||||
output(): string {
|
||||
return this._output.text();
|
||||
}
|
||||
|
||||
async waitForHighlight(action: () => Promise<void>): Promise<string> {
|
||||
if (!this._highlightInstalled) {
|
||||
this._highlightInstalled = true;
|
||||
await this.page.exposeBinding('_highlightUpdatedForTest', (source, arg) => this._highlightCallback(arg));
|
||||
}
|
||||
const [ generatedSelector ] = await Promise.all([
|
||||
new Promise<string>(f => this._highlightCallback = f),
|
||||
action()
|
||||
]);
|
||||
return generatedSelector;
|
||||
}
|
||||
|
||||
async waitForActionPerformed(): Promise<void> {
|
||||
if (!this._actionReporterInstalled) {
|
||||
this._actionReporterInstalled = true;
|
||||
await this.page.exposeBinding('_actionPerformedForTest', (source, arg) => this._actionPerformedCallback(arg));
|
||||
}
|
||||
await new Promise(f => this._actionPerformedCallback = f);
|
||||
}
|
||||
|
||||
async hoverOverElement(selector: string): Promise<string> {
|
||||
return this.waitForHighlight(() => this.page.dispatchEvent(selector, 'mousemove', { detail: 1 }));
|
||||
}
|
||||
|
||||
async focusElement(selector: string): Promise<string> {
|
||||
return this.waitForHighlight(() => this.page.focus(selector));
|
||||
}
|
||||
}
|
||||
|
||||
fixtures.registerFixture('runCLI', async ({ }, runTest, info) => {
|
||||
let cli: CLIMock
|
||||
const cliFactory = (args: string[]) => {
|
||||
cli = new CLIMock(args);
|
||||
return cli
|
||||
}
|
||||
await runTest(cliFactory);
|
||||
cli.kill()
|
||||
});
|
||||
|
||||
class CLIMock {
|
||||
private process: ChildProcessWithoutNullStreams
|
||||
private lines: string[]
|
||||
private waitForText: string
|
||||
private waitForCallback: () => void;
|
||||
constructor(args: string[]) {
|
||||
this.lines = []
|
||||
this.process = spawn('node', [
|
||||
path.join(__dirname, '..', 'lib', 'cli.js'),
|
||||
...args
|
||||
], {
|
||||
env: {
|
||||
...process.env,
|
||||
PWCLI_EXIT_FOR_TEST: "1"
|
||||
}
|
||||
});
|
||||
this.process.stdout.on('data', line => {
|
||||
this.lines.push(removeAnsiColors(line.toString()))
|
||||
if (this.waitForCallback && this.lines.join('\n').includes(this.waitForText))
|
||||
this.waitForCallback()
|
||||
})
|
||||
}
|
||||
async waitFor(text: string): Promise<void> {
|
||||
if (this.lines.join('\n').includes(text))
|
||||
return Promise.resolve();
|
||||
this.waitForText = text;
|
||||
return new Promise(f => this.waitForCallback = f);
|
||||
}
|
||||
text() {
|
||||
return removeAnsiColors(this.lines.join('\n'))
|
||||
}
|
||||
kill() {
|
||||
this.process.kill()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { fixtures, isChromium, isWebKit, isFirefox, isMac } from './playwright.fixtures';
|
||||
import * as http from 'http';
|
||||
import * as url from 'url';
|
||||
const { it, expect } = fixtures;
|
||||
|
||||
it('should click', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<button onclick="console.log('click')">Submit</button>`);
|
||||
|
||||
const selector = await recorder.hoverOverElement('button');
|
||||
expect(selector).toBe('text="Submit"');
|
||||
|
||||
const [message] = await Promise.all([
|
||||
page.waitForEvent('console'),
|
||||
recorder.waitForOutput('click'),
|
||||
page.dispatchEvent('button', 'click', { detail: 1 })
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Click text="Submit"
|
||||
await page.click('text="Submit"');`);
|
||||
expect(message.text()).toBe('click');
|
||||
});
|
||||
|
||||
it('should not target selector preview by text regexp', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<span>dummy</span>`);
|
||||
|
||||
// Force highlight.
|
||||
await recorder.hoverOverElement('span');
|
||||
|
||||
// Append text after highlight.
|
||||
await page.evaluate(() => {
|
||||
const div = document.createElement('div');
|
||||
div.setAttribute('onclick', "console.log('click')");
|
||||
div.textContent = ' Some long text here ';
|
||||
document.documentElement.appendChild(div);
|
||||
});
|
||||
|
||||
const selector = await recorder.hoverOverElement('div');
|
||||
expect(selector).toBe('text=/.*Some long text here.*/');
|
||||
|
||||
// Sanity check that selector does not match our highlight.
|
||||
const divContents = await page.$eval(selector, div => div.outerHTML);
|
||||
expect(divContents).toBe(`<div onclick="console.log('click')"> Some long text here </div>`);
|
||||
|
||||
const [message] = await Promise.all([
|
||||
page.waitForEvent('console'),
|
||||
recorder.waitForOutput('click'),
|
||||
page.dispatchEvent('div', 'click', { detail: 1 })
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Click text=/.*Some long text here.*/
|
||||
await page.click('text=/.*Some long text here.*/');`);
|
||||
expect(message.text()).toBe('click');
|
||||
});
|
||||
|
||||
it('should fill', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<input id="input" name="name" oninput="console.log(input.value)"></input>`);
|
||||
const selector = await recorder.focusElement('input');
|
||||
expect(selector).toBe('input[name="name"]');
|
||||
|
||||
const [message] = await Promise.all([
|
||||
page.waitForEvent('console'),
|
||||
recorder.waitForOutput('fill'),
|
||||
page.fill('input', 'John')
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Fill input[name="name"]
|
||||
await page.fill('input[name="name"]', 'John');`);
|
||||
expect(message.text()).toBe('John');
|
||||
});
|
||||
|
||||
it('should fill textarea', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<textarea id="textarea" name="name" oninput="console.log(textarea.value)"></textarea>`);
|
||||
const selector = await recorder.focusElement('textarea');
|
||||
expect(selector).toBe('textarea[name="name"]');
|
||||
|
||||
const [message] = await Promise.all([
|
||||
page.waitForEvent('console'),
|
||||
recorder.waitForOutput('fill'),
|
||||
page.fill('textarea', 'John')
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Fill textarea[name="name"]
|
||||
await page.fill('textarea[name="name"]', 'John');`);
|
||||
expect(message.text()).toBe('John');
|
||||
});
|
||||
|
||||
it('should press', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<input name="name" onkeypress="console.log('press')"></input>`);
|
||||
|
||||
const selector = await recorder.focusElement('input');
|
||||
expect(selector).toBe('input[name="name"]');
|
||||
|
||||
const messages = [];
|
||||
page.on('console', message => messages.push(message)),
|
||||
await Promise.all([
|
||||
recorder.waitForActionPerformed(),
|
||||
recorder.waitForOutput('press'),
|
||||
page.press('input', 'Shift+Enter')
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Press Enter with modifiers
|
||||
await page.press('input[name="name"]', 'Shift+Enter');`);
|
||||
expect(messages[0].text()).toBe('press');
|
||||
});
|
||||
|
||||
it('should update selected element after pressing Tab', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<input name="one"></input>
|
||||
<input name="two"></input>
|
||||
`);
|
||||
|
||||
await page.click('input[name="one"]');
|
||||
await recorder.waitForOutput('click');
|
||||
await page.keyboard.type('foobar123');
|
||||
await recorder.waitForOutput('foobar123');
|
||||
|
||||
await page.keyboard.press('Tab');
|
||||
await recorder.waitForOutput('Tab');
|
||||
await page.keyboard.type('barfoo321');
|
||||
await recorder.waitForOutput('barfoo321')
|
||||
|
||||
expect(recorder.output()).toContain(`
|
||||
// Fill input[name="one"]
|
||||
await page.fill('input[name="one"]', 'foobar123');`);
|
||||
|
||||
expect(recorder.output()).toContain(`
|
||||
// Press Tab
|
||||
await page.press('input[name="one"]', 'Tab');`);
|
||||
|
||||
expect(recorder.output()).toContain(`
|
||||
// Fill input[name="two"]
|
||||
await page.fill('input[name="two"]', 'barfoo321');`);
|
||||
});
|
||||
|
||||
it('should record ArrowDown', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<input name="name" onkeydown="console.log('press:' + event.key)"></input>`);
|
||||
|
||||
const selector = await recorder.focusElement('input');
|
||||
expect(selector).toBe('input[name="name"]');
|
||||
|
||||
const messages = [];
|
||||
page.on('console', message => {
|
||||
messages.push(message);
|
||||
}),
|
||||
await Promise.all([
|
||||
recorder.waitForActionPerformed(),
|
||||
recorder.waitForOutput('press'),
|
||||
page.press('input', 'ArrowDown')
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Press ArrowDown
|
||||
await page.press('input[name="name"]', 'ArrowDown');`);
|
||||
expect(messages[0].text()).toBe('press:ArrowDown');
|
||||
});
|
||||
|
||||
it('should emit single keyup on ArrowDown', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<input name="name" onkeydown="console.log('down:' + event.key)" onkeyup="console.log('up:' + event.key)"></input>`);
|
||||
|
||||
const selector = await recorder.focusElement('input');
|
||||
expect(selector).toBe('input[name="name"]');
|
||||
|
||||
const messages = [];
|
||||
page.on('console', message => {
|
||||
messages.push(message);
|
||||
}),
|
||||
await Promise.all([
|
||||
recorder.waitForActionPerformed(),
|
||||
recorder.waitForOutput('press'),
|
||||
page.press('input', 'ArrowDown')
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Press ArrowDown
|
||||
await page.press('input[name="name"]', 'ArrowDown');`);
|
||||
expect(messages.length).toBe(2);
|
||||
expect(messages[0].text()).toBe('down:ArrowDown');
|
||||
expect(messages[1].text()).toBe('up:ArrowDown');
|
||||
});
|
||||
|
||||
it('should check', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="console.log(checkbox.checked)"></input>`);
|
||||
|
||||
const selector = await recorder.hoverOverElement('input');
|
||||
expect(selector).toBe('input[name="accept"]');
|
||||
|
||||
const [message] = await Promise.all([
|
||||
page.waitForEvent('console'),
|
||||
recorder.waitForOutput('check'),
|
||||
page.click('input')
|
||||
]);
|
||||
await recorder.waitForOutput('check');
|
||||
expect(recorder.output()).toContain(`
|
||||
// Check input[name="accept"]
|
||||
await page.check('input[name="accept"]');`);
|
||||
expect(message.text()).toBe('true');
|
||||
});
|
||||
|
||||
it('should check with keyboard', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="console.log(checkbox.checked)"></input>`);
|
||||
|
||||
const selector = await recorder.focusElement('input');
|
||||
expect(selector).toBe('input[name="accept"]');
|
||||
|
||||
const [message] = await Promise.all([
|
||||
page.waitForEvent('console'),
|
||||
recorder.waitForOutput('check'),
|
||||
page.keyboard.press('Space')
|
||||
]);
|
||||
await recorder.waitForOutput('check');
|
||||
expect(recorder.output()).toContain(`
|
||||
// Check input[name="accept"]
|
||||
await page.check('input[name="accept"]');`);
|
||||
expect(message.text()).toBe('true');
|
||||
});
|
||||
|
||||
it('should uncheck', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" checked name="accept" onchange="console.log(checkbox.checked)"></input>`);
|
||||
|
||||
const selector = await recorder.hoverOverElement('input');
|
||||
expect(selector).toBe('input[name="accept"]');
|
||||
|
||||
const [message] = await Promise.all([
|
||||
page.waitForEvent('console'),
|
||||
recorder.waitForOutput('uncheck'),
|
||||
page.click('input')
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Uncheck input[name="accept"]
|
||||
await page.uncheck('input[name="accept"]');`);
|
||||
expect(message.text()).toBe('false');
|
||||
});
|
||||
|
||||
it('should select', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait('<select id="age" onchange="console.log(age.selectedOptions[0].value)"><option value="1"><option value="2"></select>');
|
||||
|
||||
const selector = await recorder.hoverOverElement('select');
|
||||
expect(selector).toBe('select[id="age"]');
|
||||
|
||||
const [message] = await Promise.all([
|
||||
page.waitForEvent('console'),
|
||||
recorder.waitForOutput('select'),
|
||||
page.selectOption('select', '2')
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Select select[id="age"]
|
||||
await page.selectOption('select[id="age"]', '2');`);
|
||||
expect(message.text()).toBe('2');
|
||||
});
|
||||
|
||||
it('should await popup', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait('<a target=_blank rel=noopener href="about:blank">link</a>');
|
||||
|
||||
const selector = await recorder.hoverOverElement('a');
|
||||
expect(selector).toBe('text="link"');
|
||||
|
||||
const [popup] = await Promise.all([
|
||||
page.context().waitForEvent('page'),
|
||||
recorder.waitForOutput('waitForEvent'),
|
||||
page.dispatchEvent('a', 'click', { detail: 1 })
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Click text="link"
|
||||
const [page1] = await Promise.all([
|
||||
page.waitForEvent('popup'),
|
||||
page.click('text="link"')
|
||||
]);`);
|
||||
expect(popup.url()).toBe('about:blank');
|
||||
});
|
||||
|
||||
it('should assert navigation', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<a onclick="window.location.href='about:blank#foo'">link</a>`);
|
||||
|
||||
const selector = await recorder.hoverOverElement('a');
|
||||
expect(selector).toBe('text="link"');
|
||||
|
||||
await Promise.all([
|
||||
page.waitForNavigation(),
|
||||
recorder.waitForOutput('assert'),
|
||||
page.dispatchEvent('a', 'click', { detail: 1 })
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Click text="link"
|
||||
await page.click('text="link"');
|
||||
// assert.equal(page.url(), 'about:blank#foo');`);
|
||||
expect(page.url()).toContain('about:blank#foo');
|
||||
});
|
||||
|
||||
|
||||
it('should await navigation', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<a onclick="setTimeout(() => window.location.href='about:blank#foo', 1000)">link</a>`);
|
||||
|
||||
const selector = await recorder.hoverOverElement('a');
|
||||
expect(selector).toBe('text="link"');
|
||||
|
||||
await Promise.all([
|
||||
page.waitForNavigation(),
|
||||
recorder.waitForOutput('waitForNavigation'),
|
||||
page.dispatchEvent('a', 'click', { detail: 1 })
|
||||
]);
|
||||
expect(recorder.output()).toContain(`
|
||||
// Click text="link"
|
||||
await Promise.all([
|
||||
page.waitForNavigation(/*{ url: 'about:blank#foo' }*/),
|
||||
page.click('text="link"')
|
||||
]);`);
|
||||
expect(page.url()).toContain('about:blank#foo');
|
||||
});
|
||||
|
||||
it('should contain open page', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(``);
|
||||
expect(recorder.output()).toContain(`const page = await context.newPage();`);
|
||||
});
|
||||
|
||||
it('should contain second page', async ({ contextWrapper, recorder }) => {
|
||||
await recorder.setContentAndWait(``);
|
||||
await contextWrapper.context.newPage();
|
||||
await recorder.waitForOutput('page1');
|
||||
expect(recorder.output()).toContain('const page1 = await context.newPage();');
|
||||
});
|
||||
|
||||
it('should contain close page', async ({ contextWrapper, recorder }) => {
|
||||
await recorder.setContentAndWait(``);
|
||||
await contextWrapper.context.newPage();
|
||||
await recorder.page.close();
|
||||
await recorder.waitForOutput('page.close();');
|
||||
});
|
||||
|
||||
it('should upload a single file', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<form>
|
||||
<input type="file">
|
||||
</form>
|
||||
`);
|
||||
|
||||
await page.focus('input[type=file]')
|
||||
await page.setInputFiles('input[type=file]', 'test/assets/file-to-upload.txt')
|
||||
await page.click('input[type=file]')
|
||||
|
||||
await recorder.waitForOutput('setInputFiles')
|
||||
expect(recorder.output()).toContain(`
|
||||
// Upload file-to-upload.txt
|
||||
await page.setInputFiles('input[type="file"]', 'file-to-upload.txt');`);
|
||||
});
|
||||
|
||||
it('should upload multiple files', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<form>
|
||||
<input type="file" multiple>
|
||||
</form>
|
||||
`);
|
||||
|
||||
await page.focus('input[type=file]')
|
||||
await page.setInputFiles('input[type=file]', ['test/assets/file-to-upload.txt', 'test/assets/file-to-upload-2.txt'])
|
||||
await page.click('input[type=file]')
|
||||
|
||||
await recorder.waitForOutput('setInputFiles')
|
||||
expect(recorder.output()).toContain(`
|
||||
// Upload file-to-upload.txt, file-to-upload-2.txt
|
||||
await page.setInputFiles('input[type="file"]', ['file-to-upload.txt', 'file-to-upload-2.txt']);`);
|
||||
});
|
||||
|
||||
it('should clear files', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<form>
|
||||
<input type="file" multiple>
|
||||
</form>
|
||||
`);
|
||||
await page.focus('input[type=file]')
|
||||
await page.setInputFiles('input[type=file]', 'test/assets/file-to-upload.txt')
|
||||
await page.setInputFiles('input[type=file]', [])
|
||||
await page.click('input[type=file]')
|
||||
|
||||
await recorder.waitForOutput('setInputFiles')
|
||||
expect(recorder.output()).toContain(`
|
||||
// Clear selected files
|
||||
await page.setInputFiles('input[type="file"]', []);`);
|
||||
});
|
||||
|
||||
it('should download files', async ({ page, recorder, httpServer }) => {
|
||||
httpServer.setHandler((req: http.IncomingMessage, res: http.ServerResponse) => {
|
||||
const pathName = url.parse(req.url).path;
|
||||
if (pathName === '/download') {
|
||||
res.setHeader('Content-Type', 'application/octet-stream');
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=file.txt');
|
||||
res.end(`Hello world`);
|
||||
} else {
|
||||
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||||
res.end('');
|
||||
}
|
||||
});
|
||||
await recorder.setContentAndWait(`
|
||||
<a href="${httpServer.PREFIX}/download" download>Download</a>
|
||||
`, httpServer.PREFIX);
|
||||
await recorder.hoverOverElement('text=Download')
|
||||
await Promise.all([
|
||||
page.waitForEvent('download'),
|
||||
page.click('text=Download')
|
||||
]);
|
||||
await recorder.waitForOutput('page.click')
|
||||
expect(recorder.output()).toContain(`
|
||||
// Click text="Download"
|
||||
const [download] = await Promise.all([
|
||||
page.waitForEvent('download'),
|
||||
page.click('text="Download"')
|
||||
]);`);
|
||||
});
|
||||
|
||||
it('should handle dialogs', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<button onclick="alert()">click me</button>
|
||||
`);
|
||||
await recorder.hoverOverElement('button');
|
||||
page.once('dialog', async dialog => {
|
||||
await dialog.dismiss();
|
||||
});
|
||||
await page.click('text="click me"');
|
||||
await recorder.waitForOutput('page.once');
|
||||
expect(recorder.output()).toContain(`
|
||||
// Click text="click me"
|
||||
page.once('dialog', dialog => {
|
||||
console.log(\`Dialog message: $\{dialog.message()}\`);
|
||||
dialog.dismiss().catch(() => {});
|
||||
});
|
||||
await page.click('text="click me"')`)
|
||||
});
|
||||
|
||||
it('should handle history.postData', async ({ page, recorder, httpServer }) => {
|
||||
httpServer.setHandler((req: http.IncomingMessage, res: http.ServerResponse) => {
|
||||
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||||
res.end('Hello world');
|
||||
});
|
||||
await recorder.setContentAndWait(`
|
||||
<script>
|
||||
let seqNum = 0;
|
||||
function pushState() {
|
||||
history.pushState({}, 'title', '${httpServer.PREFIX}/#seqNum=' + (++seqNum));
|
||||
}
|
||||
</script>`, httpServer.PREFIX);
|
||||
for (let i = 1; i < 3; ++i) {
|
||||
await page.evaluate('pushState()');
|
||||
await recorder.waitForOutput(`seqNum=${i}`);
|
||||
expect(recorder.output()).toContain(`await page.goto('${httpServer.PREFIX}/#seqNum=${i}');`);
|
||||
}
|
||||
});
|
||||
|
||||
it('should record open in a new tab with url', test => {
|
||||
test.fixme(isWebKit(), 'Ctrl+click does not open in new tab on WebKit');
|
||||
}, async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`<a href="about:blank?foo">link</a>`);
|
||||
|
||||
const selector = await recorder.hoverOverElement('a');
|
||||
expect(selector).toBe('text="link"');
|
||||
|
||||
await page.click('a', { modifiers: [ isMac() ? 'Meta' : 'Control'] });
|
||||
await recorder.waitForOutput('page1');
|
||||
if (isChromium()) {
|
||||
expect(recorder.output()).toContain(`
|
||||
// Open new page
|
||||
const page1 = await context.newPage();
|
||||
page1.load('about:blank?foo');`);
|
||||
} else if (isFirefox()) {
|
||||
expect(recorder.output()).toContain(`
|
||||
// Click text="link"
|
||||
const [page1] = await Promise.all([
|
||||
page.waitForEvent('popup'),
|
||||
page.click('text="link"', {
|
||||
modifiers: ['${isMac() ? 'Meta' : 'Control'}']
|
||||
})
|
||||
]);`);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not clash pages', test => {
|
||||
test.fixme(isFirefox(), 'Times out on Firefox, maybe the focus issue')
|
||||
}, async ({ page, recorder }) => {
|
||||
const [popup1] = await Promise.all([
|
||||
page.context().waitForEvent('page'),
|
||||
page.evaluate(`window.open('about:blank')`)
|
||||
]);
|
||||
await recorder.setPageContentAndWait(popup1, '<input id=name>');
|
||||
|
||||
const [popup2] = await Promise.all([
|
||||
page.context().waitForEvent('page'),
|
||||
page.evaluate(`window.open('about:blank')`)
|
||||
]);
|
||||
await recorder.setPageContentAndWait(popup2, '<input id=name>');
|
||||
|
||||
await popup1.type('input', 'TextA');
|
||||
await recorder.waitForOutput('TextA');
|
||||
|
||||
await popup2.type('input', 'TextB');
|
||||
await recorder.waitForOutput('TextB');
|
||||
|
||||
expect(recorder.output()).toContain(`await page1.fill('input[id="name"]', 'TextA');`);
|
||||
expect(recorder.output()).toContain(`await page2.fill('input[id="name"]', 'TextB');`);
|
||||
});
|
||||
|
||||
it('click should emit events in order', async ({ page, recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<button id=button>
|
||||
<script>
|
||||
button.addEventListener('mousedown', e => console.log(e.type));
|
||||
button.addEventListener('mouseup', e => console.log(e.type));
|
||||
button.addEventListener('click', e => console.log(e.type));
|
||||
</script>
|
||||
`);
|
||||
|
||||
const messages = [];
|
||||
page.on('console', message => messages.push(message.text()));
|
||||
await Promise.all([
|
||||
page.click('button'),
|
||||
recorder.waitForOutput('page.click')
|
||||
]);
|
||||
expect(messages).toEqual(['mousedown', 'mouseup', 'click']);
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { fixtures } from './playwright.fixtures';
|
||||
const { it, expect, describe } = fixtures;
|
||||
|
||||
it('should generate for text', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`<div>Text</div>`);
|
||||
const selector = await recorder.hoverOverElement('div');
|
||||
expect(selector).toBe('text="Text"');
|
||||
});
|
||||
|
||||
it('should use ordinal for identical nodes', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`<div>Text</div><div>Text</div><div mark=1>Text</div><div>Text</div>`);
|
||||
const selector = await recorder.hoverOverElement('div[mark="1"]');
|
||||
expect(selector).toBe('//div[3][normalize-space(.)=\'Text\']');
|
||||
});
|
||||
|
||||
it('should prefer data-testid', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`<div>Text</div><div>Text</div><div data-testid=a>Text</div><div>Text</div>`);
|
||||
const selector = await recorder.hoverOverElement('div[data-testid="a"]');
|
||||
expect(selector).toBe('div[data-testid="a"]');
|
||||
});
|
||||
|
||||
it('should handle first non-unique data-testid', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<div data-testid=a mark=1>
|
||||
Text
|
||||
</div>
|
||||
<div data-testid=a>
|
||||
Text
|
||||
</div>`);
|
||||
const selector = await recorder.hoverOverElement('div[mark="1"]');
|
||||
expect(selector).toBe('div[data-testid="a"]');
|
||||
});
|
||||
|
||||
it('should handle second non-unique data-testid', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<div data-testid=a>
|
||||
Text
|
||||
</div>
|
||||
<div data-testid=a mark=1>
|
||||
Text
|
||||
</div>`);
|
||||
const selector = await recorder.hoverOverElement('div[mark="1"]');
|
||||
expect(selector).toBe('//div[2][normalize-space(.)=\'Text\']');
|
||||
});
|
||||
|
||||
it('should use readable id', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<div></div>
|
||||
<div id=first-item mark=1></div>
|
||||
`);
|
||||
const selector = await recorder.hoverOverElement('div[mark="1"]');
|
||||
expect(selector).toBe('div[id="first-item"]');
|
||||
});
|
||||
|
||||
it('should not use generated id', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<div></div>
|
||||
<div id=aAbBcCdDeE mark=1></div>
|
||||
`);
|
||||
const selector = await recorder.hoverOverElement('div[mark="1"]');
|
||||
expect(selector).toBe('//div[2]');
|
||||
});
|
||||
|
||||
it('should separate selectors by >>', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<div>
|
||||
<div>Text</div>
|
||||
</div>
|
||||
<div id="id">
|
||||
<div>Text</div>
|
||||
</div>
|
||||
`);
|
||||
const selector = await recorder.hoverOverElement('#id > div');
|
||||
expect(selector).toBe('div[id=\"id\"] >> text=\"Text\"');
|
||||
});
|
||||
|
||||
it('should trim long text', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<div>
|
||||
<div>Text that goes on and on and on and on and on and on and on and on and on and on and on and on and on and on and on</div>
|
||||
</div>
|
||||
<div id="id">
|
||||
<div>Text that goes on and on and on and on and on and on and on and on and on and on and on and on and on and on and on</div>
|
||||
</div>
|
||||
`);
|
||||
const selector = await recorder.hoverOverElement('#id > div');
|
||||
expect(selector).toBe('div[id=\"id\"] >> text=/.*Text that goes on and on and o.*/');
|
||||
});
|
||||
|
||||
it('should use nested ordinals', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<a><b></b></a>
|
||||
<a>
|
||||
<b>
|
||||
<c>
|
||||
</c>
|
||||
</b>
|
||||
<b>
|
||||
<c mark=1></c>
|
||||
</b>
|
||||
</a>
|
||||
<a><b></b></a>
|
||||
`);
|
||||
const selector = await recorder.hoverOverElement('c[mark="1"]');
|
||||
expect(selector).toBe('//b[2]/c');
|
||||
});
|
||||
|
||||
|
||||
it('should not use input[value]', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`
|
||||
<input value="one">
|
||||
<input value="two" mark="1">
|
||||
<input value="three">
|
||||
`);
|
||||
const selector = await recorder.hoverOverElement('input[mark="1"]');
|
||||
expect(selector).toBe('//input[2]');
|
||||
});
|
||||
|
||||
describe("should prioritise input element attributes correctly", () => {
|
||||
it('name', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`<input name="foobar" type="text"/>`);
|
||||
expect(await recorder.hoverOverElement('input')).toBe('input[name="foobar"]');
|
||||
});
|
||||
it('placeholder', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`<input placeholder="foobar" type="text"/>`);
|
||||
expect(await recorder.hoverOverElement('input')).toBe('input[placeholder="foobar"]');
|
||||
});
|
||||
it('type', async ({ recorder }) => {
|
||||
await recorder.setContentAndWait(`<input type="text"/>`);
|
||||
expect(await recorder.hoverOverElement('input')).toBe('input[type="text"]');
|
||||
});
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Copyright Microsoft Corporation. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
declare const matrix: (m: any) => void;
|
||||
|
||||
matrix({
|
||||
'browserName': process.env.BROWSER ? [process.env.BROWSER] : ['chromium', 'webkit', 'firefox'],
|
||||
});
|
||||
@@ -1,138 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { spawn } from 'child_process';
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
type CliResult = {
|
||||
output: string;
|
||||
error: string;
|
||||
exitCode: number | null;
|
||||
};
|
||||
|
||||
async function runCli(args: string[], env: Record<string, string> = {}): Promise<CliResult> {
|
||||
const cliPath = path.join(__dirname, '../playwright-cli.js');
|
||||
|
||||
return new Promise<CliResult>((resolve, reject) => {
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
const childProcess = spawn(process.execPath, [cliPath, ...args], {
|
||||
env: {
|
||||
...process.env,
|
||||
PLAYWRIGHT_CLI_INSTALLATION_FOR_TEST: test.info().outputPath(),
|
||||
...env,
|
||||
},
|
||||
cwd: test.info().outputPath(),
|
||||
});
|
||||
|
||||
childProcess.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
childProcess.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
childProcess.on('close', (code) => {
|
||||
resolve({
|
||||
output: stdout.trim(),
|
||||
error: stderr.trim(),
|
||||
exitCode: code,
|
||||
});
|
||||
});
|
||||
|
||||
childProcess.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
test('open data URL', async ({}) => {
|
||||
expect(await runCli(['open', 'data:text/html,hello', '--persistent'])).toEqual(expect.objectContaining({
|
||||
output: expect.stringContaining('hello'),
|
||||
exitCode: 0,
|
||||
}));
|
||||
|
||||
expect(await runCli(['delete-data'])).toEqual(expect.objectContaining({
|
||||
output: expect.stringContaining('Deleted user data for'),
|
||||
exitCode: 0,
|
||||
}));
|
||||
});
|
||||
|
||||
test('warns when installed skill is out of date', async ({}) => {
|
||||
expect(await runCli(['install', '--skills'], { NO_UPDATE_NOTIFIER: '1' })).toEqual(expect.objectContaining({
|
||||
exitCode: 0,
|
||||
}));
|
||||
|
||||
const skillFile = path.join(test.info().outputPath(), '.claude', 'skills', 'playwright-cli', 'SKILL.md');
|
||||
fs.appendFileSync(skillFile, 'x');
|
||||
|
||||
const env = { CI: '', NO_UPDATE_NOTIFIER: '' };
|
||||
expect(await runCli(['--help'], env)).toEqual(expect.objectContaining({
|
||||
error: expect.stringContaining('does not match the tool version'),
|
||||
}));
|
||||
|
||||
expect(await runCli(['--help'], env)).toEqual(expect.objectContaining({
|
||||
error: expect.not.stringContaining('does not match the tool version'),
|
||||
}));
|
||||
});
|
||||
|
||||
test('does not warn when installed skill only differs in line endings', async ({}) => {
|
||||
expect(await runCli(['install', '--skills'], { NO_UPDATE_NOTIFIER: '1' })).toEqual(expect.objectContaining({
|
||||
exitCode: 0,
|
||||
}));
|
||||
|
||||
const skillFile = path.join(test.info().outputPath(), '.claude', 'skills', 'playwright-cli', 'SKILL.md');
|
||||
fs.writeFileSync(skillFile, fs.readFileSync(skillFile, 'utf8').replace(/\n/g, '\r\n'));
|
||||
|
||||
expect(await runCli(['--help'], { CI: '', NO_UPDATE_NOTIFIER: '' })).toEqual(expect.objectContaining({
|
||||
error: expect.not.stringContaining('does not match the tool version'),
|
||||
}));
|
||||
});
|
||||
|
||||
test('caches the update check in the default registry directory', async ({}) => {
|
||||
// Redirect the home/cache directories so the real user cache is untouched, and
|
||||
// leave PLAYWRIGHT_CLI_INSTALLATION_FOR_TEST empty so the default path is used.
|
||||
const home = test.info().outputPath('home');
|
||||
fs.mkdirSync(home, { recursive: true });
|
||||
const env = {
|
||||
CI: '',
|
||||
NO_UPDATE_NOTIFIER: '',
|
||||
PLAYWRIGHT_CLI_INSTALLATION_FOR_TEST: '',
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CACHE_HOME: path.join(home, '.cache'),
|
||||
LOCALAPPDATA: path.join(home, 'AppData', 'Local'),
|
||||
};
|
||||
|
||||
expect(await runCli(['--version'], env)).toEqual(expect.objectContaining({ exitCode: 0 }));
|
||||
|
||||
const found: string[] = [];
|
||||
const walk = (dir: string) => {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory())
|
||||
walk(full);
|
||||
else if (entry.name === 'cli-update-check.json')
|
||||
found.push(full);
|
||||
}
|
||||
};
|
||||
walk(home);
|
||||
|
||||
expect(found).toHaveLength(1);
|
||||
expect(JSON.parse(fs.readFileSync(found[0], 'utf8')).lastCheck).toEqual(expect.any(Number));
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2018",
|
||||
"module": "commonjs",
|
||||
"lib": ["esnext", "dom", "DOM.Iterable"],
|
||||
"sourceMap": true,
|
||||
"rootDir": "./src",
|
||||
"outDir": "./lib",
|
||||
"strict": true,
|
||||
"declaration": false
|
||||
},
|
||||
"compileOnSave": true,
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
const child_process = require('child_process');
|
||||
const path = require('path');
|
||||
|
||||
const files = [
|
||||
path.join('src', 'injected', 'script.webpack.config.js'),
|
||||
];
|
||||
|
||||
function runOne(runner, file) {
|
||||
return runner('npx', ['webpack', '--config', file, ...process.argv.slice(2)], { stdio: 'inherit', shell: true });
|
||||
}
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
if (args.includes('--watch')) {
|
||||
const spawns = files.map(file => runOne(child_process.spawn, file));
|
||||
process.on('exit', () => spawns.forEach(s => s.kill()));
|
||||
} else {
|
||||
for (const file of files) {
|
||||
const out = runOne(child_process.spawnSync, file);
|
||||
if (out.status)
|
||||
process.exit(out.status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
module.exports = class InlineSource {
|
||||
constructor(outFile) {
|
||||
this.outFile = outFile;
|
||||
}
|
||||
|
||||
apply(compiler) {
|
||||
compiler.hooks.emit.tapAsync('InlineSource', (compilation, callback) => {
|
||||
let source = compilation.assets[path.basename(this.outFile).replace('.ts', '.js')].source();
|
||||
const lastLine = source.split('\n').pop();
|
||||
if (lastLine.startsWith('//# sourceMappingURL'))
|
||||
source = source.substring(0, source.length - lastLine.length - 1);
|
||||
if (source.endsWith(';'))
|
||||
source = source.substring(0, source.length - 1);
|
||||
source = '(' + source + ').default';
|
||||
fs.mkdirSync(path.dirname(this.outFile), { recursive: true });
|
||||
const newSource = 'export const source = ' + JSON.stringify(source) + ';';
|
||||
fs.writeFileSync(this.outFile, newSource);
|
||||
callback();
|
||||
});
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user