
Playwright
- 777 installs
- 196 repo stars
- Updated July 25, 2026
- secondsky/claude-skills
playwright is a Claude Code skill that writes and runs Playwright browser automation scripts for developers who need local end-to-end tests covering navigation, forms, and assertions.
About
playwright is a Claude Code skill that equips agents to author and execute real-browser Playwright tests on a developer machine. It bundles @playwright/test and the Playwright runtime (lockfile pins Playwright 1.57.0) so agents can scaffold specs, drive Chromium/WebKit/Firefox, fill forms, click through flows, and assert DOM state without manual test boilerplate. Developers reach for playwright when a feature needs repeatable UI verification—login paths, checkout wizards, or regression checks—before merging or shipping. The skill targets local execution with standard Playwright CLI patterns rather than hosted CI configuration alone.
- Pins @playwright/test and playwright (~1.55–1.57) with a ready skill workspace
- Runnable patterns: launch Chromium, goto routes, fill inputs, submit forms
- Supports headed runs with slowMo for debugging flaky UI during solo development
- CLI-driven workflows agents can extend for contact pages, auth, and multi-step flows
- Node-based scripts suitable for CI hooks or one-off local repro commands
Playwright by the numbers
- 777 all-time installs (skills.sh)
- +32 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #560 of 2,159 Testing & QA skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
npx skills add https://github.com/secondsky/claude-skills --skill playwrightAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 777 |
|---|---|
| repo stars | ★ 196 |
| Security audit | 1 / 3 scanners passed |
| Last updated | July 25, 2026 |
| Repository | secondsky/claude-skills ↗ |
How do you automate browser UI tests with Playwright?
Automate real-browser flows—navigation, forms, and assertions—with Playwright scripts your agent writes and runs locally.
Who is it for?
Developers shipping web apps who want agents to generate and run Playwright E2E specs locally during feature work.
Skip if: Teams that only need unit tests without a browser, or projects with no web UI surface to exercise.
When should I use this skill?
The user asks to write, debug, or run Playwright browser tests, form flows, or UI regression checks.
What you get
Executable Playwright spec files, browser-driven test runs, and pass/fail assertion reports.
- Playwright spec files
- Browser test run output
- Assertion pass/fail results
By the numbers
- Lockfile pins Playwright and @playwright/test at version 1.57.0
Files
Playwright - Browser Automation & E2E Testing
Expert knowledge for browser automation and end-to-end testing with Playwright - a modern cross-browser testing framework.
IMPORTANT - Path Resolution: This skill can be installed in different locations. Before executing commands, determine the skill directory based on where you loaded this SKILL.md file, and use that path in all commands. Replace $SKILL_DIR with the actual discovered path.
Common installation paths:
- Plugin system:
~/.claude/plugins/*/playwright/skills/playwright - Manual global:
~/.claude/skills/playwright - Project-specific:
<project>/.claude/skills/playwright
CRITICAL WORKFLOW - Follow These Steps
When automating browser tasks:
1. Auto-detect dev servers - For localhost testing, ALWAYS run server detection FIRST:
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 constant at top of script
5. Execute via run.js - Always run: cd $SKILL_DIR && node run.js /tmp/playwright-test-*.js
Quick Start
First-Time Setup
# Navigate to skill directory
cd $SKILL_DIR
# Install using bun (preferred)
bun run setup
# Or using npm
npm run setup:npmThis installs Playwright and Chromium browser. Only needed once.
Installation (For E2E Testing Projects)
# Using Bun (preferred)
bun add -d @playwright/test
bunx playwright install
# Using npm
npm init playwright@latestConfiguration
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
testDir: './tests',
fullyParallel: true,
reporter: 'html',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
webServer: {
command: 'bun run dev',
url: 'http://localhost:3000',
},
})Browser Automation Patterns
How It Works
1. You describe what you want to test/automate 2. I auto-detect running dev servers (or ask for URL) 3. I write custom Playwright code in /tmp/playwright-test-*.js 4. I execute it via: cd $SKILL_DIR && node run.js /tmp/playwright-test-*.js 5. Results displayed in real-time, browser window visible
Test a Page (Multiple Viewports)
// /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();
})();Execute: cd $SKILL_DIR && node run.js /tmp/playwright-test-responsive.js
Test Login Flow
// /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"]');
await page.waitForURL('**/dashboard');
console.log('✅ Login successful, redirected to dashboard');
await browser.close();
})();Check for Broken Links
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();
})();E2E Testing Patterns
Running Tests
# Run all tests
bunx playwright test
# Headed mode (see browser)
bunx playwright test --headed
# Specific file
bunx playwright test tests/login.spec.ts
# Debug mode
bunx playwright test --debug
# UI mode (interactive)
bunx playwright test --ui
# Specific browser
bunx playwright test --project=chromium
# Generate report
bunx playwright show-reportWriting Tests
import { test, expect } from '@playwright/test'
test.describe('Login flow', () => {
test('successful login', async ({ page }) => {
await page.goto('/')
await page.getByRole('link', { name: 'Login' }).click()
await page.getByLabel('Email').fill('user@example.com')
await page.getByLabel('Password').fill('password123')
await page.getByRole('button', { name: 'Sign in' }).click()
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible()
})
test('shows error for invalid credentials', async ({ page }) => {
await page.goto('/login')
await page.getByLabel('Email').fill('wrong@example.com')
await page.getByLabel('Password').fill('wrongpassword')
await page.getByRole('button', { name: 'Sign in' }).click()
await expect(page.getByText('Invalid credentials')).toBeVisible()
})
})Selectors (Best Practices)
// ✅ Role-based (recommended)
await page.getByRole('button', { name: 'Submit' })
await page.getByRole('link', { name: 'Home' })
// ✅ Text/Label
await page.getByText('Hello World')
await page.getByLabel('Email')
// ✅ Test ID (fallback)
await page.getByTestId('submit-button')
// ❌ Avoid CSS selectors (brittle)
await page.locator('.btn-primary')Assertions
// Visibility
await expect(page.getByText('Success')).toBeVisible()
await expect(page.getByRole('button')).toBeEnabled()
// Text
await expect(page.getByRole('heading')).toHaveText('Welcome')
await expect(page.getByRole('alert')).toContainText('error')
// Attributes
await expect(page.getByRole('link')).toHaveAttribute('href', '/home')
// URL/Title
await expect(page).toHaveURL('/dashboard')
await expect(page).toHaveTitle('Dashboard')
// Count
await expect(page.getByRole('listitem')).toHaveCount(5)Actions
// Clicking
await page.getByRole('button').click()
await page.getByText('File').dblclick()
// Typing
await page.getByLabel('Email').fill('user@example.com')
await page.getByLabel('Search').press('Enter')
// Selecting
await page.getByLabel('Country').selectOption('us')
// File Upload
await page.getByLabel('Upload').setInputFiles('path/to/file.pdf')Network Mocking
test('mocks API response', async ({ page }) => {
await page.route('**/api/users', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([{ id: 1, name: 'Test User' }]),
})
})
await page.goto('/users')
await expect(page.getByText('Test User')).toBeVisible()
})Visual Testing
test('captures screenshot', async ({ page }) => {
await page.goto('/')
await page.screenshot({ path: 'screenshot.png', fullPage: true })
await expect(page).toHaveScreenshot('homepage.png')
})Authentication State
// Save state after login
setup('authenticate', async ({ page }) => {
await page.goto('/login')
await page.getByLabel('Email').fill('user@example.com')
await page.getByLabel('Password').fill('password123')
await page.getByRole('button', { name: 'Sign in' }).click()
await page.context().storageState({ path: 'auth.json' })
})
// Reuse in config
use: { storageState: 'auth.json' }Page Object Model
// pages/LoginPage.ts
import { Page, Locator } from '@playwright/test'
export class LoginPage {
readonly emailInput: Locator
readonly passwordInput: Locator
readonly submitButton: Locator
constructor(page: Page) {
this.emailInput = page.getByLabel('Email')
this.passwordInput = page.getByLabel('Password')
this.submitButton = page.getByRole('button', { name: 'Sign in' })
}
async login(email: string, password: string) {
await this.emailInput.fill(email)
await this.passwordInput.fill(password)
await this.submitButton.click()
}
}
// Usage
const loginPage = new LoginPage(page)
await loginPage.login('user@example.com', 'password123')Available Helpers
Optional utility functions in lib/helpers.js:
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');
// Create context with custom headers
const context = await helpers.createContext(browser);Custom HTTP Headers
Configure custom headers for all HTTP requests via environment variables:
# Single header (common case)
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)
PW_EXTRA_HEADERS='{"X-Automated-By":"playwright-skill","X-Debug":"true"}' \
cd $SKILL_DIR && node run.js /tmp/my-script.jsHeaders are automatically applied when using helpers.createContext().
Inline Execution (Simple Tasks)
For quick one-off tasks:
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: Quick one-off tasks (screenshot, element check)
- Files: Complex tests, reusable automation
Best Practices
- CRITICAL: Detect servers FIRST - Always run
detectDevServers()before writing test code - Use /tmp for test files - Write to
/tmp/playwright-test-*.js, never to skill directory - Parameterize URLs - Put detected/provided URL in
TARGET_URLconstant - DEFAULT: Visible browser - Always use
headless: falseunless explicitly requested - Prefer role-based selectors - More stable than CSS selectors
- Trust auto-waiting - No manual sleeps needed
- Each test gets fresh context - Automatic isolation
- Run tests in parallel - Default behavior
- Mock external dependencies - Use
page.route() - Use trace viewer - Time-travel debugging
Tips
- Slow down: Use
slowMo: 100to make actions visible - Wait strategies: Use
waitForURL,waitForSelector,waitForLoadStateinstead of fixed timeouts - Error handling: Always use try-catch for robust automation
- Console output: Use
console.log()to track progress
Troubleshooting
Playwright not installed:
cd $SKILL_DIR && bun run setupModule 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 })
Secure Installation
When installing Playwright and browser binaries, follow supply chain security best practices:
- Block post-install scripts —
npm config set ignore-scripts true(then manually runnpx playwright installto download browsers) - Cooldown period — Wait 7 days for new package versions to be vetted by the community
- Audit before installing — Run
socket package score npm <pkg>or usesocket npm install <pkg>to check packages
Load the dependency-upgrade skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement.
See Also
vitest-testing- Unit and integration testingapi-testing- HTTP API testingtest-quality-analysis- Test quality patterns
When to Load References
Load references/API_REFERENCE.md when you need:
- Advanced selector patterns and locator strategies
- Network interception and request/response mocking
- Authentication patterns and session management
- Visual regression testing setup
- Mobile device emulation configurations
- Performance testing and metrics
- Debugging techniques (trace viewer, inspector)
- CI/CD pipeline integration
- Accessibility testing with axe-core
- Data-driven and parameterized testing
- Page Object Model advanced patterns
- Parallel execution strategies
{
"lockfileVersion": 1,
"configVersion": 1,
"workspaces": {
"": {
"name": "playwright-skill",
"dependencies": {
"@playwright/test": "^1.55.0",
"playwright": "^1.55.0",
},
},
},
"packages": {
"@playwright/test": ["@playwright/test@1.57.0", "", { "dependencies": { "playwright": "1.57.0" }, "bin": { "playwright": "cli.js" } }, "sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA=="],
"fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
"playwright": ["playwright@1.57.0", "", { "dependencies": { "playwright-core": "1.57.0" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw=="],
"playwright-core": ["playwright-core@1.57.0", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ=="],
}
}
// Example: Fill and submit a form
const { chromium } = require('playwright');
const TARGET_URL = 'http://localhost:3000'; // Change as needed
(async () => {
const browser = await chromium.launch({ headless: false, slowMo: 50 });
const page = await browser.newPage();
await page.goto(`${TARGET_URL}/contact`);
// Fill form fields
await page.fill('input[name="name"]', 'John Doe');
await page.fill('input[name="email"]', 'john@example.com');
await page.fill('textarea[name="message"]', 'This is a test message');
// Submit form
await page.click('button[type="submit"]');
// Verify submission
try {
await page.waitForSelector('.success-message', { timeout: 5000 });
console.log('✅ Form submitted successfully');
} catch (e) {
console.log('❌ Form submission failed or success message not found');
}
await browser.close();
})();
// Example: Check for broken links on a page
const { chromium } = require('playwright');
const TARGET_URL = 'http://localhost:3000'; // Change as needed
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
console.log(`Checking links on: ${TARGET_URL}\n`);
await page.goto(TARGET_URL);
// Get all links, then filter to http(s) only
// Note: This excludes relative links (/about), mailto:, tel:, and #anchors
const allLinks = await page.locator('a[href]').all();
const httpLinks = [];
for (const link of allLinks) {
const href = await link.getAttribute('href');
// Filter to only http(s) and protocol-relative links
if (href && (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('//'))) {
httpLinks.push({ locator: link, href });
}
}
console.log(`Found ${httpLinks.length} external http(s) links to check\n`);
const results = { working: 0, broken: [] };
for (const { locator: link, href } of httpLinks) {
try {
const response = await page.request.head(href);
if (response.ok()) {
results.working++;
console.log(`✅ ${href}`);
} else {
results.broken.push({ url: href, status: response.status() });
console.log(`❌ ${href} (Status: ${response.status()})`);
}
} catch (e) {
results.broken.push({ url: href, error: e.message });
console.log(`❌ ${href} (Error: ${e.message})`);
}
}
console.log(`\n\n=== RESULTS ===`);
console.log(`✅ Working links: ${results.working}`);
console.log(`❌ Broken links: ${results.broken.length}`);
if (results.broken.length > 0) {
console.log('\nBroken link details:');
console.log(JSON.stringify(results.broken, null, 2));
}
await browser.close();
})();
// Example: Test responsive design across multiple viewports
const { chromium } = require('playwright');
const TARGET_URL = 'http://localhost:3000'; // Change as needed
(async () => {
const browser = await chromium.launch({ headless: false, slowMo: 100 });
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(`\nTesting ${viewport.name} (${viewport.width}x${viewport.height})`);
await page.setViewportSize({
width: viewport.width,
height: viewport.height,
});
await page.goto(TARGET_URL);
// Wait for network to be idle before taking screenshot
await page.waitForLoadState('networkidle');
await page.screenshot({
path: `/tmp/${viewport.name.toLowerCase()}.png`,
fullPage: true,
});
console.log(`✅ Screenshot saved: /tmp/${viewport.name.toLowerCase()}.png`);
}
console.log('\n✅ All viewports tested');
await browser.close();
})();
// playwright-helpers.js
// Reusable utility functions for Playwright automation
const { chromium, firefox, webkit } = require('playwright');
const http = require('http');
/**
* 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);
}
// Note: User-Agent should be set at context level via createContext({ userAgent })
// Setting it via page.setExtraHTTPHeaders can be overridden and is unreliable
// 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}`);
// Wait for selector to be ready instead of fixed timeout
try {
await page.waitForSelector(selector, { state: 'visible', timeout: retryDelay });
} catch {
// Continue even if selector not visible yet
}
}
}
}
/**
* 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 = `/tmp/${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)
* @param {number} settleDelay - Time to wait for scroll animation (ms), default 500
*/
async function scrollPage(page, direction = 'down', distance = 500, settleDelay = 500) {
const previousY = await page.evaluate(() => window.scrollY);
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;
}
// Wait for scroll to stabilize using condition-based wait
try {
await page.waitForFunction(
(prevY) => Math.abs(window.scrollY - prevY) >= 10 || window.scrollY === prevY,
{ timeout: settleDelay },
previousY
);
} catch {
// Fallback if waitForFunction times out - scroll may have completed
}
}
/**
* 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
}
}
// Log when no banner found
console.debug(`No cookie banner detected. Tried ${commonSelectors.length} selectors with timeout ${timeout}ms`);
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 },
// Use explicit userAgent if provided, otherwise use mobile UA if mobile option is set
userAgent: options.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<number>} customPorts - Additional ports to check
* @returns {Promise<Array>} Array of detected server URLs
*/
async function detectDevServers(customPorts = []) {
// 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
};
{
"name": "playwright-skill",
"version": "1.0.0",
"description": "Complete browser automation and E2E testing with Playwright",
"main": "run.js",
"scripts": {
"setup": "bun install && bunx playwright install chromium",
"setup:npm": "npm install && npx playwright install chromium",
"setup:all-browsers": "bun install && bunx playwright install",
"install-all-browsers": "bunx playwright install",
"test": "bunx playwright test",
"test:headed": "bunx playwright test --headed",
"test:debug": "bunx playwright test --debug",
"test:ui": "bunx playwright test --ui",
"codegen": "bunx playwright codegen"
},
"keywords": [
"playwright",
"browser-automation",
"e2e-testing",
"web-testing",
"test-automation",
"claude-skill"
],
"author": "Claude Skills Maintainers",
"license": "MIT",
"dependencies": {
"@playwright/test": "^1.59.0",
"playwright": "^1.59.0"
},
"devDependencies": {},
"engines": {
"node": ">=18.0.0",
"bun": ">=1.0.0"
}
}
Playwright - Complete API Reference
This document contains comprehensive Playwright API documentation and advanced patterns. For quick-start execution patterns, see SKILL.md.
Table of Contents
- Core Patterns
- Selectors & Locators
- Common Actions
- Waiting Strategies
- Assertions
- Page Object Model
- Network & API Testing
- Authentication & Session Management
- Visual Testing
- Mobile Testing
- Debugging
- Performance Testing
- Parallel Execution
- Data-Driven Testing
- Accessibility Testing
- CI/CD Integration
- Best Practices
Core Patterns
Basic Browser Automation
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
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
// 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(); // FragileAdvanced Locator Patterns
// 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
// 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
// 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
// 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
// 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
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
// 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
// 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:
# 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 when using helpers.createContext(browser).
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
// 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
// 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
# Run with inspector
bunx playwright test --debug
# Headed mode
bunx playwright test --headed
# Slow motion
bunx playwright test --headed --slowmo=1000In-Code Debugging
// 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
// 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
// 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
// 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
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
name: Playwright Tests
on:
push:
branches: [main, master]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
- name: Install dependencies
run: bun install
- name: Install Playwright Browsers
run: bunx playwright install --with-deps
- name: Run tests
run: bunx playwright testBest 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
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('button.open-popup')
]);
await popup.waitForLoadState();File Downloads
const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('button.download')
]);
await download.saveAs(`./downloads/${download.suggestedFilename()}`);iFrames
const frame = page.frameLocator('#my-iframe');
await frame.locator('button').click();Infinite Scroll
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
# Run tests
bunx playwright test
# Run in headed mode
bunx playwright test --headed
# Debug tests
bunx playwright test --debug
# Generate code
bunx playwright codegen https://example.com
# Show report
bunx playwright show-reportAdditional Resources
#!/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 {
// Try bun first, fallback to npm
const packageManager = fs.existsSync(path.join(__dirname, 'bun.lockb')) ? 'bun' : 'npm';
if (packageManager === 'bun') {
execSync('bun install', { stdio: 'inherit', cwd: __dirname });
execSync('bunx playwright install chromium', { stdio: 'inherit', cwd: __dirname });
} else {
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, '&& bun 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 and export as promise for dynamic import
*/
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, wrap it to export the promise
if (hasRequire && hasAsyncIIFE) {
return `
${code}
// Note: The above code contains an async IIFE. If you need to wait for it,
// ensure it's exported or awaited properly.
`;
}
// 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 || {})
}
};
}
module.exports = (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 `
module.exports = (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 using dynamic import
console.log('🚀 Starting automation...\n');
// Convert file path to file URL for dynamic import
const { pathToFileURL } = require('url');
const fileUrl = pathToFileURL(tempFile).href;
// Use dynamic import and await the exported promise
const module = await import(fileUrl);
if (module.default) {
await module.default;
}
// Clean up temp file after completion
try {
fs.unlinkSync(tempFile);
} catch (e) {
// Ignore cleanup errors
}
} catch (error) {
console.error('❌ Execution failed:', error.message);
if (error.stack) {
console.error('\n📋 Stack trace:');
console.error(error.stack);
}
// Clean up temp file on error
try {
fs.unlinkSync(tempFile);
} catch (e) {
// Ignore cleanup errors
}
process.exit(1);
}
}
// Run main function
main().catch(error => {
console.error('❌ Fatal error:', error.message);
process.exit(1);
});
Related skills
How it compares
Choose playwright when you need executable browser E2E specs locally; use lighter unit-test skills when no real browser session is required.
FAQ
What does the playwright skill automate?
The playwright skill automates real-browser flows—page navigation, form interaction, clicks, and DOM assertions—by having Claude Code write and execute Playwright test scripts locally using the bundled @playwright/test runtime.
Which Playwright version ships with this skill?
The playwright skill lockfile pins Playwright and @playwright/test at version 1.57.0, giving agents a consistent local runtime for generating and running browser automation specs.
Is Playwright safe to install?
skills.sh reports 1 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.