From 4ffa7417a359ef4eae09f61d7da4de06539462ca Mon Sep 17 00:00:00 2001 From: Craig Jennings Date: Sun, 19 Apr 2026 15:24:51 -0500 Subject: refactor(playwright): split into playwright-js + playwright-py variants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rename `playwright-skill/` → `playwright-js/` and add `playwright-py/` as a verbatim fork of Anthropic's official `webapp-testing` skill (Apache-2.0). Cross-pollinate: each skill gains patterns and helpers inspired by the other's strengths, with upstream semantics preserved. ## playwright-js (JS/TS stack) Renamed from playwright-skill; upstream lackeyjb MIT content untouched. New sections added (clearly marked, preserving upstream semantics): - Static HTML vs Dynamic Webapp decision tree (core Anthropic methodology) - Reconnaissance-Then-Action pattern (navigate → networkidle → inspect → act) - Console Log Capture snippet (page.on console/pageerror/requestfailed) Description updated to clarify JS/TS stack fit (React/Next/Vue/Svelte/Node) and reference `/playwright-py` as the Python sibling. ## playwright-py (Python stack) Verbatim fork of anthropics/skills/skills/webapp-testing; upstream SKILL.md and bundled `scripts/with_server.py` + examples kept intact. New scripts and examples added (all lackeyjb-style conveniences in Python): Scripts: scripts/detect_dev_servers.py Probe common localhost ports for HTTP servers; outputs JSON of found services. scripts/safe_actions.py safe_click, safe_type (retry-wrapped), handle_cookie_banner (common selectors), build_context_with_headers (env-var- driven: PW_HEADER_NAME / PW_HEADER_VALUE / PW_EXTRA_HEADERS='{…json…}'). Examples: examples/login_flow.py Login form + wait_for_url. examples/broken_links.py Scan visible external hrefs via HEAD. examples/responsive_sweep.py Multi-viewport screenshots to /tmp. SKILL.md gains 5 "Added:" sections documenting the new scripts, retry helpers, env-header injection, and /tmp script discipline. Attribution notes explicitly mark upstream vs local additions. ## Makefile SKILLS: playwright-skill → playwright-js + playwright-py deps target: extended Playwright step to install Python package + Chromium via `python3 -m pip install --user playwright && python3 -m playwright install chromium` when playwright-py/ is present. Idempotent (detected via `python3 -c "import playwright"`). ## Usage Both skills symlinked globally via `make install`. Invoke whichever matches the project stack — cross-references in descriptions route you to the right one. Run `make deps` once to install both runtimes. --- Makefile | 25 +- playwright-js/API_REFERENCE.md | 653 +++++++++++++++++++++++ playwright-js/LICENSE | 21 + playwright-js/SKILL.md | 513 ++++++++++++++++++ playwright-js/lib/helpers.js | 441 +++++++++++++++ playwright-js/package.json | 26 + playwright-js/run.js | 228 ++++++++ playwright-py/LICENSE.txt | 202 +++++++ playwright-py/SKILL.md | 175 ++++++ playwright-py/examples/broken_links.py | 58 ++ playwright-py/examples/console_logging.py | 35 ++ playwright-py/examples/element_discovery.py | 40 ++ playwright-py/examples/login_flow.py | 55 ++ playwright-py/examples/responsive_sweep.py | 51 ++ playwright-py/examples/static_html_automation.py | 33 ++ playwright-py/scripts/detect_dev_servers.py | 71 +++ playwright-py/scripts/safe_actions.py | 100 ++++ playwright-py/scripts/with_server.py | 106 ++++ playwright-skill/API_REFERENCE.md | 653 ----------------------- playwright-skill/LICENSE | 21 - playwright-skill/SKILL.md | 460 ---------------- playwright-skill/lib/helpers.js | 441 --------------- playwright-skill/package.json | 26 - playwright-skill/run.js | 228 -------- 24 files changed, 2826 insertions(+), 1836 deletions(-) create mode 100644 playwright-js/API_REFERENCE.md create mode 100644 playwright-js/LICENSE create mode 100644 playwright-js/SKILL.md create mode 100644 playwright-js/lib/helpers.js create mode 100644 playwright-js/package.json create mode 100755 playwright-js/run.js create mode 100644 playwright-py/LICENSE.txt create mode 100644 playwright-py/SKILL.md create mode 100644 playwright-py/examples/broken_links.py create mode 100644 playwright-py/examples/console_logging.py create mode 100644 playwright-py/examples/element_discovery.py create mode 100644 playwright-py/examples/login_flow.py create mode 100644 playwright-py/examples/responsive_sweep.py create mode 100644 playwright-py/examples/static_html_automation.py create mode 100644 playwright-py/scripts/detect_dev_servers.py create mode 100644 playwright-py/scripts/safe_actions.py create mode 100755 playwright-py/scripts/with_server.py delete mode 100644 playwright-skill/API_REFERENCE.md delete mode 100644 playwright-skill/LICENSE delete mode 100644 playwright-skill/SKILL.md delete mode 100644 playwright-skill/lib/helpers.js delete mode 100644 playwright-skill/package.json delete mode 100755 playwright-skill/run.js diff --git a/Makefile b/Makefile index c78bad6..74d1905 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ RULES_DIR := $(HOME)/.claude/rules SKILLS := c4-analyze c4-diagram debug add-tests respond-to-review review-pr fix-issue security-check \ arch-design arch-decide arch-document arch-evaluate \ brainstorm codify root-cause-trace five-whys prompt-engineering \ - playwright-skill + playwright-js playwright-py RULES := $(wildcard claude-rules/*.md) LANGUAGES := $(notdir $(wildcard languages/*)) @@ -64,15 +64,26 @@ deps: ## Install required tools (claude, node, jq, fzf, ripgrep, emacs, playwrig { echo " ripgrep: installing..."; $(call install_pkg,ripgrep); } @command -v emacs >/dev/null 2>&1 && echo " emacs: installed" || \ { echo " emacs: installing..."; $(call install_pkg,emacs); } - @if [ -d "$(CURDIR)/playwright-skill" ]; then \ - if [ -d "$(CURDIR)/playwright-skill/node_modules/playwright" ]; then \ - echo " playwright: installed (skill node_modules present)"; \ + @if [ -d "$(CURDIR)/playwright-js" ]; then \ + if [ -d "$(CURDIR)/playwright-js/node_modules/playwright" ]; then \ + echo " playwright (js): installed (skill node_modules present)"; \ else \ - echo " playwright: running skill setup (npm install + chromium download ~300 MB)..."; \ - (cd "$(CURDIR)/playwright-skill" && npm run setup); \ + echo " playwright (js): running skill setup (npm install + chromium download ~300 MB)..."; \ + (cd "$(CURDIR)/playwright-js" && npm run setup); \ fi \ else \ - echo " playwright: skipped (playwright-skill/ not present in this repo)"; \ + echo " playwright (js): skipped (playwright-js/ not present)"; \ + fi + @if [ -d "$(CURDIR)/playwright-py" ]; then \ + if python3 -c "import playwright" >/dev/null 2>&1; then \ + echo " playwright (py): installed (python package importable)"; \ + else \ + echo " playwright (py): installing via pip --user..."; \ + python3 -m pip install --user playwright && \ + python3 -m playwright install chromium; \ + fi \ + else \ + echo " playwright (py): skipped (playwright-py/ not present)"; \ fi @echo "Done." diff --git a/playwright-js/API_REFERENCE.md b/playwright-js/API_REFERENCE.md new file mode 100644 index 0000000..9ee2975 --- /dev/null +++ b/playwright-js/API_REFERENCE.md @@ -0,0 +1,653 @@ +# Playwright Skill - Complete API Reference + +This document contains the comprehensive Playwright API reference and advanced patterns. For quick-start execution patterns, see [SKILL.md](SKILL.md). + +## Table of Contents + +- [Installation & Setup](#installation--setup) +- [Core Patterns](#core-patterns) +- [Selectors & Locators](#selectors--locators) +- [Common Actions](#common-actions) +- [Waiting Strategies](#waiting-strategies) +- [Assertions](#assertions) +- [Page Object Model](#page-object-model-pom) +- [Network & API Testing](#network--api-testing) +- [Authentication & Session Management](#authentication--session-management) +- [Visual Testing](#visual-testing) +- [Mobile Testing](#mobile-testing) +- [Debugging](#debugging) +- [Performance Testing](#performance-testing) +- [Parallel Execution](#parallel-execution) +- [Data-Driven Testing](#data-driven-testing) +- [Accessibility Testing](#accessibility-testing) +- [CI/CD Integration](#cicd-integration) +- [Best Practices](#best-practices) +- [Common Patterns & Solutions](#common-patterns--solutions) +- [Troubleshooting](#troubleshooting) + +## Installation & Setup + +### Prerequisites + +Before using this skill, ensure Playwright is available: + +```bash +# Check if Playwright is installed +npm list playwright 2>/dev/null || echo "Playwright not installed" + +# Install (if needed) +cd ~/.claude/skills/playwright-skill +npm run setup +``` + +### Basic Configuration + +Create `playwright.config.ts`: + +```typescript +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests', + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 2 : 0, + workers: process.env.CI ? 1 : undefined, + reporter: 'html', + use: { + baseURL: 'http://localhost:3000', + trace: 'on-first-retry', + screenshot: 'only-on-failure', + video: 'retain-on-failure', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], + webServer: { + command: 'npm run start', + url: 'http://localhost:3000', + reuseExistingServer: !process.env.CI, + }, +}); +``` + +## Core Patterns + +### Basic Browser Automation + +```javascript +const { chromium } = require('playwright'); + +(async () => { + // Launch browser + const browser = await chromium.launch({ + headless: false, // Set to true for headless mode + slowMo: 50 // Slow down operations by 50ms + }); + + const context = await browser.newContext({ + viewport: { width: 1280, height: 720 }, + userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' + }); + + const page = await context.newPage(); + + // Navigate + await page.goto('https://example.com', { + waitUntil: 'networkidle' // Wait for network to be idle + }); + + // Your automation here + + await browser.close(); +})(); +``` + +### Test Structure + +```typescript +import { test, expect } from '@playwright/test'; + +test.describe('Feature Name', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/'); + }); + + test('should do something', async ({ page }) => { + // Arrange + const button = page.locator('button[data-testid="submit"]'); + + // Act + await button.click(); + + // Assert + await expect(page).toHaveURL('/success'); + await expect(page.locator('.message')).toHaveText('Success!'); + }); +}); +``` + +## Selectors & Locators + +### Best Practices for Selectors + +```javascript +// PREFERRED: Data attributes (most stable) +await page.locator('[data-testid="submit-button"]').click(); +await page.locator('[data-cy="user-input"]').fill('text'); + +// GOOD: Role-based selectors (accessible) +await page.getByRole('button', { name: 'Submit' }).click(); +await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com'); +await page.getByRole('heading', { level: 1 }).click(); + +// GOOD: Text content (for unique text) +await page.getByText('Sign in').click(); +await page.getByText(/welcome back/i).click(); + +// OK: Semantic HTML +await page.locator('button[type="submit"]').click(); +await page.locator('input[name="email"]').fill('test@test.com'); + +// AVOID: Classes and IDs (can change frequently) +await page.locator('.btn-primary').click(); // Avoid +await page.locator('#submit').click(); // Avoid + +// LAST RESORT: Complex CSS/XPath +await page.locator('div.container > form > button').click(); // Fragile +``` + +### Advanced Locator Patterns + +```javascript +// Filter and chain locators +const row = page.locator('tr').filter({ hasText: 'John Doe' }); +await row.locator('button').click(); + +// Nth element +await page.locator('button').nth(2).click(); + +// Combining conditions +await page.locator('button').and(page.locator('[disabled]')).count(); + +// Parent/child navigation +const cell = page.locator('td').filter({ hasText: 'Active' }); +const row = cell.locator('..'); +await row.locator('button.edit').click(); +``` + +## Common Actions + +### Form Interactions + +```javascript +// Text input +await page.getByLabel('Email').fill('user@example.com'); +await page.getByPlaceholder('Enter your name').fill('John Doe'); + +// Clear and type +await page.locator('#username').clear(); +await page.locator('#username').type('newuser', { delay: 100 }); + +// Checkbox +await page.getByLabel('I agree').check(); +await page.getByLabel('Subscribe').uncheck(); + +// Radio button +await page.getByLabel('Option 2').check(); + +// Select dropdown +await page.selectOption('select#country', 'usa'); +await page.selectOption('select#country', { label: 'United States' }); +await page.selectOption('select#country', { index: 2 }); + +// Multi-select +await page.selectOption('select#colors', ['red', 'blue', 'green']); + +// File upload +await page.setInputFiles('input[type="file"]', 'path/to/file.pdf'); +await page.setInputFiles('input[type="file"]', [ + 'file1.pdf', + 'file2.pdf' +]); +``` + +### Mouse Actions + +```javascript +// Click variations +await page.click('button'); // Left click +await page.click('button', { button: 'right' }); // Right click +await page.dblclick('button'); // Double click +await page.click('button', { position: { x: 10, y: 10 } }); // Click at position + +// Hover +await page.hover('.menu-item'); + +// Drag and drop +await page.dragAndDrop('#source', '#target'); + +// Manual drag +await page.locator('#source').hover(); +await page.mouse.down(); +await page.locator('#target').hover(); +await page.mouse.up(); +``` + +### Keyboard Actions + +```javascript +// Type with delay +await page.keyboard.type('Hello World', { delay: 100 }); + +// Key combinations +await page.keyboard.press('Control+A'); +await page.keyboard.press('Control+C'); +await page.keyboard.press('Control+V'); + +// Special keys +await page.keyboard.press('Enter'); +await page.keyboard.press('Tab'); +await page.keyboard.press('Escape'); +await page.keyboard.press('ArrowDown'); +``` + +## Waiting Strategies + +### Smart Waiting + +```javascript +// Wait for element states +await page.locator('button').waitFor({ state: 'visible' }); +await page.locator('.spinner').waitFor({ state: 'hidden' }); +await page.locator('button').waitFor({ state: 'attached' }); +await page.locator('button').waitFor({ state: 'detached' }); + +// Wait for specific conditions +await page.waitForURL('**/success'); +await page.waitForURL(url => url.pathname === '/dashboard'); + +// Wait for network +await page.waitForLoadState('networkidle'); +await page.waitForLoadState('domcontentloaded'); + +// Wait for function +await page.waitForFunction(() => document.querySelector('.loaded')); +await page.waitForFunction( + text => document.body.innerText.includes(text), + 'Content loaded' +); + +// Wait for response +const responsePromise = page.waitForResponse('**/api/users'); +await page.click('button#load-users'); +const response = await responsePromise; + +// Wait for request +await page.waitForRequest(request => + request.url().includes('/api/') && request.method() === 'POST' +); + +// Custom timeout +await page.locator('.slow-element').waitFor({ + state: 'visible', + timeout: 10000 // 10 seconds +}); +``` + +## Assertions + +### Common Assertions + +```javascript +import { expect } from '@playwright/test'; + +// Page assertions +await expect(page).toHaveTitle('My App'); +await expect(page).toHaveURL('https://example.com/dashboard'); +await expect(page).toHaveURL(/.*dashboard/); + +// Element visibility +await expect(page.locator('.message')).toBeVisible(); +await expect(page.locator('.spinner')).toBeHidden(); +await expect(page.locator('button')).toBeEnabled(); +await expect(page.locator('input')).toBeDisabled(); + +// Text content +await expect(page.locator('h1')).toHaveText('Welcome'); +await expect(page.locator('.message')).toContainText('success'); +await expect(page.locator('.items')).toHaveText(['Item 1', 'Item 2']); + +// Input values +await expect(page.locator('input')).toHaveValue('test@example.com'); +await expect(page.locator('input')).toBeEmpty(); + +// Attributes +await expect(page.locator('button')).toHaveAttribute('type', 'submit'); +await expect(page.locator('img')).toHaveAttribute('src', /.*\.png/); + +// CSS properties +await expect(page.locator('.error')).toHaveCSS('color', 'rgb(255, 0, 0)'); + +// Count +await expect(page.locator('.item')).toHaveCount(5); + +// Checkbox/Radio state +await expect(page.locator('input[type="checkbox"]')).toBeChecked(); +``` + +## Page Object Model (POM) + +### Basic Page Object + +```javascript +// pages/LoginPage.js +class LoginPage { + constructor(page) { + this.page = page; + this.usernameInput = page.locator('input[name="username"]'); + this.passwordInput = page.locator('input[name="password"]'); + this.submitButton = page.locator('button[type="submit"]'); + this.errorMessage = page.locator('.error-message'); + } + + async navigate() { + await this.page.goto('/login'); + } + + async login(username, password) { + await this.usernameInput.fill(username); + await this.passwordInput.fill(password); + await this.submitButton.click(); + } + + async getErrorMessage() { + return await this.errorMessage.textContent(); + } +} + +// Usage in test +test('login with valid credentials', async ({ page }) => { + const loginPage = new LoginPage(page); + await loginPage.navigate(); + await loginPage.login('user@example.com', 'password123'); + await expect(page).toHaveURL('/dashboard'); +}); +``` + +## Network & API Testing + +### Intercepting Requests + +```javascript +// Mock API responses +await page.route('**/api/users', route => { + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify([ + { id: 1, name: 'John' }, + { id: 2, name: 'Jane' } + ]) + }); +}); + +// Modify requests +await page.route('**/api/**', route => { + const headers = { + ...route.request().headers(), + 'X-Custom-Header': 'value' + }; + route.continue({ headers }); +}); + +// Block resources +await page.route('**/*.{png,jpg,jpeg,gif}', route => route.abort()); +``` + +### Custom Headers via Environment Variables + +The skill supports automatic header injection via environment variables: + +```bash +# Single header (simple) +PW_HEADER_NAME=X-Automated-By PW_HEADER_VALUE=playwright-skill + +# Multiple headers (JSON) +PW_EXTRA_HEADERS='{"X-Automated-By":"playwright-skill","X-Request-ID":"123"}' +``` + +These headers are automatically applied to all requests when using: +- `helpers.createContext(browser)` - headers merged automatically +- `getContextOptionsWithHeaders(options)` - utility injected by run.js wrapper + +**Precedence (highest to lowest):** +1. Headers passed directly in `options.extraHTTPHeaders` +2. Environment variable headers +3. Playwright defaults + +**Use case:** Identify automated traffic so your backend can return LLM-optimized responses (e.g., plain text errors instead of styled HTML). + +## Visual Testing + +### Screenshots + +```javascript +// Full page screenshot +await page.screenshot({ + path: 'screenshot.png', + fullPage: true +}); + +// Element screenshot +await page.locator('.chart').screenshot({ + path: 'chart.png' +}); + +// Visual comparison +await expect(page).toHaveScreenshot('homepage.png'); +``` + +## Mobile Testing + +```javascript +// Device emulation +const { devices } = require('playwright'); +const iPhone = devices['iPhone 12']; + +const context = await browser.newContext({ + ...iPhone, + locale: 'en-US', + permissions: ['geolocation'], + geolocation: { latitude: 37.7749, longitude: -122.4194 } +}); +``` + +## Debugging + +### Debug Mode + +```bash +# Run with inspector +npx playwright test --debug + +# Headed mode +npx playwright test --headed + +# Slow motion +npx playwright test --headed --slowmo=1000 +``` + +### In-Code Debugging + +```javascript +// Pause execution +await page.pause(); + +// Console logs +page.on('console', msg => console.log('Browser log:', msg.text())); +page.on('pageerror', error => console.log('Page error:', error)); +``` + +## Performance Testing + +```javascript +// Measure page load time +const startTime = Date.now(); +await page.goto('https://example.com'); +const loadTime = Date.now() - startTime; +console.log(`Page loaded in ${loadTime}ms`); +``` + +## Parallel Execution + +```javascript +// Run tests in parallel +test.describe.parallel('Parallel suite', () => { + test('test 1', async ({ page }) => { + // Runs in parallel with test 2 + }); + + test('test 2', async ({ page }) => { + // Runs in parallel with test 1 + }); +}); +``` + +## Data-Driven Testing + +```javascript +// Parameterized tests +const testData = [ + { username: 'user1', password: 'pass1', expected: 'Welcome user1' }, + { username: 'user2', password: 'pass2', expected: 'Welcome user2' }, +]; + +testData.forEach(({ username, password, expected }) => { + test(`login with ${username}`, async ({ page }) => { + await page.goto('/login'); + await page.fill('#username', username); + await page.fill('#password', password); + await page.click('button[type="submit"]'); + await expect(page.locator('.message')).toHaveText(expected); + }); +}); +``` + +## Accessibility Testing + +```javascript +import { injectAxe, checkA11y } from 'axe-playwright'; + +test('accessibility check', async ({ page }) => { + await page.goto('/'); + await injectAxe(page); + await checkA11y(page); +}); +``` + +## CI/CD Integration + +### GitHub Actions + +```yaml +name: Playwright Tests +on: + push: + branches: [main, master] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + - name: Install dependencies + run: npm ci + - name: Install Playwright Browsers + run: npx playwright install --with-deps + - name: Run tests + run: npx playwright test +``` + +## Best Practices + +1. **Test Organization** - Use descriptive test names, group related tests +2. **Selector Strategy** - Prefer data-testid attributes, use role-based selectors +3. **Waiting** - Use Playwright's auto-waiting, avoid hard-coded delays +4. **Error Handling** - Add proper error messages, take screenshots on failure +5. **Performance** - Run tests in parallel, reuse authentication state + +## Common Patterns & Solutions + +### Handling Popups + +```javascript +const [popup] = await Promise.all([ + page.waitForEvent('popup'), + page.click('button.open-popup') +]); +await popup.waitForLoadState(); +``` + +### File Downloads + +```javascript +const [download] = await Promise.all([ + page.waitForEvent('download'), + page.click('button.download') +]); +await download.saveAs(`./downloads/${download.suggestedFilename()}`); +``` + +### iFrames + +```javascript +const frame = page.frameLocator('#my-iframe'); +await frame.locator('button').click(); +``` + +### Infinite Scroll + +```javascript +async function scrollToBottom(page) { + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await page.waitForTimeout(500); +} +``` + +## Troubleshooting + +### Common Issues + +1. **Element not found** - Check if element is in iframe, verify visibility +2. **Timeout errors** - Increase timeout, check network conditions +3. **Flaky tests** - Use proper waiting strategies, mock external dependencies +4. **Authentication issues** - Verify auth state is properly saved + +## Quick Reference Commands + +```bash +# Run tests +npx playwright test + +# Run in headed mode +npx playwright test --headed + +# Debug tests +npx playwright test --debug + +# Generate code +npx playwright codegen https://example.com + +# Show report +npx playwright show-report +``` + +## Additional Resources + +- [Playwright Documentation](https://playwright.dev/docs/intro) +- [API Reference](https://playwright.dev/docs/api/class-playwright) +- [Best Practices](https://playwright.dev/docs/best-practices) diff --git a/playwright-js/LICENSE b/playwright-js/LICENSE new file mode 100644 index 0000000..5d40ba0 --- /dev/null +++ b/playwright-js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 lackeyjb + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/playwright-js/SKILL.md b/playwright-js/SKILL.md new file mode 100644 index 0000000..7c5f10c --- /dev/null +++ b/playwright-js/SKILL.md @@ -0,0 +1,513 @@ +--- +name: playwright-js +description: Browser automation and UI testing with Playwright using the JavaScript bindings. Auto-detects dev servers, writes clean test scripts to /tmp, runs visible Chromium by default for interactive debugging, ships a helper library (safe click/type retries, cookie banner handler, table extraction, dev-server detection, env-driven header injection). Use when testing a web app with a JavaScript or TypeScript stack (React, Next.js, Vue, Svelte, Express, Node frontends generally), automating browser interactions, validating UX, testing login flows, or checking links. Prefer this over playwright-py when the project is JS/TS-native. See also `/playwright-py` for Python-based variant (Django, FastAPI backend smoke tests, pytest integration). +--- + +**IMPORTANT - Path Resolution:** +This skill can be installed in different locations (plugin system, manual installation, global, or project-specific). Before executing any commands, determine the skill directory based on where you loaded this SKILL.md file, and use that path in all commands below. Replace `$SKILL_DIR` with the actual discovered path. + +Common installation paths: + +- Plugin system: `~/.claude/plugins/marketplaces/playwright-skill/skills/playwright-skill` +- Manual global: `~/.claude/skills/playwright-skill` +- Project-specific: `/.claude/skills/playwright-skill` + +# Playwright Browser Automation + +General-purpose browser automation skill. I'll write custom Playwright code for any automation task you request and execute it via the universal executor. + +**CRITICAL WORKFLOW - Follow these steps in order:** + +1. **Auto-detect dev servers** - For localhost testing, ALWAYS run server detection FIRST: + + ```bash + cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(servers => console.log(JSON.stringify(servers)))" + ``` + + - If **1 server found**: Use it automatically, inform user + - If **multiple servers found**: Ask user which one to test + - If **no servers found**: Ask for URL or offer to help start dev server + +2. **Write scripts to /tmp** - NEVER write test files to skill directory; always use `/tmp/playwright-test-*.js` + +3. **Use visible browser by default** - Always use `headless: false` unless user specifically requests headless mode + +4. **Parameterize URLs** - Always make URLs configurable via environment variable or constant at top of script + +## How It Works + +1. You describe what you want to test/automate +2. I auto-detect running dev servers (or ask for URL if testing external site) +3. I write custom Playwright code in `/tmp/playwright-test-*.js` (won't clutter your project) +4. I execute it via: `cd $SKILL_DIR && node run.js /tmp/playwright-test-*.js` +5. Results displayed in real-time, browser window visible for debugging +6. Test files auto-cleaned from /tmp by your OS + +## Setup (First Time) + +```bash +cd $SKILL_DIR +npm run setup +``` + +This installs Playwright and Chromium browser. Only needed once. + +## Execution Pattern + +**Step 1: Detect dev servers (for localhost testing)** + +```bash +cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(s => console.log(JSON.stringify(s)))" +``` + +**Step 2: Write test script to /tmp with URL parameter** + +```javascript +// /tmp/playwright-test-page.js +const { chromium } = require('playwright'); + +// Parameterized URL (detected or user-provided) +const TARGET_URL = 'http://localhost:3001'; // <-- Auto-detected or from user + +(async () => { + const browser = await chromium.launch({ headless: false }); + const page = await browser.newPage(); + + await page.goto(TARGET_URL); + console.log('Page loaded:', await page.title()); + + await page.screenshot({ path: '/tmp/screenshot.png', fullPage: true }); + console.log('📸 Screenshot saved to /tmp/screenshot.png'); + + await browser.close(); +})(); +``` + +**Step 3: Execute from skill directory** + +```bash +cd $SKILL_DIR && node run.js /tmp/playwright-test-page.js +``` + +## Common Patterns + +### Test a Page (Multiple Viewports) + +```javascript +// /tmp/playwright-test-responsive.js +const { chromium } = require('playwright'); + +const TARGET_URL = 'http://localhost:3001'; // Auto-detected + +(async () => { + const browser = await chromium.launch({ headless: false, slowMo: 100 }); + const page = await browser.newPage(); + + // Desktop test + await page.setViewportSize({ width: 1920, height: 1080 }); + await page.goto(TARGET_URL); + console.log('Desktop - Title:', await page.title()); + await page.screenshot({ path: '/tmp/desktop.png', fullPage: true }); + + // Mobile test + await page.setViewportSize({ width: 375, height: 667 }); + await page.screenshot({ path: '/tmp/mobile.png', fullPage: true }); + + await browser.close(); +})(); +``` + +### Test Login Flow + +```javascript +// /tmp/playwright-test-login.js +const { chromium } = require('playwright'); + +const TARGET_URL = 'http://localhost:3001'; // Auto-detected + +(async () => { + const browser = await chromium.launch({ headless: false }); + const page = await browser.newPage(); + + await page.goto(`${TARGET_URL}/login`); + + await page.fill('input[name="email"]', 'test@example.com'); + await page.fill('input[name="password"]', 'password123'); + await page.click('button[type="submit"]'); + + // Wait for redirect + await page.waitForURL('**/dashboard'); + console.log('✅ Login successful, redirected to dashboard'); + + await browser.close(); +})(); +``` + +### Fill and Submit Form + +```javascript +// /tmp/playwright-test-form.js +const { chromium } = require('playwright'); + +const TARGET_URL = 'http://localhost:3001'; // Auto-detected + +(async () => { + const browser = await chromium.launch({ headless: false, slowMo: 50 }); + const page = await browser.newPage(); + + await page.goto(`${TARGET_URL}/contact`); + + await page.fill('input[name="name"]', 'John Doe'); + await page.fill('input[name="email"]', 'john@example.com'); + await page.fill('textarea[name="message"]', 'Test message'); + await page.click('button[type="submit"]'); + + // Verify submission + await page.waitForSelector('.success-message'); + console.log('✅ Form submitted successfully'); + + await browser.close(); +})(); +``` + +### Check for Broken Links + +```javascript +const { chromium } = require('playwright'); + +(async () => { + const browser = await chromium.launch({ headless: false }); + const page = await browser.newPage(); + + await page.goto('http://localhost:3000'); + + const links = await page.locator('a[href^="http"]').all(); + const results = { working: 0, broken: [] }; + + for (const link of links) { + const href = await link.getAttribute('href'); + try { + const response = await page.request.head(href); + if (response.ok()) { + results.working++; + } else { + results.broken.push({ url: href, status: response.status() }); + } + } catch (e) { + results.broken.push({ url: href, error: e.message }); + } + } + + console.log(`✅ Working links: ${results.working}`); + console.log(`❌ Broken links:`, results.broken); + + await browser.close(); +})(); +``` + +### Take Screenshot with Error Handling + +```javascript +const { chromium } = require('playwright'); + +(async () => { + const browser = await chromium.launch({ headless: false }); + const page = await browser.newPage(); + + try { + await page.goto('http://localhost:3000', { + waitUntil: 'networkidle', + timeout: 10000, + }); + + await page.screenshot({ + path: '/tmp/screenshot.png', + fullPage: true, + }); + + console.log('📸 Screenshot saved to /tmp/screenshot.png'); + } catch (error) { + console.error('❌ Error:', error.message); + } finally { + await browser.close(); + } +})(); +``` + +### Test Responsive Design + +```javascript +// /tmp/playwright-test-responsive-full.js +const { chromium } = require('playwright'); + +const TARGET_URL = 'http://localhost:3001'; // Auto-detected + +(async () => { + const browser = await chromium.launch({ headless: false }); + const page = await browser.newPage(); + + const viewports = [ + { name: 'Desktop', width: 1920, height: 1080 }, + { name: 'Tablet', width: 768, height: 1024 }, + { name: 'Mobile', width: 375, height: 667 }, + ]; + + for (const viewport of viewports) { + console.log( + `Testing ${viewport.name} (${viewport.width}x${viewport.height})`, + ); + + await page.setViewportSize({ + width: viewport.width, + height: viewport.height, + }); + + await page.goto(TARGET_URL); + await page.waitForTimeout(1000); + + await page.screenshot({ + path: `/tmp/${viewport.name.toLowerCase()}.png`, + fullPage: true, + }); + } + + console.log('✅ All viewports tested'); + await browser.close(); +})(); +``` + +## Inline Execution (Simple Tasks) + +For quick one-off tasks, you can execute code inline without creating files: + +```bash +# Take a quick screenshot +cd $SKILL_DIR && node run.js " +const browser = await chromium.launch({ headless: false }); +const page = await browser.newPage(); +await page.goto('http://localhost:3001'); +await page.screenshot({ path: '/tmp/quick-screenshot.png', fullPage: true }); +console.log('Screenshot saved'); +await browser.close(); +" +``` + +**When to use inline vs files:** + +- **Inline**: Quick one-off tasks (screenshot, check if element exists, get page title) +- **Files**: Complex tests, responsive design checks, anything user might want to re-run + +## Available Helpers + +Optional utility functions in `lib/helpers.js`: + +```javascript +const helpers = require('./lib/helpers'); + +// Detect running dev servers (CRITICAL - use this first!) +const servers = await helpers.detectDevServers(); +console.log('Found servers:', servers); + +// Safe click with retry +await helpers.safeClick(page, 'button.submit', { retries: 3 }); + +// Safe type with clear +await helpers.safeType(page, '#username', 'testuser'); + +// Take timestamped screenshot +await helpers.takeScreenshot(page, 'test-result'); + +// Handle cookie banners +await helpers.handleCookieBanner(page); + +// Extract table data +const data = await helpers.extractTableData(page, 'table.results'); +``` + +See `lib/helpers.js` for full list. + +## Custom HTTP Headers + +Configure custom headers for all HTTP requests via environment variables. Useful for: + +- Identifying automated traffic to your backend +- Getting LLM-optimized responses (e.g., plain text errors instead of styled HTML) +- Adding authentication tokens globally + +### Configuration + +**Single header (common case):** + +```bash +PW_HEADER_NAME=X-Automated-By PW_HEADER_VALUE=playwright-skill \ + cd $SKILL_DIR && node run.js /tmp/my-script.js +``` + +**Multiple headers (JSON format):** + +```bash +PW_EXTRA_HEADERS='{"X-Automated-By":"playwright-skill","X-Debug":"true"}' \ + cd $SKILL_DIR && node run.js /tmp/my-script.js +``` + +### How It Works + +Headers are automatically applied when using `helpers.createContext()`: + +```javascript +const context = await helpers.createContext(browser); +const page = await context.newPage(); +// All requests from this page include your custom headers +``` + +For scripts using raw Playwright API, use the injected `getContextOptionsWithHeaders()`: + +```javascript +const context = await browser.newContext( + getContextOptionsWithHeaders({ viewport: { width: 1920, height: 1080 } }), +); +``` + +## Advanced Usage + +For comprehensive Playwright API documentation, see [API_REFERENCE.md](API_REFERENCE.md): + +- Selectors & Locators best practices +- Network interception & API mocking +- Authentication & session management +- Visual regression testing +- Mobile device emulation +- Performance testing +- Debugging techniques +- CI/CD integration + +## Tips + +- **CRITICAL: Detect servers FIRST** - Always run `detectDevServers()` before writing test code for localhost testing +- **Custom headers** - Use `PW_HEADER_NAME`/`PW_HEADER_VALUE` env vars to identify automated traffic to your backend +- **Use /tmp for test files** - Write to `/tmp/playwright-test-*.js`, never to skill directory or user's project +- **Parameterize URLs** - Put detected/provided URL in a `TARGET_URL` constant at the top of every script +- **DEFAULT: Visible browser** - Always use `headless: false` unless user explicitly asks for headless mode +- **Headless mode** - Only use `headless: true` when user specifically requests "headless" or "background" execution +- **Slow down:** Use `slowMo: 100` to make actions visible and easier to follow +- **Wait strategies:** Use `waitForURL`, `waitForSelector`, `waitForLoadState` instead of fixed timeouts +- **Error handling:** Always use try-catch for robust automation +- **Console output:** Use `console.log()` to track progress and show what's happening + +## Troubleshooting + +**Playwright not installed:** + +```bash +cd $SKILL_DIR && npm run setup +``` + +**Module not found:** +Ensure running from skill directory via `run.js` wrapper + +**Browser doesn't open:** +Check `headless: false` and ensure display available + +**Element not found:** +Add wait: `await page.waitForSelector('.element', { timeout: 10000 })` + +## Example Usage + +``` +User: "Test if the marketing page looks good" + +Claude: I'll test the marketing page across multiple viewports. Let me first detect running servers... +[Runs: detectDevServers()] +[Output: Found server on port 3001] +I found your dev server running on http://localhost:3001 + +[Writes custom automation script to /tmp/playwright-test-marketing.js with URL parameterized] +[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-marketing.js] +[Shows results with screenshots from /tmp/] +``` + +``` +User: "Check if login redirects correctly" + +Claude: I'll test the login flow. First, let me check for running servers... +[Runs: detectDevServers()] +[Output: Found servers on ports 3000 and 3001] +I found 2 dev servers. Which one should I test? +- http://localhost:3000 +- http://localhost:3001 + +User: "Use 3001" + +[Writes login automation to /tmp/playwright-test-login.js] +[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-login.js] +[Reports: ✅ Login successful, redirected to /dashboard] +``` + +## Notes + +- Each automation is custom-written for your specific request +- Not limited to pre-built scripts - any browser task possible +- Auto-detects running dev servers to eliminate hardcoded URLs +- Test scripts written to `/tmp` for automatic cleanup (no clutter) +- Code executes reliably with proper module resolution via `run.js` +- Progressive disclosure - API_REFERENCE.md loaded only when advanced features needed + +--- + +## Added: Static HTML vs Dynamic Webapp Decision + +Before writing any test, decide which path the target needs. Missing this step causes the most common failure: inspecting a dynamic page before JS has populated it. + +``` +User task → Is it static HTML (file:// or plain server-rendered)? + ├─ Yes → Read the HTML source directly, identify selectors from the raw markup, + │ write a Playwright script using those selectors. + │ + └─ No (dynamic webapp) → + 1. Navigate to the page + 2. Wait for networkidle: await page.waitForLoadState('networkidle'); + 3. Inspect rendered DOM (screenshot, page.content(), or locator().all()) + 4. Identify selectors from the rendered state, not the source + 5. Execute actions with those selectors +``` + +**Common pitfall:** inspecting the DOM before `networkidle` on a dynamic app returns stale content or an empty skeleton. Every "element not found" bug on dynamic pages should trigger a "did I wait for networkidle?" check first. + +## Added: Reconnaissance-Then-Action Pattern + +For any non-trivial interaction on a dynamic page: + +1. **Reconnoiter.** Navigate, wait for load, capture state: + ```javascript + await page.goto(TARGET_URL); + await page.waitForLoadState('networkidle'); + await page.screenshot({ path: '/tmp/inspect.png', fullPage: true }); + const html = await page.content(); + const buttons = await page.locator('button').all(); + ``` + +2. **Decide.** From the screenshot + content + locator list, pick the selectors you'll use. Don't guess from source. + +3. **Act.** Execute the interaction with the discovered selectors. + +This beats "write what you think the page looks like, run it, fix the selectors when it breaks." Especially valuable for first-time automation on an unfamiliar app. + +## Added: Console Log Capture + +Frontend errors often don't surface in the Playwright output unless captured explicitly. For flaky tests or "works in my browser, fails in Playwright" symptoms: + +```javascript +page.on('console', msg => console.log(`[browser.${msg.type()}] ${msg.text()}`)); +page.on('pageerror', err => console.log(`[browser.pageerror] ${err.message}`)); +page.on('requestfailed', req => console.log(`[browser.requestfailed] ${req.url()} ${req.failure()?.errorText}`)); +``` + +Attach these before `page.goto()`. Messages stream to stdout during the test run, giving you the same signal the browser devtools console would. + +--- + +## Attribution + +Forked from [lackeyjb/playwright-skill](https://github.com/lackeyjb/playwright-skill) — MIT licensed. See `LICENSE` in this directory for the original copyright and terms. + +**Local additions** (not upstream): the three *Added:* sections above (Static HTML vs Dynamic Webapp Decision, Reconnaissance-Then-Action Pattern, Console Log Capture) were added in this fork, informed by patterns from Anthropic's `webapp-testing` skill (the sibling `playwright-py` in this rulesets repo). The upstream skill is self-contained; these additions pair well with it but are not required. diff --git a/playwright-js/lib/helpers.js b/playwright-js/lib/helpers.js new file mode 100644 index 0000000..0920d68 --- /dev/null +++ b/playwright-js/lib/helpers.js @@ -0,0 +1,441 @@ +// playwright-helpers.js +// Reusable utility functions for Playwright automation + +const { chromium, firefox, webkit } = require('playwright'); + +/** + * Parse extra HTTP headers from environment variables. + * Supports two formats: + * - PW_HEADER_NAME + PW_HEADER_VALUE: Single header (simple, common case) + * - PW_EXTRA_HEADERS: JSON object for multiple headers (advanced) + * Single header format takes precedence if both are set. + * @returns {Object|null} Headers object or null if none configured + */ +function getExtraHeadersFromEnv() { + const headerName = process.env.PW_HEADER_NAME; + const headerValue = process.env.PW_HEADER_VALUE; + + if (headerName && headerValue) { + return { [headerName]: headerValue }; + } + + const headersJson = process.env.PW_EXTRA_HEADERS; + if (headersJson) { + try { + const parsed = JSON.parse(headersJson); + if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) { + return parsed; + } + console.warn('PW_EXTRA_HEADERS must be a JSON object, ignoring...'); + } catch (e) { + console.warn('Failed to parse PW_EXTRA_HEADERS as JSON:', e.message); + } + } + + return null; +} + +/** + * Launch browser with standard configuration + * @param {string} browserType - 'chromium', 'firefox', or 'webkit' + * @param {Object} options - Additional launch options + */ +async function launchBrowser(browserType = 'chromium', options = {}) { + const defaultOptions = { + headless: process.env.HEADLESS !== 'false', + slowMo: process.env.SLOW_MO ? parseInt(process.env.SLOW_MO) : 0, + args: ['--no-sandbox', '--disable-setuid-sandbox'] + }; + + const browsers = { chromium, firefox, webkit }; + const browser = browsers[browserType]; + + if (!browser) { + throw new Error(`Invalid browser type: ${browserType}`); + } + + return await browser.launch({ ...defaultOptions, ...options }); +} + +/** + * Create a new page with viewport and user agent + * @param {Object} context - Browser context + * @param {Object} options - Page options + */ +async function createPage(context, options = {}) { + const page = await context.newPage(); + + if (options.viewport) { + await page.setViewportSize(options.viewport); + } + + if (options.userAgent) { + await page.setExtraHTTPHeaders({ + 'User-Agent': options.userAgent + }); + } + + // Set default timeout + page.setDefaultTimeout(options.timeout || 30000); + + return page; +} + +/** + * Smart wait for page to be ready + * @param {Object} page - Playwright page + * @param {Object} options - Wait options + */ +async function waitForPageReady(page, options = {}) { + const waitOptions = { + waitUntil: options.waitUntil || 'networkidle', + timeout: options.timeout || 30000 + }; + + try { + await page.waitForLoadState(waitOptions.waitUntil, { + timeout: waitOptions.timeout + }); + } catch (e) { + console.warn('Page load timeout, continuing...'); + } + + // Additional wait for dynamic content if selector provided + if (options.waitForSelector) { + await page.waitForSelector(options.waitForSelector, { + timeout: options.timeout + }); + } +} + +/** + * Safe click with retry logic + * @param {Object} page - Playwright page + * @param {string} selector - Element selector + * @param {Object} options - Click options + */ +async function safeClick(page, selector, options = {}) { + const maxRetries = options.retries || 3; + const retryDelay = options.retryDelay || 1000; + + for (let i = 0; i < maxRetries; i++) { + try { + await page.waitForSelector(selector, { + state: 'visible', + timeout: options.timeout || 5000 + }); + await page.click(selector, { + force: options.force || false, + timeout: options.timeout || 5000 + }); + return true; + } catch (e) { + if (i === maxRetries - 1) { + console.error(`Failed to click ${selector} after ${maxRetries} attempts`); + throw e; + } + console.log(`Retry ${i + 1}/${maxRetries} for clicking ${selector}`); + await page.waitForTimeout(retryDelay); + } + } +} + +/** + * Safe text input with clear before type + * @param {Object} page - Playwright page + * @param {string} selector - Input selector + * @param {string} text - Text to type + * @param {Object} options - Type options + */ +async function safeType(page, selector, text, options = {}) { + await page.waitForSelector(selector, { + state: 'visible', + timeout: options.timeout || 10000 + }); + + if (options.clear !== false) { + await page.fill(selector, ''); + } + + if (options.slow) { + await page.type(selector, text, { delay: options.delay || 100 }); + } else { + await page.fill(selector, text); + } +} + +/** + * Extract text from multiple elements + * @param {Object} page - Playwright page + * @param {string} selector - Elements selector + */ +async function extractTexts(page, selector) { + await page.waitForSelector(selector, { timeout: 10000 }); + return await page.$$eval(selector, elements => + elements.map(el => el.textContent?.trim()).filter(Boolean) + ); +} + +/** + * Take screenshot with timestamp + * @param {Object} page - Playwright page + * @param {string} name - Screenshot name + * @param {Object} options - Screenshot options + */ +async function takeScreenshot(page, name, options = {}) { + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + const filename = `${name}-${timestamp}.png`; + + await page.screenshot({ + path: filename, + fullPage: options.fullPage !== false, + ...options + }); + + console.log(`Screenshot saved: ${filename}`); + return filename; +} + +/** + * Handle authentication + * @param {Object} page - Playwright page + * @param {Object} credentials - Username and password + * @param {Object} selectors - Login form selectors + */ +async function authenticate(page, credentials, selectors = {}) { + const defaultSelectors = { + username: 'input[name="username"], input[name="email"], #username, #email', + password: 'input[name="password"], #password', + submit: 'button[type="submit"], input[type="submit"], button:has-text("Login"), button:has-text("Sign in")' + }; + + const finalSelectors = { ...defaultSelectors, ...selectors }; + + await safeType(page, finalSelectors.username, credentials.username); + await safeType(page, finalSelectors.password, credentials.password); + await safeClick(page, finalSelectors.submit); + + // Wait for navigation or success indicator + await Promise.race([ + page.waitForNavigation({ waitUntil: 'networkidle' }), + page.waitForSelector(selectors.successIndicator || '.dashboard, .user-menu, .logout', { timeout: 10000 }) + ]).catch(() => { + console.log('Login might have completed without navigation'); + }); +} + +/** + * Scroll page + * @param {Object} page - Playwright page + * @param {string} direction - 'down', 'up', 'top', 'bottom' + * @param {number} distance - Pixels to scroll (for up/down) + */ +async function scrollPage(page, direction = 'down', distance = 500) { + switch (direction) { + case 'down': + await page.evaluate(d => window.scrollBy(0, d), distance); + break; + case 'up': + await page.evaluate(d => window.scrollBy(0, -d), distance); + break; + case 'top': + await page.evaluate(() => window.scrollTo(0, 0)); + break; + case 'bottom': + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + break; + } + await page.waitForTimeout(500); // Wait for scroll animation +} + +/** + * Extract table data + * @param {Object} page - Playwright page + * @param {string} tableSelector - Table selector + */ +async function extractTableData(page, tableSelector) { + await page.waitForSelector(tableSelector); + + return await page.evaluate((selector) => { + const table = document.querySelector(selector); + if (!table) return null; + + const headers = Array.from(table.querySelectorAll('thead th')).map(th => + th.textContent?.trim() + ); + + const rows = Array.from(table.querySelectorAll('tbody tr')).map(tr => { + const cells = Array.from(tr.querySelectorAll('td')); + if (headers.length > 0) { + return cells.reduce((obj, cell, index) => { + obj[headers[index] || `column_${index}`] = cell.textContent?.trim(); + return obj; + }, {}); + } else { + return cells.map(cell => cell.textContent?.trim()); + } + }); + + return { headers, rows }; + }, tableSelector); +} + +/** + * Wait for and dismiss cookie banners + * @param {Object} page - Playwright page + * @param {number} timeout - Max time to wait + */ +async function handleCookieBanner(page, timeout = 3000) { + const commonSelectors = [ + 'button:has-text("Accept")', + 'button:has-text("Accept all")', + 'button:has-text("OK")', + 'button:has-text("Got it")', + 'button:has-text("I agree")', + '.cookie-accept', + '#cookie-accept', + '[data-testid="cookie-accept"]' + ]; + + for (const selector of commonSelectors) { + try { + const element = await page.waitForSelector(selector, { + timeout: timeout / commonSelectors.length, + state: 'visible' + }); + if (element) { + await element.click(); + console.log('Cookie banner dismissed'); + return true; + } + } catch (e) { + // Continue to next selector + } + } + + return false; +} + +/** + * Retry a function with exponential backoff + * @param {Function} fn - Function to retry + * @param {number} maxRetries - Maximum retry attempts + * @param {number} initialDelay - Initial delay in ms + */ +async function retryWithBackoff(fn, maxRetries = 3, initialDelay = 1000) { + let lastError; + + for (let i = 0; i < maxRetries; i++) { + try { + return await fn(); + } catch (error) { + lastError = error; + const delay = initialDelay * Math.pow(2, i); + console.log(`Attempt ${i + 1} failed, retrying in ${delay}ms...`); + await new Promise(resolve => setTimeout(resolve, delay)); + } + } + + throw lastError; +} + +/** + * Create browser context with common settings + * @param {Object} browser - Browser instance + * @param {Object} options - Context options + */ +async function createContext(browser, options = {}) { + const envHeaders = getExtraHeadersFromEnv(); + + // Merge environment headers with any passed in options + const mergedHeaders = { + ...envHeaders, + ...options.extraHTTPHeaders + }; + + const defaultOptions = { + viewport: { width: 1280, height: 720 }, + userAgent: options.mobile + ? 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1' + : undefined, + permissions: options.permissions || [], + geolocation: options.geolocation, + locale: options.locale || 'en-US', + timezoneId: options.timezoneId || 'America/New_York', + // Only include extraHTTPHeaders if we have any + ...(Object.keys(mergedHeaders).length > 0 && { extraHTTPHeaders: mergedHeaders }) + }; + + return await browser.newContext({ ...defaultOptions, ...options }); +} + +/** + * Detect running dev servers on common ports + * @param {Array} customPorts - Additional ports to check + * @returns {Promise} Array of detected server URLs + */ +async function detectDevServers(customPorts = []) { + const http = require('http'); + + // Common dev server ports + const commonPorts = [3000, 3001, 3002, 5173, 8080, 8000, 4200, 5000, 9000, 1234]; + const allPorts = [...new Set([...commonPorts, ...customPorts])]; + + const detectedServers = []; + + console.log('🔍 Checking for running dev servers...'); + + for (const port of allPorts) { + try { + await new Promise((resolve, reject) => { + const req = http.request({ + hostname: 'localhost', + port: port, + path: '/', + method: 'HEAD', + timeout: 500 + }, (res) => { + if (res.statusCode < 500) { + detectedServers.push(`http://localhost:${port}`); + console.log(` ✅ Found server on port ${port}`); + } + resolve(); + }); + + req.on('error', () => resolve()); + req.on('timeout', () => { + req.destroy(); + resolve(); + }); + + req.end(); + }); + } catch (e) { + // Port not available, continue + } + } + + if (detectedServers.length === 0) { + console.log(' ❌ No dev servers detected'); + } + + return detectedServers; +} + +module.exports = { + launchBrowser, + createPage, + waitForPageReady, + safeClick, + safeType, + extractTexts, + takeScreenshot, + authenticate, + scrollPage, + extractTableData, + handleCookieBanner, + retryWithBackoff, + createContext, + detectDevServers, + getExtraHeadersFromEnv +}; diff --git a/playwright-js/package.json b/playwright-js/package.json new file mode 100644 index 0000000..ada6c8b --- /dev/null +++ b/playwright-js/package.json @@ -0,0 +1,26 @@ +{ + "name": "playwright-skill", + "version": "4.1.0", + "description": "General-purpose browser automation with Playwright for Claude Code with auto-detection and smart test management", + "author": "lackeyjb", + "main": "run.js", + "scripts": { + "setup": "npm install && npx playwright install chromium", + "install-all-browsers": "npx playwright install chromium firefox webkit" + }, + "keywords": [ + "playwright", + "automation", + "browser-testing", + "web-automation", + "claude-skill", + "general-purpose" + ], + "dependencies": { + "playwright": "^1.57.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "license": "MIT" +} diff --git a/playwright-js/run.js b/playwright-js/run.js new file mode 100755 index 0000000..10f2616 --- /dev/null +++ b/playwright-js/run.js @@ -0,0 +1,228 @@ +#!/usr/bin/env node +/** + * Universal Playwright Executor for Claude Code + * + * Executes Playwright automation code from: + * - File path: node run.js script.js + * - Inline code: node run.js 'await page.goto("...")' + * - Stdin: cat script.js | node run.js + * + * Ensures proper module resolution by running from skill directory. + */ + +const fs = require('fs'); +const path = require('path'); +const { execSync } = require('child_process'); + +// Change to skill directory for proper module resolution +process.chdir(__dirname); + +/** + * Check if Playwright is installed + */ +function checkPlaywrightInstalled() { + try { + require.resolve('playwright'); + return true; + } catch (e) { + return false; + } +} + +/** + * Install Playwright if missing + */ +function installPlaywright() { + console.log('📦 Playwright not found. Installing...'); + try { + execSync('npm install', { stdio: 'inherit', cwd: __dirname }); + execSync('npx playwright install chromium', { stdio: 'inherit', cwd: __dirname }); + console.log('✅ Playwright installed successfully'); + return true; + } catch (e) { + console.error('❌ Failed to install Playwright:', e.message); + console.error('Please run manually: cd', __dirname, '&& npm run setup'); + return false; + } +} + +/** + * Get code to execute from various sources + */ +function getCodeToExecute() { + const args = process.argv.slice(2); + + // Case 1: File path provided + if (args.length > 0 && fs.existsSync(args[0])) { + const filePath = path.resolve(args[0]); + console.log(`📄 Executing file: ${filePath}`); + return fs.readFileSync(filePath, 'utf8'); + } + + // Case 2: Inline code provided as argument + if (args.length > 0) { + console.log('⚡ Executing inline code'); + return args.join(' '); + } + + // Case 3: Code from stdin + if (!process.stdin.isTTY) { + console.log('📥 Reading from stdin'); + return fs.readFileSync(0, 'utf8'); + } + + // No input + console.error('❌ No code to execute'); + console.error('Usage:'); + console.error(' node run.js script.js # Execute file'); + console.error(' node run.js "code here" # Execute inline'); + console.error(' cat script.js | node run.js # Execute from stdin'); + process.exit(1); +} + +/** + * Clean up old temporary execution files from previous runs + */ +function cleanupOldTempFiles() { + try { + const files = fs.readdirSync(__dirname); + const tempFiles = files.filter(f => f.startsWith('.temp-execution-') && f.endsWith('.js')); + + if (tempFiles.length > 0) { + tempFiles.forEach(file => { + const filePath = path.join(__dirname, file); + try { + fs.unlinkSync(filePath); + } catch (e) { + // Ignore errors - file might be in use or already deleted + } + }); + } + } catch (e) { + // Ignore directory read errors + } +} + +/** + * Wrap code in async IIFE if not already wrapped + */ +function wrapCodeIfNeeded(code) { + // Check if code already has require() and async structure + const hasRequire = code.includes('require('); + const hasAsyncIIFE = code.includes('(async () => {') || code.includes('(async()=>{'); + + // If it's already a complete script, return as-is + if (hasRequire && hasAsyncIIFE) { + return code; + } + + // If it's just Playwright commands, wrap in full template + if (!hasRequire) { + return ` +const { chromium, firefox, webkit, devices } = require('playwright'); +const helpers = require('./lib/helpers'); + +// Extra headers from environment variables (if configured) +const __extraHeaders = helpers.getExtraHeadersFromEnv(); + +/** + * Utility to merge environment headers into context options. + * Use when creating contexts with raw Playwright API instead of helpers.createContext(). + * @param {Object} options - Context options + * @returns {Object} Options with extraHTTPHeaders merged in + */ +function getContextOptionsWithHeaders(options = {}) { + if (!__extraHeaders) return options; + return { + ...options, + extraHTTPHeaders: { + ...__extraHeaders, + ...(options.extraHTTPHeaders || {}) + } + }; +} + +(async () => { + try { + ${code} + } catch (error) { + console.error('❌ Automation error:', error.message); + if (error.stack) { + console.error(error.stack); + } + process.exit(1); + } +})(); +`; + } + + // If has require but no async wrapper + if (!hasAsyncIIFE) { + return ` +(async () => { + try { + ${code} + } catch (error) { + console.error('❌ Automation error:', error.message); + if (error.stack) { + console.error(error.stack); + } + process.exit(1); + } +})(); +`; + } + + return code; +} + +/** + * Main execution + */ +async function main() { + console.log('🎭 Playwright Skill - Universal Executor\n'); + + // Clean up old temp files from previous runs + cleanupOldTempFiles(); + + // Check Playwright installation + if (!checkPlaywrightInstalled()) { + const installed = installPlaywright(); + if (!installed) { + process.exit(1); + } + } + + // Get code to execute + const rawCode = getCodeToExecute(); + const code = wrapCodeIfNeeded(rawCode); + + // Create temporary file for execution + const tempFile = path.join(__dirname, `.temp-execution-${Date.now()}.js`); + + try { + // Write code to temp file + fs.writeFileSync(tempFile, code, 'utf8'); + + // Execute the code + console.log('🚀 Starting automation...\n'); + require(tempFile); + + // Note: Temp file will be cleaned up on next run + // This allows long-running async operations to complete safely + + } catch (error) { + console.error('❌ Execution failed:', error.message); + if (error.stack) { + console.error('\n📋 Stack trace:'); + console.error(error.stack); + } + process.exit(1); + } +} + +// Run main function +main().catch(error => { + console.error('❌ Fatal error:', error.message); + process.exit(1); +}); diff --git a/playwright-py/LICENSE.txt b/playwright-py/LICENSE.txt new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/playwright-py/LICENSE.txt @@ -0,0 +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 [yyyy] [name of copyright owner] + + 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. \ No newline at end of file diff --git a/playwright-py/SKILL.md b/playwright-py/SKILL.md new file mode 100644 index 0000000..1dee60e --- /dev/null +++ b/playwright-py/SKILL.md @@ -0,0 +1,175 @@ +--- +name: playwright-py +description: Browser automation and UI testing with Playwright using the Python (sync_api) bindings. Native Python scripts using `playwright.sync_api`, server lifecycle management via `with_server.py` (can manage backend + frontend simultaneously), headless Chromium by default, reconnaissance-then-action methodology for dynamic pages. Ships bundled helpers (dev server probe, safe click/type with retries, cookie banner handler, env-driven header injection) and worked examples (login flow, broken-link scan, responsive viewport sweep). Use when testing a web app with a Python stack (Django, FastAPI, Flask), when wiring browser tests into pytest, or when backend and frontend need to be launched together. See also `/playwright-js` for JavaScript/TypeScript variant (React, Next.js, Vue frontends). +license: Complete terms in LICENSE.txt +--- + +# Web Application Testing + +To test local web applications, write native Python Playwright scripts. + +**Helper Scripts Available**: +- `scripts/with_server.py` - Manages server lifecycle (supports multiple servers) + +**Always run scripts with `--help` first** to see usage. DO NOT read the source until you try running the script first and find that a customized solution is abslutely necessary. These scripts can be very large and thus pollute your context window. They exist to be called directly as black-box scripts rather than ingested into your context window. + +## Decision Tree: Choosing Your Approach + +``` +User task → Is it static HTML? + ├─ Yes → Read HTML file directly to identify selectors + │ ├─ Success → Write Playwright script using selectors + │ └─ Fails/Incomplete → Treat as dynamic (below) + │ + └─ No (dynamic webapp) → Is the server already running? + ├─ No → Run: python scripts/with_server.py --help + │ Then use the helper + write simplified Playwright script + │ + └─ Yes → Reconnaissance-then-action: + 1. Navigate and wait for networkidle + 2. Take screenshot or inspect DOM + 3. Identify selectors from rendered state + 4. Execute actions with discovered selectors +``` + +## Example: Using with_server.py + +To start a server, run `--help` first, then use the helper: + +**Single server:** +```bash +python scripts/with_server.py --server "npm run dev" --port 5173 -- python your_automation.py +``` + +**Multiple servers (e.g., backend + frontend):** +```bash +python scripts/with_server.py \ + --server "cd backend && python server.py" --port 3000 \ + --server "cd frontend && npm run dev" --port 5173 \ + -- python your_automation.py +``` + +To create an automation script, include only Playwright logic (servers are managed automatically): +```python +from playwright.sync_api import sync_playwright + +with sync_playwright() as p: + browser = p.chromium.launch(headless=True) # Always launch chromium in headless mode + page = browser.new_page() + page.goto('http://localhost:5173') # Server already running and ready + page.wait_for_load_state('networkidle') # CRITICAL: Wait for JS to execute + # ... your automation logic + browser.close() +``` + +## Reconnaissance-Then-Action Pattern + +1. **Inspect rendered DOM**: + ```python + page.screenshot(path='/tmp/inspect.png', full_page=True) + content = page.content() + page.locator('button').all() + ``` + +2. **Identify selectors** from inspection results + +3. **Execute actions** using discovered selectors + +## Common Pitfall + +❌ **Don't** inspect the DOM before waiting for `networkidle` on dynamic apps +✅ **Do** wait for `page.wait_for_load_state('networkidle')` before inspection + +## Best Practices + +- **Use bundled scripts as black boxes** - To accomplish a task, consider whether one of the scripts available in `scripts/` can help. These scripts handle common, complex workflows reliably without cluttering the context window. Use `--help` to see usage, then invoke directly. +- Use `sync_playwright()` for synchronous scripts +- Always close the browser when done +- Use descriptive selectors: `text=`, `role=`, CSS selectors, or IDs +- Add appropriate waits: `page.wait_for_selector()` or `page.wait_for_timeout()` + +## Reference Files + +- **examples/** - Examples showing common patterns: + - `element_discovery.py` - Discovering buttons, links, and inputs on a page + - `static_html_automation.py` - Using file:// URLs for local HTML + - `console_logging.py` - Capturing console logs during automation + - `login_flow.py` - Worked login example (added in this fork) + - `broken_links.py` - Scan visible external links for broken URLs (added in this fork) + - `responsive_sweep.py` - Screenshot multiple viewports for responsive QA (added in this fork) + +--- + +## Added: Dev Server Detection + +Before testing, see what's running on localhost. Run the bundled helper: + +```bash +python scripts/detect_dev_servers.py +``` + +Outputs JSON: `[{"port": 5173, "url": "http://localhost:5173", "server": "vite"}, ...]`. Use this to discover the target URL rather than hardcoding it. If nothing is found, either start the server manually or use `scripts/with_server.py`. + +## Added: Retry Helpers + +Dynamic pages sometimes fail a click or fill on the first try. `scripts/safe_actions.py` provides retry-wrapped wrappers and a cookie-banner handler: + +```python +from scripts.safe_actions import safe_click, safe_type, handle_cookie_banner + +page.goto(TARGET_URL) +page.wait_for_load_state('networkidle') +handle_cookie_banner(page) # clicks common accept buttons if present +safe_type(page, 'input[name="email"]', 'test@example.com') +safe_click(page, 'button[type="submit"]') +``` + +Each helper retries up to 3 times with a short delay and re-raises the last error if all attempts fail. + +## Added: Env-Driven Header Injection + +For authenticated testing without hardcoding tokens. Set env vars: + +```bash +export PW_HEADER_NAME="Authorization" +export PW_HEADER_VALUE="Bearer eyJhbGciOi…" +# or multiple: +export PW_EXTRA_HEADERS='{"X-API-Key": "…", "X-Tenant": "acme"}' +``` + +Then in your script: + +```python +from scripts.safe_actions import build_context_with_headers + +with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + context = build_context_with_headers(browser) # auto-applies env vars + page = context.new_page() + ... +``` + +Falls back to no extra headers when env vars are unset. + +## Added: Script Discipline + +Write ad-hoc Playwright automation scripts to `/tmp/pw--.py`, not into the project directory. Reasons: + +- OS reaps `/tmp` periodically; no stale test files to clean up +- Scripts don't clutter git status +- Keeps the project tree focused on code and not on investigation artifacts + +For reusable tests that belong to the project (pytest suites, CI scripts), commit them under `tests/` as usual. One-off investigation scripts go in `/tmp`. + +--- + +## Attribution + +Forked from [anthropics/skills/skills/webapp-testing](https://github.com/anthropics/skills/tree/main/skills/webapp-testing) — Apache 2.0 licensed. See `LICENSE.txt` in this directory for the original copyright and terms. + +**Local additions** (not upstream): +- `scripts/detect_dev_servers.py`, `scripts/safe_actions.py` — new helpers inspired by the sibling `playwright-js` skill (lackeyjb MIT) which bundles equivalent helpers in JavaScript. +- `examples/login_flow.py`, `examples/broken_links.py`, `examples/responsive_sweep.py` — worked examples. +- The five *Added:* sections above (Dev Server Detection, Retry Helpers, Env-Driven Header Injection, Script Discipline, and updated Reference Files list). + +The upstream skill is self-contained and headless-by-default; the additions here pair the Python side with the same conveniences Craig's `playwright-js` fork has on the JavaScript side, without changing upstream semantics. \ No newline at end of file diff --git a/playwright-py/examples/broken_links.py b/playwright-py/examples/broken_links.py new file mode 100644 index 0000000..c78520f --- /dev/null +++ b/playwright-py/examples/broken_links.py @@ -0,0 +1,58 @@ +"""Worked example: scan visible external links on a page for broken URLs. + +Env vars used: + TARGET_URL (default: http://localhost:5173) + +Run: + python examples/broken_links.py +""" + +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from playwright.sync_api import sync_playwright +from scripts.safe_actions import build_context_with_headers + +TARGET_URL = os.environ.get("TARGET_URL", "http://localhost:5173") + + +def main() -> int: + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + context = build_context_with_headers(browser) + page = context.new_page() + + page.goto(TARGET_URL) + page.wait_for_load_state("networkidle") + + # Collect unique external hrefs + links = page.locator('a[href^="http"]').all() + urls = sorted( + {link.get_attribute("href") for link in links if link.get_attribute("href")} + ) + + ok, bad, err = 0, 0, 0 + for url in urls: + try: + resp = page.request.head(url, timeout=5000) + status = resp.status + if status < 400: + ok += 1 + print(f"✓ {status} {url}") + else: + bad += 1 + print(f"✗ {status} {url}") + except Exception as ex: + err += 1 + print(f"✗ ERR {url} ({type(ex).__name__}: {ex})") + + print(f"\n{ok} ok, {bad} broken, {err} errored out of {len(urls)} total") + browser.close() + return 0 if (bad == 0 and err == 0) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/playwright-py/examples/console_logging.py b/playwright-py/examples/console_logging.py new file mode 100644 index 0000000..9329b5e --- /dev/null +++ b/playwright-py/examples/console_logging.py @@ -0,0 +1,35 @@ +from playwright.sync_api import sync_playwright + +# Example: Capturing console logs during browser automation + +url = 'http://localhost:5173' # Replace with your URL + +console_logs = [] + +with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + page = browser.new_page(viewport={'width': 1920, 'height': 1080}) + + # Set up console log capture + def handle_console_message(msg): + console_logs.append(f"[{msg.type}] {msg.text}") + print(f"Console: [{msg.type}] {msg.text}") + + page.on("console", handle_console_message) + + # Navigate to page + page.goto(url) + page.wait_for_load_state('networkidle') + + # Interact with the page (triggers console logs) + page.click('text=Dashboard') + page.wait_for_timeout(1000) + + browser.close() + +# Save console logs to file +with open('/mnt/user-data/outputs/console.log', 'w') as f: + f.write('\n'.join(console_logs)) + +print(f"\nCaptured {len(console_logs)} console messages") +print(f"Logs saved to: /mnt/user-data/outputs/console.log") \ No newline at end of file diff --git a/playwright-py/examples/element_discovery.py b/playwright-py/examples/element_discovery.py new file mode 100644 index 0000000..917ba72 --- /dev/null +++ b/playwright-py/examples/element_discovery.py @@ -0,0 +1,40 @@ +from playwright.sync_api import sync_playwright + +# Example: Discovering buttons and other elements on a page + +with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + page = browser.new_page() + + # Navigate to page and wait for it to fully load + page.goto('http://localhost:5173') + page.wait_for_load_state('networkidle') + + # Discover all buttons on the page + buttons = page.locator('button').all() + print(f"Found {len(buttons)} buttons:") + for i, button in enumerate(buttons): + text = button.inner_text() if button.is_visible() else "[hidden]" + print(f" [{i}] {text}") + + # Discover links + links = page.locator('a[href]').all() + print(f"\nFound {len(links)} links:") + for link in links[:5]: # Show first 5 + text = link.inner_text().strip() + href = link.get_attribute('href') + print(f" - {text} -> {href}") + + # Discover input fields + inputs = page.locator('input, textarea, select').all() + print(f"\nFound {len(inputs)} input fields:") + for input_elem in inputs: + name = input_elem.get_attribute('name') or input_elem.get_attribute('id') or "[unnamed]" + input_type = input_elem.get_attribute('type') or 'text' + print(f" - {name} ({input_type})") + + # Take screenshot for visual reference + page.screenshot(path='/tmp/page_discovery.png', full_page=True) + print("\nScreenshot saved to /tmp/page_discovery.png") + + browser.close() \ No newline at end of file diff --git a/playwright-py/examples/login_flow.py b/playwright-py/examples/login_flow.py new file mode 100644 index 0000000..d114ac6 --- /dev/null +++ b/playwright-py/examples/login_flow.py @@ -0,0 +1,55 @@ +"""Worked example: log in and verify redirect. + +Env vars used: + TARGET_URL (default: http://localhost:5173) + TEST_USER (default: test@example.com) + TEST_PASS (default: password123) + +Run from within the skill directory (so `scripts.safe_actions` resolves): + python examples/login_flow.py +""" + +import os +import sys +from pathlib import Path + +# Make sibling scripts/ importable +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from playwright.sync_api import sync_playwright +from scripts.safe_actions import ( + handle_cookie_banner, + safe_click, + safe_type, + build_context_with_headers, +) + +TARGET_URL = os.environ.get("TARGET_URL", "http://localhost:5173") +TEST_USER = os.environ.get("TEST_USER", "test@example.com") +TEST_PASS = os.environ.get("TEST_PASS", "password123") + + +def main() -> int: + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + context = build_context_with_headers(browser) + page = context.new_page() + + page.goto(f"{TARGET_URL}/login") + page.wait_for_load_state("networkidle") + + handle_cookie_banner(page) + + safe_type(page, 'input[name="username"], input[name="email"]', TEST_USER) + safe_type(page, 'input[name="password"]', TEST_PASS) + safe_click(page, 'button[type="submit"]') + + page.wait_for_url("**/dashboard", timeout=5000) + print(f"✓ Logged in; redirected to {page.url}") + + browser.close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/playwright-py/examples/responsive_sweep.py b/playwright-py/examples/responsive_sweep.py new file mode 100644 index 0000000..d890d5b --- /dev/null +++ b/playwright-py/examples/responsive_sweep.py @@ -0,0 +1,51 @@ +"""Worked example: screenshot each viewport for responsive QA. + +Env vars used: + TARGET_URL (default: http://localhost:5173) + OUTPUT_DIR (default: /tmp) + +Run: + python examples/responsive_sweep.py +""" + +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from playwright.sync_api import sync_playwright +from scripts.safe_actions import build_context_with_headers + +TARGET_URL = os.environ.get("TARGET_URL", "http://localhost:5173") +OUTPUT_DIR = Path(os.environ.get("OUTPUT_DIR", "/tmp")) + +VIEWPORTS = [ + ("desktop", 1920, 1080), + ("laptop", 1366, 768), + ("tablet", 768, 1024), + ("mobile", 375, 667), +] + + +def main() -> int: + OUTPUT_DIR.mkdir(parents=True, exist_ok=True) + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + for name, width, height in VIEWPORTS: + context = build_context_with_headers( + browser, extra_kwargs={"viewport": {"width": width, "height": height}} + ) + page = context.new_page() + page.goto(TARGET_URL) + page.wait_for_load_state("networkidle") + path = OUTPUT_DIR / f"responsive-{name}.png" + page.screenshot(path=str(path), full_page=True) + print(f"✓ {name:<8} ({width:>4}x{height:<4}) → {path}") + context.close() + browser.close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/playwright-py/examples/static_html_automation.py b/playwright-py/examples/static_html_automation.py new file mode 100644 index 0000000..90bbedc --- /dev/null +++ b/playwright-py/examples/static_html_automation.py @@ -0,0 +1,33 @@ +from playwright.sync_api import sync_playwright +import os + +# Example: Automating interaction with static HTML files using file:// URLs + +html_file_path = os.path.abspath('path/to/your/file.html') +file_url = f'file://{html_file_path}' + +with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + page = browser.new_page(viewport={'width': 1920, 'height': 1080}) + + # Navigate to local HTML file + page.goto(file_url) + + # Take screenshot + page.screenshot(path='/mnt/user-data/outputs/static_page.png', full_page=True) + + # Interact with elements + page.click('text=Click Me') + page.fill('#name', 'John Doe') + page.fill('#email', 'john@example.com') + + # Submit form + page.click('button[type="submit"]') + page.wait_for_timeout(500) + + # Take final screenshot + page.screenshot(path='/mnt/user-data/outputs/after_submit.png', full_page=True) + + browser.close() + +print("Static HTML automation completed!") \ No newline at end of file diff --git a/playwright-py/scripts/detect_dev_servers.py b/playwright-py/scripts/detect_dev_servers.py new file mode 100644 index 0000000..fb8b1ea --- /dev/null +++ b/playwright-py/scripts/detect_dev_servers.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Probe common localhost ports for running HTTP dev servers. + +Outputs JSON: [{"port": N, "url": "http://localhost:N", "server": ""}, ...] + +Usage: + python detect_dev_servers.py + python detect_dev_servers.py --ports 3000,5173,8000 + python detect_dev_servers.py --host localhost --ports 8080 +""" + +import argparse +import json +import socket +import sys +import urllib.request + +DEFAULT_PORTS = [3000, 3001, 4200, 5000, 5173, 5500, 8000, 8080, 8888, 9000] + + +def is_port_open(host: str, port: int, timeout: float = 0.3) -> bool: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(timeout) + try: + s.connect((host, port)) + return True + except (socket.timeout, ConnectionRefusedError, OSError): + return False + + +def probe_http(url: str, timeout: float = 0.5) -> str | None: + """Return a short hint about the server (e.g. its Server header), or None.""" + try: + req = urllib.request.Request(url, headers={"User-Agent": "detect_dev_servers"}) + with urllib.request.urlopen(req, timeout=timeout) as resp: + server = resp.headers.get("Server", "") + return server or "http" + except Exception: + return None + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--ports", + default=",".join(str(p) for p in DEFAULT_PORTS), + help="Comma-separated port list", + ) + parser.add_argument("--host", default="localhost") + args = parser.parse_args() + + try: + ports = [int(p.strip()) for p in args.ports.split(",") if p.strip()] + except ValueError as err: + print(f"ERROR: bad --ports value: {err}", file=sys.stderr) + return 2 + + results = [] + for port in ports: + if is_port_open(args.host, port): + url = f"http://{args.host}:{port}" + hint = probe_http(url) + if hint is not None: + results.append({"port": port, "url": url, "server": hint}) + + print(json.dumps(results, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/playwright-py/scripts/safe_actions.py b/playwright-py/scripts/safe_actions.py new file mode 100644 index 0000000..c3f72bf --- /dev/null +++ b/playwright-py/scripts/safe_actions.py @@ -0,0 +1,100 @@ +"""Retry-wrapped Playwright action helpers + common convenience utilities. + +Usage: + from scripts.safe_actions import ( + safe_click, safe_type, handle_cookie_banner, build_context_with_headers + ) +""" + +import json +import os +import time + + +def safe_click(page, selector, retries: int = 3, delay: float = 0.5, timeout: int = 5000): + """Click SELECTOR. Retry up to RETRIES times with DELAY seconds between. + + Raises the last exception if all attempts fail. + """ + last_err = None + for attempt in range(retries): + try: + page.wait_for_selector(selector, timeout=timeout) + page.click(selector) + return + except Exception as err: + last_err = err + if attempt < retries - 1: + time.sleep(delay) + raise last_err # type: ignore[misc] + + +def safe_type(page, selector, value: str, retries: int = 3, delay: float = 0.5, timeout: int = 5000): + """Fill SELECTOR with VALUE. Retry on failure.""" + last_err = None + for attempt in range(retries): + try: + page.wait_for_selector(selector, timeout=timeout) + page.fill(selector, value) + return + except Exception as err: + last_err = err + if attempt < retries - 1: + time.sleep(delay) + raise last_err # type: ignore[misc] + + +def handle_cookie_banner(page, selectors=None) -> bool: + """Try common cookie-banner accept selectors; click the first that exists. + + Returns True if a banner was found and clicked, False otherwise. + Does not raise on failure — many pages have no banner. + """ + selectors = selectors or [ + "#onetrust-accept-btn-handler", + 'button[aria-label*="ccept" i]', + 'button:has-text("Accept")', + 'button:has-text("I agree")', + 'button:has-text("Got it")', + '[data-testid="uc-accept-all-button"]', + "#cookie-accept", + ".cookie-accept", + ] + for selector in selectors: + try: + if page.locator(selector).count() > 0: + page.click(selector, timeout=1000) + return True + except Exception: + continue + return False + + +def build_context_with_headers(browser, extra_kwargs=None): + """Create a browser context with extra HTTP headers from env vars. + + Reads: + PW_HEADER_NAME / PW_HEADER_VALUE — single header + PW_EXTRA_HEADERS='{"X-A":"1","X-B":"2"}' — JSON object of headers + + Unset env vars → plain context with no extra headers. + extra_kwargs, if supplied, are passed to browser.new_context(). + """ + headers: dict[str, str] = {} + name = os.environ.get("PW_HEADER_NAME") + value = os.environ.get("PW_HEADER_VALUE") + if name and value: + headers[name] = value + extra = os.environ.get("PW_EXTRA_HEADERS") + if extra: + try: + parsed = json.loads(extra) + if isinstance(parsed, dict): + headers.update({str(k): str(v) for k, v in parsed.items()}) + except json.JSONDecodeError: + pass + + kwargs: dict = dict(extra_kwargs or {}) + if headers: + kwargs["extra_http_headers"] = headers + return browser.new_context(**kwargs) diff --git a/playwright-py/scripts/with_server.py b/playwright-py/scripts/with_server.py new file mode 100755 index 0000000..431f2eb --- /dev/null +++ b/playwright-py/scripts/with_server.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +""" +Start one or more servers, wait for them to be ready, run a command, then clean up. + +Usage: + # Single server + python scripts/with_server.py --server "npm run dev" --port 5173 -- python automation.py + python scripts/with_server.py --server "npm start" --port 3000 -- python test.py + + # Multiple servers + python scripts/with_server.py \ + --server "cd backend && python server.py" --port 3000 \ + --server "cd frontend && npm run dev" --port 5173 \ + -- python test.py +""" + +import subprocess +import socket +import time +import sys +import argparse + +def is_server_ready(port, timeout=30): + """Wait for server to be ready by polling the port.""" + start_time = time.time() + while time.time() - start_time < timeout: + try: + with socket.create_connection(('localhost', port), timeout=1): + return True + except (socket.error, ConnectionRefusedError): + time.sleep(0.5) + return False + + +def main(): + parser = argparse.ArgumentParser(description='Run command with one or more servers') + parser.add_argument('--server', action='append', dest='servers', required=True, help='Server command (can be repeated)') + parser.add_argument('--port', action='append', dest='ports', type=int, required=True, help='Port for each server (must match --server count)') + parser.add_argument('--timeout', type=int, default=30, help='Timeout in seconds per server (default: 30)') + parser.add_argument('command', nargs=argparse.REMAINDER, help='Command to run after server(s) ready') + + args = parser.parse_args() + + # Remove the '--' separator if present + if args.command and args.command[0] == '--': + args.command = args.command[1:] + + if not args.command: + print("Error: No command specified to run") + sys.exit(1) + + # Parse server configurations + if len(args.servers) != len(args.ports): + print("Error: Number of --server and --port arguments must match") + sys.exit(1) + + servers = [] + for cmd, port in zip(args.servers, args.ports): + servers.append({'cmd': cmd, 'port': port}) + + server_processes = [] + + try: + # Start all servers + for i, server in enumerate(servers): + print(f"Starting server {i+1}/{len(servers)}: {server['cmd']}") + + # Use shell=True to support commands with cd and && + process = subprocess.Popen( + server['cmd'], + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE + ) + server_processes.append(process) + + # Wait for this server to be ready + print(f"Waiting for server on port {server['port']}...") + if not is_server_ready(server['port'], timeout=args.timeout): + raise RuntimeError(f"Server failed to start on port {server['port']} within {args.timeout}s") + + print(f"Server ready on port {server['port']}") + + print(f"\nAll {len(servers)} server(s) ready") + + # Run the command + print(f"Running: {' '.join(args.command)}\n") + result = subprocess.run(args.command) + sys.exit(result.returncode) + + finally: + # Clean up all servers + print(f"\nStopping {len(server_processes)} server(s)...") + for i, process in enumerate(server_processes): + try: + process.terminate() + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + print(f"Server {i+1} stopped") + print("All servers stopped") + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/playwright-skill/API_REFERENCE.md b/playwright-skill/API_REFERENCE.md deleted file mode 100644 index 9ee2975..0000000 --- a/playwright-skill/API_REFERENCE.md +++ /dev/null @@ -1,653 +0,0 @@ -# Playwright Skill - Complete API Reference - -This document contains the comprehensive Playwright API reference and advanced patterns. For quick-start execution patterns, see [SKILL.md](SKILL.md). - -## Table of Contents - -- [Installation & Setup](#installation--setup) -- [Core Patterns](#core-patterns) -- [Selectors & Locators](#selectors--locators) -- [Common Actions](#common-actions) -- [Waiting Strategies](#waiting-strategies) -- [Assertions](#assertions) -- [Page Object Model](#page-object-model-pom) -- [Network & API Testing](#network--api-testing) -- [Authentication & Session Management](#authentication--session-management) -- [Visual Testing](#visual-testing) -- [Mobile Testing](#mobile-testing) -- [Debugging](#debugging) -- [Performance Testing](#performance-testing) -- [Parallel Execution](#parallel-execution) -- [Data-Driven Testing](#data-driven-testing) -- [Accessibility Testing](#accessibility-testing) -- [CI/CD Integration](#cicd-integration) -- [Best Practices](#best-practices) -- [Common Patterns & Solutions](#common-patterns--solutions) -- [Troubleshooting](#troubleshooting) - -## Installation & Setup - -### Prerequisites - -Before using this skill, ensure Playwright is available: - -```bash -# Check if Playwright is installed -npm list playwright 2>/dev/null || echo "Playwright not installed" - -# Install (if needed) -cd ~/.claude/skills/playwright-skill -npm run setup -``` - -### Basic Configuration - -Create `playwright.config.ts`: - -```typescript -import { defineConfig, devices } from '@playwright/test'; - -export default defineConfig({ - testDir: './tests', - fullyParallel: true, - forbidOnly: !!process.env.CI, - retries: process.env.CI ? 2 : 0, - workers: process.env.CI ? 1 : undefined, - reporter: 'html', - use: { - baseURL: 'http://localhost:3000', - trace: 'on-first-retry', - screenshot: 'only-on-failure', - video: 'retain-on-failure', - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], - webServer: { - command: 'npm run start', - url: 'http://localhost:3000', - reuseExistingServer: !process.env.CI, - }, -}); -``` - -## Core Patterns - -### Basic Browser Automation - -```javascript -const { chromium } = require('playwright'); - -(async () => { - // Launch browser - const browser = await chromium.launch({ - headless: false, // Set to true for headless mode - slowMo: 50 // Slow down operations by 50ms - }); - - const context = await browser.newContext({ - viewport: { width: 1280, height: 720 }, - userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' - }); - - const page = await context.newPage(); - - // Navigate - await page.goto('https://example.com', { - waitUntil: 'networkidle' // Wait for network to be idle - }); - - // Your automation here - - await browser.close(); -})(); -``` - -### Test Structure - -```typescript -import { test, expect } from '@playwright/test'; - -test.describe('Feature Name', () => { - test.beforeEach(async ({ page }) => { - await page.goto('/'); - }); - - test('should do something', async ({ page }) => { - // Arrange - const button = page.locator('button[data-testid="submit"]'); - - // Act - await button.click(); - - // Assert - await expect(page).toHaveURL('/success'); - await expect(page.locator('.message')).toHaveText('Success!'); - }); -}); -``` - -## Selectors & Locators - -### Best Practices for Selectors - -```javascript -// PREFERRED: Data attributes (most stable) -await page.locator('[data-testid="submit-button"]').click(); -await page.locator('[data-cy="user-input"]').fill('text'); - -// GOOD: Role-based selectors (accessible) -await page.getByRole('button', { name: 'Submit' }).click(); -await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com'); -await page.getByRole('heading', { level: 1 }).click(); - -// GOOD: Text content (for unique text) -await page.getByText('Sign in').click(); -await page.getByText(/welcome back/i).click(); - -// OK: Semantic HTML -await page.locator('button[type="submit"]').click(); -await page.locator('input[name="email"]').fill('test@test.com'); - -// AVOID: Classes and IDs (can change frequently) -await page.locator('.btn-primary').click(); // Avoid -await page.locator('#submit').click(); // Avoid - -// LAST RESORT: Complex CSS/XPath -await page.locator('div.container > form > button').click(); // Fragile -``` - -### Advanced Locator Patterns - -```javascript -// Filter and chain locators -const row = page.locator('tr').filter({ hasText: 'John Doe' }); -await row.locator('button').click(); - -// Nth element -await page.locator('button').nth(2).click(); - -// Combining conditions -await page.locator('button').and(page.locator('[disabled]')).count(); - -// Parent/child navigation -const cell = page.locator('td').filter({ hasText: 'Active' }); -const row = cell.locator('..'); -await row.locator('button.edit').click(); -``` - -## Common Actions - -### Form Interactions - -```javascript -// Text input -await page.getByLabel('Email').fill('user@example.com'); -await page.getByPlaceholder('Enter your name').fill('John Doe'); - -// Clear and type -await page.locator('#username').clear(); -await page.locator('#username').type('newuser', { delay: 100 }); - -// Checkbox -await page.getByLabel('I agree').check(); -await page.getByLabel('Subscribe').uncheck(); - -// Radio button -await page.getByLabel('Option 2').check(); - -// Select dropdown -await page.selectOption('select#country', 'usa'); -await page.selectOption('select#country', { label: 'United States' }); -await page.selectOption('select#country', { index: 2 }); - -// Multi-select -await page.selectOption('select#colors', ['red', 'blue', 'green']); - -// File upload -await page.setInputFiles('input[type="file"]', 'path/to/file.pdf'); -await page.setInputFiles('input[type="file"]', [ - 'file1.pdf', - 'file2.pdf' -]); -``` - -### Mouse Actions - -```javascript -// Click variations -await page.click('button'); // Left click -await page.click('button', { button: 'right' }); // Right click -await page.dblclick('button'); // Double click -await page.click('button', { position: { x: 10, y: 10 } }); // Click at position - -// Hover -await page.hover('.menu-item'); - -// Drag and drop -await page.dragAndDrop('#source', '#target'); - -// Manual drag -await page.locator('#source').hover(); -await page.mouse.down(); -await page.locator('#target').hover(); -await page.mouse.up(); -``` - -### Keyboard Actions - -```javascript -// Type with delay -await page.keyboard.type('Hello World', { delay: 100 }); - -// Key combinations -await page.keyboard.press('Control+A'); -await page.keyboard.press('Control+C'); -await page.keyboard.press('Control+V'); - -// Special keys -await page.keyboard.press('Enter'); -await page.keyboard.press('Tab'); -await page.keyboard.press('Escape'); -await page.keyboard.press('ArrowDown'); -``` - -## Waiting Strategies - -### Smart Waiting - -```javascript -// Wait for element states -await page.locator('button').waitFor({ state: 'visible' }); -await page.locator('.spinner').waitFor({ state: 'hidden' }); -await page.locator('button').waitFor({ state: 'attached' }); -await page.locator('button').waitFor({ state: 'detached' }); - -// Wait for specific conditions -await page.waitForURL('**/success'); -await page.waitForURL(url => url.pathname === '/dashboard'); - -// Wait for network -await page.waitForLoadState('networkidle'); -await page.waitForLoadState('domcontentloaded'); - -// Wait for function -await page.waitForFunction(() => document.querySelector('.loaded')); -await page.waitForFunction( - text => document.body.innerText.includes(text), - 'Content loaded' -); - -// Wait for response -const responsePromise = page.waitForResponse('**/api/users'); -await page.click('button#load-users'); -const response = await responsePromise; - -// Wait for request -await page.waitForRequest(request => - request.url().includes('/api/') && request.method() === 'POST' -); - -// Custom timeout -await page.locator('.slow-element').waitFor({ - state: 'visible', - timeout: 10000 // 10 seconds -}); -``` - -## Assertions - -### Common Assertions - -```javascript -import { expect } from '@playwright/test'; - -// Page assertions -await expect(page).toHaveTitle('My App'); -await expect(page).toHaveURL('https://example.com/dashboard'); -await expect(page).toHaveURL(/.*dashboard/); - -// Element visibility -await expect(page.locator('.message')).toBeVisible(); -await expect(page.locator('.spinner')).toBeHidden(); -await expect(page.locator('button')).toBeEnabled(); -await expect(page.locator('input')).toBeDisabled(); - -// Text content -await expect(page.locator('h1')).toHaveText('Welcome'); -await expect(page.locator('.message')).toContainText('success'); -await expect(page.locator('.items')).toHaveText(['Item 1', 'Item 2']); - -// Input values -await expect(page.locator('input')).toHaveValue('test@example.com'); -await expect(page.locator('input')).toBeEmpty(); - -// Attributes -await expect(page.locator('button')).toHaveAttribute('type', 'submit'); -await expect(page.locator('img')).toHaveAttribute('src', /.*\.png/); - -// CSS properties -await expect(page.locator('.error')).toHaveCSS('color', 'rgb(255, 0, 0)'); - -// Count -await expect(page.locator('.item')).toHaveCount(5); - -// Checkbox/Radio state -await expect(page.locator('input[type="checkbox"]')).toBeChecked(); -``` - -## Page Object Model (POM) - -### Basic Page Object - -```javascript -// pages/LoginPage.js -class LoginPage { - constructor(page) { - this.page = page; - this.usernameInput = page.locator('input[name="username"]'); - this.passwordInput = page.locator('input[name="password"]'); - this.submitButton = page.locator('button[type="submit"]'); - this.errorMessage = page.locator('.error-message'); - } - - async navigate() { - await this.page.goto('/login'); - } - - async login(username, password) { - await this.usernameInput.fill(username); - await this.passwordInput.fill(password); - await this.submitButton.click(); - } - - async getErrorMessage() { - return await this.errorMessage.textContent(); - } -} - -// Usage in test -test('login with valid credentials', async ({ page }) => { - const loginPage = new LoginPage(page); - await loginPage.navigate(); - await loginPage.login('user@example.com', 'password123'); - await expect(page).toHaveURL('/dashboard'); -}); -``` - -## Network & API Testing - -### Intercepting Requests - -```javascript -// Mock API responses -await page.route('**/api/users', route => { - route.fulfill({ - status: 200, - contentType: 'application/json', - body: JSON.stringify([ - { id: 1, name: 'John' }, - { id: 2, name: 'Jane' } - ]) - }); -}); - -// Modify requests -await page.route('**/api/**', route => { - const headers = { - ...route.request().headers(), - 'X-Custom-Header': 'value' - }; - route.continue({ headers }); -}); - -// Block resources -await page.route('**/*.{png,jpg,jpeg,gif}', route => route.abort()); -``` - -### Custom Headers via Environment Variables - -The skill supports automatic header injection via environment variables: - -```bash -# Single header (simple) -PW_HEADER_NAME=X-Automated-By PW_HEADER_VALUE=playwright-skill - -# Multiple headers (JSON) -PW_EXTRA_HEADERS='{"X-Automated-By":"playwright-skill","X-Request-ID":"123"}' -``` - -These headers are automatically applied to all requests when using: -- `helpers.createContext(browser)` - headers merged automatically -- `getContextOptionsWithHeaders(options)` - utility injected by run.js wrapper - -**Precedence (highest to lowest):** -1. Headers passed directly in `options.extraHTTPHeaders` -2. Environment variable headers -3. Playwright defaults - -**Use case:** Identify automated traffic so your backend can return LLM-optimized responses (e.g., plain text errors instead of styled HTML). - -## Visual Testing - -### Screenshots - -```javascript -// Full page screenshot -await page.screenshot({ - path: 'screenshot.png', - fullPage: true -}); - -// Element screenshot -await page.locator('.chart').screenshot({ - path: 'chart.png' -}); - -// Visual comparison -await expect(page).toHaveScreenshot('homepage.png'); -``` - -## Mobile Testing - -```javascript -// Device emulation -const { devices } = require('playwright'); -const iPhone = devices['iPhone 12']; - -const context = await browser.newContext({ - ...iPhone, - locale: 'en-US', - permissions: ['geolocation'], - geolocation: { latitude: 37.7749, longitude: -122.4194 } -}); -``` - -## Debugging - -### Debug Mode - -```bash -# Run with inspector -npx playwright test --debug - -# Headed mode -npx playwright test --headed - -# Slow motion -npx playwright test --headed --slowmo=1000 -``` - -### In-Code Debugging - -```javascript -// Pause execution -await page.pause(); - -// Console logs -page.on('console', msg => console.log('Browser log:', msg.text())); -page.on('pageerror', error => console.log('Page error:', error)); -``` - -## Performance Testing - -```javascript -// Measure page load time -const startTime = Date.now(); -await page.goto('https://example.com'); -const loadTime = Date.now() - startTime; -console.log(`Page loaded in ${loadTime}ms`); -``` - -## Parallel Execution - -```javascript -// Run tests in parallel -test.describe.parallel('Parallel suite', () => { - test('test 1', async ({ page }) => { - // Runs in parallel with test 2 - }); - - test('test 2', async ({ page }) => { - // Runs in parallel with test 1 - }); -}); -``` - -## Data-Driven Testing - -```javascript -// Parameterized tests -const testData = [ - { username: 'user1', password: 'pass1', expected: 'Welcome user1' }, - { username: 'user2', password: 'pass2', expected: 'Welcome user2' }, -]; - -testData.forEach(({ username, password, expected }) => { - test(`login with ${username}`, async ({ page }) => { - await page.goto('/login'); - await page.fill('#username', username); - await page.fill('#password', password); - await page.click('button[type="submit"]'); - await expect(page.locator('.message')).toHaveText(expected); - }); -}); -``` - -## Accessibility Testing - -```javascript -import { injectAxe, checkA11y } from 'axe-playwright'; - -test('accessibility check', async ({ page }) => { - await page.goto('/'); - await injectAxe(page); - await checkA11y(page); -}); -``` - -## CI/CD Integration - -### GitHub Actions - -```yaml -name: Playwright Tests -on: - push: - branches: [main, master] -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - - name: Install dependencies - run: npm ci - - name: Install Playwright Browsers - run: npx playwright install --with-deps - - name: Run tests - run: npx playwright test -``` - -## Best Practices - -1. **Test Organization** - Use descriptive test names, group related tests -2. **Selector Strategy** - Prefer data-testid attributes, use role-based selectors -3. **Waiting** - Use Playwright's auto-waiting, avoid hard-coded delays -4. **Error Handling** - Add proper error messages, take screenshots on failure -5. **Performance** - Run tests in parallel, reuse authentication state - -## Common Patterns & Solutions - -### Handling Popups - -```javascript -const [popup] = await Promise.all([ - page.waitForEvent('popup'), - page.click('button.open-popup') -]); -await popup.waitForLoadState(); -``` - -### File Downloads - -```javascript -const [download] = await Promise.all([ - page.waitForEvent('download'), - page.click('button.download') -]); -await download.saveAs(`./downloads/${download.suggestedFilename()}`); -``` - -### iFrames - -```javascript -const frame = page.frameLocator('#my-iframe'); -await frame.locator('button').click(); -``` - -### Infinite Scroll - -```javascript -async function scrollToBottom(page) { - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await page.waitForTimeout(500); -} -``` - -## Troubleshooting - -### Common Issues - -1. **Element not found** - Check if element is in iframe, verify visibility -2. **Timeout errors** - Increase timeout, check network conditions -3. **Flaky tests** - Use proper waiting strategies, mock external dependencies -4. **Authentication issues** - Verify auth state is properly saved - -## Quick Reference Commands - -```bash -# Run tests -npx playwright test - -# Run in headed mode -npx playwright test --headed - -# Debug tests -npx playwright test --debug - -# Generate code -npx playwright codegen https://example.com - -# Show report -npx playwright show-report -``` - -## Additional Resources - -- [Playwright Documentation](https://playwright.dev/docs/intro) -- [API Reference](https://playwright.dev/docs/api/class-playwright) -- [Best Practices](https://playwright.dev/docs/best-practices) diff --git a/playwright-skill/LICENSE b/playwright-skill/LICENSE deleted file mode 100644 index 5d40ba0..0000000 --- a/playwright-skill/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 lackeyjb - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/playwright-skill/SKILL.md b/playwright-skill/SKILL.md deleted file mode 100644 index 72db3f9..0000000 --- a/playwright-skill/SKILL.md +++ /dev/null @@ -1,460 +0,0 @@ ---- -name: playwright-skill -description: Complete browser automation with Playwright. Auto-detects dev servers, writes clean test scripts to /tmp. Test pages, fill forms, take screenshots, check responsive design, validate UX, test login flows, check links, automate any browser task. Use when user wants to test websites, automate browser interactions, validate web functionality, or perform any browser-based testing. ---- - -**IMPORTANT - Path Resolution:** -This skill can be installed in different locations (plugin system, manual installation, global, or project-specific). Before executing any commands, determine the skill directory based on where you loaded this SKILL.md file, and use that path in all commands below. Replace `$SKILL_DIR` with the actual discovered path. - -Common installation paths: - -- Plugin system: `~/.claude/plugins/marketplaces/playwright-skill/skills/playwright-skill` -- Manual global: `~/.claude/skills/playwright-skill` -- Project-specific: `/.claude/skills/playwright-skill` - -# Playwright Browser Automation - -General-purpose browser automation skill. I'll write custom Playwright code for any automation task you request and execute it via the universal executor. - -**CRITICAL WORKFLOW - Follow these steps in order:** - -1. **Auto-detect dev servers** - For localhost testing, ALWAYS run server detection FIRST: - - ```bash - cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(servers => console.log(JSON.stringify(servers)))" - ``` - - - If **1 server found**: Use it automatically, inform user - - If **multiple servers found**: Ask user which one to test - - If **no servers found**: Ask for URL or offer to help start dev server - -2. **Write scripts to /tmp** - NEVER write test files to skill directory; always use `/tmp/playwright-test-*.js` - -3. **Use visible browser by default** - Always use `headless: false` unless user specifically requests headless mode - -4. **Parameterize URLs** - Always make URLs configurable via environment variable or constant at top of script - -## How It Works - -1. You describe what you want to test/automate -2. I auto-detect running dev servers (or ask for URL if testing external site) -3. I write custom Playwright code in `/tmp/playwright-test-*.js` (won't clutter your project) -4. I execute it via: `cd $SKILL_DIR && node run.js /tmp/playwright-test-*.js` -5. Results displayed in real-time, browser window visible for debugging -6. Test files auto-cleaned from /tmp by your OS - -## Setup (First Time) - -```bash -cd $SKILL_DIR -npm run setup -``` - -This installs Playwright and Chromium browser. Only needed once. - -## Execution Pattern - -**Step 1: Detect dev servers (for localhost testing)** - -```bash -cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(s => console.log(JSON.stringify(s)))" -``` - -**Step 2: Write test script to /tmp with URL parameter** - -```javascript -// /tmp/playwright-test-page.js -const { chromium } = require('playwright'); - -// Parameterized URL (detected or user-provided) -const TARGET_URL = 'http://localhost:3001'; // <-- Auto-detected or from user - -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - - await page.goto(TARGET_URL); - console.log('Page loaded:', await page.title()); - - await page.screenshot({ path: '/tmp/screenshot.png', fullPage: true }); - console.log('📸 Screenshot saved to /tmp/screenshot.png'); - - await browser.close(); -})(); -``` - -**Step 3: Execute from skill directory** - -```bash -cd $SKILL_DIR && node run.js /tmp/playwright-test-page.js -``` - -## Common Patterns - -### Test a Page (Multiple Viewports) - -```javascript -// /tmp/playwright-test-responsive.js -const { chromium } = require('playwright'); - -const TARGET_URL = 'http://localhost:3001'; // Auto-detected - -(async () => { - const browser = await chromium.launch({ headless: false, slowMo: 100 }); - const page = await browser.newPage(); - - // Desktop test - await page.setViewportSize({ width: 1920, height: 1080 }); - await page.goto(TARGET_URL); - console.log('Desktop - Title:', await page.title()); - await page.screenshot({ path: '/tmp/desktop.png', fullPage: true }); - - // Mobile test - await page.setViewportSize({ width: 375, height: 667 }); - await page.screenshot({ path: '/tmp/mobile.png', fullPage: true }); - - await browser.close(); -})(); -``` - -### Test Login Flow - -```javascript -// /tmp/playwright-test-login.js -const { chromium } = require('playwright'); - -const TARGET_URL = 'http://localhost:3001'; // Auto-detected - -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - - await page.goto(`${TARGET_URL}/login`); - - await page.fill('input[name="email"]', 'test@example.com'); - await page.fill('input[name="password"]', 'password123'); - await page.click('button[type="submit"]'); - - // Wait for redirect - await page.waitForURL('**/dashboard'); - console.log('✅ Login successful, redirected to dashboard'); - - await browser.close(); -})(); -``` - -### Fill and Submit Form - -```javascript -// /tmp/playwright-test-form.js -const { chromium } = require('playwright'); - -const TARGET_URL = 'http://localhost:3001'; // Auto-detected - -(async () => { - const browser = await chromium.launch({ headless: false, slowMo: 50 }); - const page = await browser.newPage(); - - await page.goto(`${TARGET_URL}/contact`); - - await page.fill('input[name="name"]', 'John Doe'); - await page.fill('input[name="email"]', 'john@example.com'); - await page.fill('textarea[name="message"]', 'Test message'); - await page.click('button[type="submit"]'); - - // Verify submission - await page.waitForSelector('.success-message'); - console.log('✅ Form submitted successfully'); - - await browser.close(); -})(); -``` - -### Check for Broken Links - -```javascript -const { chromium } = require('playwright'); - -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - - await page.goto('http://localhost:3000'); - - const links = await page.locator('a[href^="http"]').all(); - const results = { working: 0, broken: [] }; - - for (const link of links) { - const href = await link.getAttribute('href'); - try { - const response = await page.request.head(href); - if (response.ok()) { - results.working++; - } else { - results.broken.push({ url: href, status: response.status() }); - } - } catch (e) { - results.broken.push({ url: href, error: e.message }); - } - } - - console.log(`✅ Working links: ${results.working}`); - console.log(`❌ Broken links:`, results.broken); - - await browser.close(); -})(); -``` - -### Take Screenshot with Error Handling - -```javascript -const { chromium } = require('playwright'); - -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - - try { - await page.goto('http://localhost:3000', { - waitUntil: 'networkidle', - timeout: 10000, - }); - - await page.screenshot({ - path: '/tmp/screenshot.png', - fullPage: true, - }); - - console.log('📸 Screenshot saved to /tmp/screenshot.png'); - } catch (error) { - console.error('❌ Error:', error.message); - } finally { - await browser.close(); - } -})(); -``` - -### Test Responsive Design - -```javascript -// /tmp/playwright-test-responsive-full.js -const { chromium } = require('playwright'); - -const TARGET_URL = 'http://localhost:3001'; // Auto-detected - -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - - const viewports = [ - { name: 'Desktop', width: 1920, height: 1080 }, - { name: 'Tablet', width: 768, height: 1024 }, - { name: 'Mobile', width: 375, height: 667 }, - ]; - - for (const viewport of viewports) { - console.log( - `Testing ${viewport.name} (${viewport.width}x${viewport.height})`, - ); - - await page.setViewportSize({ - width: viewport.width, - height: viewport.height, - }); - - await page.goto(TARGET_URL); - await page.waitForTimeout(1000); - - await page.screenshot({ - path: `/tmp/${viewport.name.toLowerCase()}.png`, - fullPage: true, - }); - } - - console.log('✅ All viewports tested'); - await browser.close(); -})(); -``` - -## Inline Execution (Simple Tasks) - -For quick one-off tasks, you can execute code inline without creating files: - -```bash -# Take a quick screenshot -cd $SKILL_DIR && node run.js " -const browser = await chromium.launch({ headless: false }); -const page = await browser.newPage(); -await page.goto('http://localhost:3001'); -await page.screenshot({ path: '/tmp/quick-screenshot.png', fullPage: true }); -console.log('Screenshot saved'); -await browser.close(); -" -``` - -**When to use inline vs files:** - -- **Inline**: Quick one-off tasks (screenshot, check if element exists, get page title) -- **Files**: Complex tests, responsive design checks, anything user might want to re-run - -## Available Helpers - -Optional utility functions in `lib/helpers.js`: - -```javascript -const helpers = require('./lib/helpers'); - -// Detect running dev servers (CRITICAL - use this first!) -const servers = await helpers.detectDevServers(); -console.log('Found servers:', servers); - -// Safe click with retry -await helpers.safeClick(page, 'button.submit', { retries: 3 }); - -// Safe type with clear -await helpers.safeType(page, '#username', 'testuser'); - -// Take timestamped screenshot -await helpers.takeScreenshot(page, 'test-result'); - -// Handle cookie banners -await helpers.handleCookieBanner(page); - -// Extract table data -const data = await helpers.extractTableData(page, 'table.results'); -``` - -See `lib/helpers.js` for full list. - -## Custom HTTP Headers - -Configure custom headers for all HTTP requests via environment variables. Useful for: - -- Identifying automated traffic to your backend -- Getting LLM-optimized responses (e.g., plain text errors instead of styled HTML) -- Adding authentication tokens globally - -### Configuration - -**Single header (common case):** - -```bash -PW_HEADER_NAME=X-Automated-By PW_HEADER_VALUE=playwright-skill \ - cd $SKILL_DIR && node run.js /tmp/my-script.js -``` - -**Multiple headers (JSON format):** - -```bash -PW_EXTRA_HEADERS='{"X-Automated-By":"playwright-skill","X-Debug":"true"}' \ - cd $SKILL_DIR && node run.js /tmp/my-script.js -``` - -### How It Works - -Headers are automatically applied when using `helpers.createContext()`: - -```javascript -const context = await helpers.createContext(browser); -const page = await context.newPage(); -// All requests from this page include your custom headers -``` - -For scripts using raw Playwright API, use the injected `getContextOptionsWithHeaders()`: - -```javascript -const context = await browser.newContext( - getContextOptionsWithHeaders({ viewport: { width: 1920, height: 1080 } }), -); -``` - -## Advanced Usage - -For comprehensive Playwright API documentation, see [API_REFERENCE.md](API_REFERENCE.md): - -- Selectors & Locators best practices -- Network interception & API mocking -- Authentication & session management -- Visual regression testing -- Mobile device emulation -- Performance testing -- Debugging techniques -- CI/CD integration - -## Tips - -- **CRITICAL: Detect servers FIRST** - Always run `detectDevServers()` before writing test code for localhost testing -- **Custom headers** - Use `PW_HEADER_NAME`/`PW_HEADER_VALUE` env vars to identify automated traffic to your backend -- **Use /tmp for test files** - Write to `/tmp/playwright-test-*.js`, never to skill directory or user's project -- **Parameterize URLs** - Put detected/provided URL in a `TARGET_URL` constant at the top of every script -- **DEFAULT: Visible browser** - Always use `headless: false` unless user explicitly asks for headless mode -- **Headless mode** - Only use `headless: true` when user specifically requests "headless" or "background" execution -- **Slow down:** Use `slowMo: 100` to make actions visible and easier to follow -- **Wait strategies:** Use `waitForURL`, `waitForSelector`, `waitForLoadState` instead of fixed timeouts -- **Error handling:** Always use try-catch for robust automation -- **Console output:** Use `console.log()` to track progress and show what's happening - -## Troubleshooting - -**Playwright not installed:** - -```bash -cd $SKILL_DIR && npm run setup -``` - -**Module not found:** -Ensure running from skill directory via `run.js` wrapper - -**Browser doesn't open:** -Check `headless: false` and ensure display available - -**Element not found:** -Add wait: `await page.waitForSelector('.element', { timeout: 10000 })` - -## Example Usage - -``` -User: "Test if the marketing page looks good" - -Claude: I'll test the marketing page across multiple viewports. Let me first detect running servers... -[Runs: detectDevServers()] -[Output: Found server on port 3001] -I found your dev server running on http://localhost:3001 - -[Writes custom automation script to /tmp/playwright-test-marketing.js with URL parameterized] -[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-marketing.js] -[Shows results with screenshots from /tmp/] -``` - -``` -User: "Check if login redirects correctly" - -Claude: I'll test the login flow. First, let me check for running servers... -[Runs: detectDevServers()] -[Output: Found servers on ports 3000 and 3001] -I found 2 dev servers. Which one should I test? -- http://localhost:3000 -- http://localhost:3001 - -User: "Use 3001" - -[Writes login automation to /tmp/playwright-test-login.js] -[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-login.js] -[Reports: ✅ Login successful, redirected to /dashboard] -``` - -## Notes - -- Each automation is custom-written for your specific request -- Not limited to pre-built scripts - any browser task possible -- Auto-detects running dev servers to eliminate hardcoded URLs -- Test scripts written to `/tmp` for automatic cleanup (no clutter) -- Code executes reliably with proper module resolution via `run.js` -- Progressive disclosure - API_REFERENCE.md loaded only when advanced features needed - ---- - -## Attribution - -Forked from [lackeyjb/playwright-skill](https://github.com/lackeyjb/playwright-skill) — MIT licensed. -See `LICENSE` in this directory for the original copyright and terms. diff --git a/playwright-skill/lib/helpers.js b/playwright-skill/lib/helpers.js deleted file mode 100644 index 0920d68..0000000 --- a/playwright-skill/lib/helpers.js +++ /dev/null @@ -1,441 +0,0 @@ -// playwright-helpers.js -// Reusable utility functions for Playwright automation - -const { chromium, firefox, webkit } = require('playwright'); - -/** - * Parse extra HTTP headers from environment variables. - * Supports two formats: - * - PW_HEADER_NAME + PW_HEADER_VALUE: Single header (simple, common case) - * - PW_EXTRA_HEADERS: JSON object for multiple headers (advanced) - * Single header format takes precedence if both are set. - * @returns {Object|null} Headers object or null if none configured - */ -function getExtraHeadersFromEnv() { - const headerName = process.env.PW_HEADER_NAME; - const headerValue = process.env.PW_HEADER_VALUE; - - if (headerName && headerValue) { - return { [headerName]: headerValue }; - } - - const headersJson = process.env.PW_EXTRA_HEADERS; - if (headersJson) { - try { - const parsed = JSON.parse(headersJson); - if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) { - return parsed; - } - console.warn('PW_EXTRA_HEADERS must be a JSON object, ignoring...'); - } catch (e) { - console.warn('Failed to parse PW_EXTRA_HEADERS as JSON:', e.message); - } - } - - return null; -} - -/** - * Launch browser with standard configuration - * @param {string} browserType - 'chromium', 'firefox', or 'webkit' - * @param {Object} options - Additional launch options - */ -async function launchBrowser(browserType = 'chromium', options = {}) { - const defaultOptions = { - headless: process.env.HEADLESS !== 'false', - slowMo: process.env.SLOW_MO ? parseInt(process.env.SLOW_MO) : 0, - args: ['--no-sandbox', '--disable-setuid-sandbox'] - }; - - const browsers = { chromium, firefox, webkit }; - const browser = browsers[browserType]; - - if (!browser) { - throw new Error(`Invalid browser type: ${browserType}`); - } - - return await browser.launch({ ...defaultOptions, ...options }); -} - -/** - * Create a new page with viewport and user agent - * @param {Object} context - Browser context - * @param {Object} options - Page options - */ -async function createPage(context, options = {}) { - const page = await context.newPage(); - - if (options.viewport) { - await page.setViewportSize(options.viewport); - } - - if (options.userAgent) { - await page.setExtraHTTPHeaders({ - 'User-Agent': options.userAgent - }); - } - - // Set default timeout - page.setDefaultTimeout(options.timeout || 30000); - - return page; -} - -/** - * Smart wait for page to be ready - * @param {Object} page - Playwright page - * @param {Object} options - Wait options - */ -async function waitForPageReady(page, options = {}) { - const waitOptions = { - waitUntil: options.waitUntil || 'networkidle', - timeout: options.timeout || 30000 - }; - - try { - await page.waitForLoadState(waitOptions.waitUntil, { - timeout: waitOptions.timeout - }); - } catch (e) { - console.warn('Page load timeout, continuing...'); - } - - // Additional wait for dynamic content if selector provided - if (options.waitForSelector) { - await page.waitForSelector(options.waitForSelector, { - timeout: options.timeout - }); - } -} - -/** - * Safe click with retry logic - * @param {Object} page - Playwright page - * @param {string} selector - Element selector - * @param {Object} options - Click options - */ -async function safeClick(page, selector, options = {}) { - const maxRetries = options.retries || 3; - const retryDelay = options.retryDelay || 1000; - - for (let i = 0; i < maxRetries; i++) { - try { - await page.waitForSelector(selector, { - state: 'visible', - timeout: options.timeout || 5000 - }); - await page.click(selector, { - force: options.force || false, - timeout: options.timeout || 5000 - }); - return true; - } catch (e) { - if (i === maxRetries - 1) { - console.error(`Failed to click ${selector} after ${maxRetries} attempts`); - throw e; - } - console.log(`Retry ${i + 1}/${maxRetries} for clicking ${selector}`); - await page.waitForTimeout(retryDelay); - } - } -} - -/** - * Safe text input with clear before type - * @param {Object} page - Playwright page - * @param {string} selector - Input selector - * @param {string} text - Text to type - * @param {Object} options - Type options - */ -async function safeType(page, selector, text, options = {}) { - await page.waitForSelector(selector, { - state: 'visible', - timeout: options.timeout || 10000 - }); - - if (options.clear !== false) { - await page.fill(selector, ''); - } - - if (options.slow) { - await page.type(selector, text, { delay: options.delay || 100 }); - } else { - await page.fill(selector, text); - } -} - -/** - * Extract text from multiple elements - * @param {Object} page - Playwright page - * @param {string} selector - Elements selector - */ -async function extractTexts(page, selector) { - await page.waitForSelector(selector, { timeout: 10000 }); - return await page.$$eval(selector, elements => - elements.map(el => el.textContent?.trim()).filter(Boolean) - ); -} - -/** - * Take screenshot with timestamp - * @param {Object} page - Playwright page - * @param {string} name - Screenshot name - * @param {Object} options - Screenshot options - */ -async function takeScreenshot(page, name, options = {}) { - const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); - const filename = `${name}-${timestamp}.png`; - - await page.screenshot({ - path: filename, - fullPage: options.fullPage !== false, - ...options - }); - - console.log(`Screenshot saved: ${filename}`); - return filename; -} - -/** - * Handle authentication - * @param {Object} page - Playwright page - * @param {Object} credentials - Username and password - * @param {Object} selectors - Login form selectors - */ -async function authenticate(page, credentials, selectors = {}) { - const defaultSelectors = { - username: 'input[name="username"], input[name="email"], #username, #email', - password: 'input[name="password"], #password', - submit: 'button[type="submit"], input[type="submit"], button:has-text("Login"), button:has-text("Sign in")' - }; - - const finalSelectors = { ...defaultSelectors, ...selectors }; - - await safeType(page, finalSelectors.username, credentials.username); - await safeType(page, finalSelectors.password, credentials.password); - await safeClick(page, finalSelectors.submit); - - // Wait for navigation or success indicator - await Promise.race([ - page.waitForNavigation({ waitUntil: 'networkidle' }), - page.waitForSelector(selectors.successIndicator || '.dashboard, .user-menu, .logout', { timeout: 10000 }) - ]).catch(() => { - console.log('Login might have completed without navigation'); - }); -} - -/** - * Scroll page - * @param {Object} page - Playwright page - * @param {string} direction - 'down', 'up', 'top', 'bottom' - * @param {number} distance - Pixels to scroll (for up/down) - */ -async function scrollPage(page, direction = 'down', distance = 500) { - switch (direction) { - case 'down': - await page.evaluate(d => window.scrollBy(0, d), distance); - break; - case 'up': - await page.evaluate(d => window.scrollBy(0, -d), distance); - break; - case 'top': - await page.evaluate(() => window.scrollTo(0, 0)); - break; - case 'bottom': - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - break; - } - await page.waitForTimeout(500); // Wait for scroll animation -} - -/** - * Extract table data - * @param {Object} page - Playwright page - * @param {string} tableSelector - Table selector - */ -async function extractTableData(page, tableSelector) { - await page.waitForSelector(tableSelector); - - return await page.evaluate((selector) => { - const table = document.querySelector(selector); - if (!table) return null; - - const headers = Array.from(table.querySelectorAll('thead th')).map(th => - th.textContent?.trim() - ); - - const rows = Array.from(table.querySelectorAll('tbody tr')).map(tr => { - const cells = Array.from(tr.querySelectorAll('td')); - if (headers.length > 0) { - return cells.reduce((obj, cell, index) => { - obj[headers[index] || `column_${index}`] = cell.textContent?.trim(); - return obj; - }, {}); - } else { - return cells.map(cell => cell.textContent?.trim()); - } - }); - - return { headers, rows }; - }, tableSelector); -} - -/** - * Wait for and dismiss cookie banners - * @param {Object} page - Playwright page - * @param {number} timeout - Max time to wait - */ -async function handleCookieBanner(page, timeout = 3000) { - const commonSelectors = [ - 'button:has-text("Accept")', - 'button:has-text("Accept all")', - 'button:has-text("OK")', - 'button:has-text("Got it")', - 'button:has-text("I agree")', - '.cookie-accept', - '#cookie-accept', - '[data-testid="cookie-accept"]' - ]; - - for (const selector of commonSelectors) { - try { - const element = await page.waitForSelector(selector, { - timeout: timeout / commonSelectors.length, - state: 'visible' - }); - if (element) { - await element.click(); - console.log('Cookie banner dismissed'); - return true; - } - } catch (e) { - // Continue to next selector - } - } - - return false; -} - -/** - * Retry a function with exponential backoff - * @param {Function} fn - Function to retry - * @param {number} maxRetries - Maximum retry attempts - * @param {number} initialDelay - Initial delay in ms - */ -async function retryWithBackoff(fn, maxRetries = 3, initialDelay = 1000) { - let lastError; - - for (let i = 0; i < maxRetries; i++) { - try { - return await fn(); - } catch (error) { - lastError = error; - const delay = initialDelay * Math.pow(2, i); - console.log(`Attempt ${i + 1} failed, retrying in ${delay}ms...`); - await new Promise(resolve => setTimeout(resolve, delay)); - } - } - - throw lastError; -} - -/** - * Create browser context with common settings - * @param {Object} browser - Browser instance - * @param {Object} options - Context options - */ -async function createContext(browser, options = {}) { - const envHeaders = getExtraHeadersFromEnv(); - - // Merge environment headers with any passed in options - const mergedHeaders = { - ...envHeaders, - ...options.extraHTTPHeaders - }; - - const defaultOptions = { - viewport: { width: 1280, height: 720 }, - userAgent: options.mobile - ? 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1' - : undefined, - permissions: options.permissions || [], - geolocation: options.geolocation, - locale: options.locale || 'en-US', - timezoneId: options.timezoneId || 'America/New_York', - // Only include extraHTTPHeaders if we have any - ...(Object.keys(mergedHeaders).length > 0 && { extraHTTPHeaders: mergedHeaders }) - }; - - return await browser.newContext({ ...defaultOptions, ...options }); -} - -/** - * Detect running dev servers on common ports - * @param {Array} customPorts - Additional ports to check - * @returns {Promise} Array of detected server URLs - */ -async function detectDevServers(customPorts = []) { - const http = require('http'); - - // Common dev server ports - const commonPorts = [3000, 3001, 3002, 5173, 8080, 8000, 4200, 5000, 9000, 1234]; - const allPorts = [...new Set([...commonPorts, ...customPorts])]; - - const detectedServers = []; - - console.log('🔍 Checking for running dev servers...'); - - for (const port of allPorts) { - try { - await new Promise((resolve, reject) => { - const req = http.request({ - hostname: 'localhost', - port: port, - path: '/', - method: 'HEAD', - timeout: 500 - }, (res) => { - if (res.statusCode < 500) { - detectedServers.push(`http://localhost:${port}`); - console.log(` ✅ Found server on port ${port}`); - } - resolve(); - }); - - req.on('error', () => resolve()); - req.on('timeout', () => { - req.destroy(); - resolve(); - }); - - req.end(); - }); - } catch (e) { - // Port not available, continue - } - } - - if (detectedServers.length === 0) { - console.log(' ❌ No dev servers detected'); - } - - return detectedServers; -} - -module.exports = { - launchBrowser, - createPage, - waitForPageReady, - safeClick, - safeType, - extractTexts, - takeScreenshot, - authenticate, - scrollPage, - extractTableData, - handleCookieBanner, - retryWithBackoff, - createContext, - detectDevServers, - getExtraHeadersFromEnv -}; diff --git a/playwright-skill/package.json b/playwright-skill/package.json deleted file mode 100644 index ada6c8b..0000000 --- a/playwright-skill/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "playwright-skill", - "version": "4.1.0", - "description": "General-purpose browser automation with Playwright for Claude Code with auto-detection and smart test management", - "author": "lackeyjb", - "main": "run.js", - "scripts": { - "setup": "npm install && npx playwright install chromium", - "install-all-browsers": "npx playwright install chromium firefox webkit" - }, - "keywords": [ - "playwright", - "automation", - "browser-testing", - "web-automation", - "claude-skill", - "general-purpose" - ], - "dependencies": { - "playwright": "^1.57.0" - }, - "engines": { - "node": ">=14.0.0" - }, - "license": "MIT" -} diff --git a/playwright-skill/run.js b/playwright-skill/run.js deleted file mode 100755 index 10f2616..0000000 --- a/playwright-skill/run.js +++ /dev/null @@ -1,228 +0,0 @@ -#!/usr/bin/env node -/** - * Universal Playwright Executor for Claude Code - * - * Executes Playwright automation code from: - * - File path: node run.js script.js - * - Inline code: node run.js 'await page.goto("...")' - * - Stdin: cat script.js | node run.js - * - * Ensures proper module resolution by running from skill directory. - */ - -const fs = require('fs'); -const path = require('path'); -const { execSync } = require('child_process'); - -// Change to skill directory for proper module resolution -process.chdir(__dirname); - -/** - * Check if Playwright is installed - */ -function checkPlaywrightInstalled() { - try { - require.resolve('playwright'); - return true; - } catch (e) { - return false; - } -} - -/** - * Install Playwright if missing - */ -function installPlaywright() { - console.log('📦 Playwright not found. Installing...'); - try { - execSync('npm install', { stdio: 'inherit', cwd: __dirname }); - execSync('npx playwright install chromium', { stdio: 'inherit', cwd: __dirname }); - console.log('✅ Playwright installed successfully'); - return true; - } catch (e) { - console.error('❌ Failed to install Playwright:', e.message); - console.error('Please run manually: cd', __dirname, '&& npm run setup'); - return false; - } -} - -/** - * Get code to execute from various sources - */ -function getCodeToExecute() { - const args = process.argv.slice(2); - - // Case 1: File path provided - if (args.length > 0 && fs.existsSync(args[0])) { - const filePath = path.resolve(args[0]); - console.log(`📄 Executing file: ${filePath}`); - return fs.readFileSync(filePath, 'utf8'); - } - - // Case 2: Inline code provided as argument - if (args.length > 0) { - console.log('⚡ Executing inline code'); - return args.join(' '); - } - - // Case 3: Code from stdin - if (!process.stdin.isTTY) { - console.log('📥 Reading from stdin'); - return fs.readFileSync(0, 'utf8'); - } - - // No input - console.error('❌ No code to execute'); - console.error('Usage:'); - console.error(' node run.js script.js # Execute file'); - console.error(' node run.js "code here" # Execute inline'); - console.error(' cat script.js | node run.js # Execute from stdin'); - process.exit(1); -} - -/** - * Clean up old temporary execution files from previous runs - */ -function cleanupOldTempFiles() { - try { - const files = fs.readdirSync(__dirname); - const tempFiles = files.filter(f => f.startsWith('.temp-execution-') && f.endsWith('.js')); - - if (tempFiles.length > 0) { - tempFiles.forEach(file => { - const filePath = path.join(__dirname, file); - try { - fs.unlinkSync(filePath); - } catch (e) { - // Ignore errors - file might be in use or already deleted - } - }); - } - } catch (e) { - // Ignore directory read errors - } -} - -/** - * Wrap code in async IIFE if not already wrapped - */ -function wrapCodeIfNeeded(code) { - // Check if code already has require() and async structure - const hasRequire = code.includes('require('); - const hasAsyncIIFE = code.includes('(async () => {') || code.includes('(async()=>{'); - - // If it's already a complete script, return as-is - if (hasRequire && hasAsyncIIFE) { - return code; - } - - // If it's just Playwright commands, wrap in full template - if (!hasRequire) { - return ` -const { chromium, firefox, webkit, devices } = require('playwright'); -const helpers = require('./lib/helpers'); - -// Extra headers from environment variables (if configured) -const __extraHeaders = helpers.getExtraHeadersFromEnv(); - -/** - * Utility to merge environment headers into context options. - * Use when creating contexts with raw Playwright API instead of helpers.createContext(). - * @param {Object} options - Context options - * @returns {Object} Options with extraHTTPHeaders merged in - */ -function getContextOptionsWithHeaders(options = {}) { - if (!__extraHeaders) return options; - return { - ...options, - extraHTTPHeaders: { - ...__extraHeaders, - ...(options.extraHTTPHeaders || {}) - } - }; -} - -(async () => { - try { - ${code} - } catch (error) { - console.error('❌ Automation error:', error.message); - if (error.stack) { - console.error(error.stack); - } - process.exit(1); - } -})(); -`; - } - - // If has require but no async wrapper - if (!hasAsyncIIFE) { - return ` -(async () => { - try { - ${code} - } catch (error) { - console.error('❌ Automation error:', error.message); - if (error.stack) { - console.error(error.stack); - } - process.exit(1); - } -})(); -`; - } - - return code; -} - -/** - * Main execution - */ -async function main() { - console.log('🎭 Playwright Skill - Universal Executor\n'); - - // Clean up old temp files from previous runs - cleanupOldTempFiles(); - - // Check Playwright installation - if (!checkPlaywrightInstalled()) { - const installed = installPlaywright(); - if (!installed) { - process.exit(1); - } - } - - // Get code to execute - const rawCode = getCodeToExecute(); - const code = wrapCodeIfNeeded(rawCode); - - // Create temporary file for execution - const tempFile = path.join(__dirname, `.temp-execution-${Date.now()}.js`); - - try { - // Write code to temp file - fs.writeFileSync(tempFile, code, 'utf8'); - - // Execute the code - console.log('🚀 Starting automation...\n'); - require(tempFile); - - // Note: Temp file will be cleaned up on next run - // This allows long-running async operations to complete safely - - } catch (error) { - console.error('❌ Execution failed:', error.message); - if (error.stack) { - console.error('\n📋 Stack trace:'); - console.error(error.stack); - } - process.exit(1); - } -} - -// Run main function -main().catch(error => { - console.error('❌ Fatal error:', error.message); - process.exit(1); -}); -- cgit v1.2.3