new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Playwright · API reference · all subjects

cli routing

53 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

playwright-cli route command basic syntax

The playwright-cli route command intercepts and mocks network requests using glob patterns. Basic syntax: playwright-cli route <pattern> [options]. Common options include --status for custom HTTP status codes, --body for response body content, --content-type for response content type header, and --header for custom response headers.

playwright-cli route mocking examples

Examples: playwright-cli route "**/*.jpg" --status=404 mocks image requests with 404 status. playwright-cli route "**/api/users" --body='[{"id":1,"name":"Alice"}]' --content-type=application/json mocks API responses with JSON. playwright-cli route "**/api/data" --body='{"ok":true}' --header="X-Custom: value" adds custom headers to responses.

playwright-cli remove-header option

The --remove-header option removes specified headers from outgoing requests. Multiple headers can be removed by comma-separating them: playwright-cli route "**/*" --remove-header=cookie,authorization removes both cookie and authorization headers.

playwright-cli route-list command

The playwright-cli route-list command displays all currently active routes.

playwright-cli unroute command

The playwright-cli unroute command removes routes. Usage: playwright-cli unroute <pattern> removes a specific route matching the pattern, and playwright-cli unroute (with no pattern) removes all routes.

URL pattern syntax for route matching

URL patterns support: **/api/users for exact path match, **/api/*/details for wildcards in path segments, **/*.{png,jpg,jpeg} for file extension matching, and **/search?q=* for query parameter matching.

page.route conditional response based on request

Use page.route() with conditional logic to respond based on request details. Example: await page.route('**/api/login', route => { const body = route.request().postDataJSON(); if (body.username === 'admin') { route.fulfill({ body: JSON.stringify({ token: 'mock-token' }) }); } else { route.fulfill({ status: 401, body: JSON.stringify({ error: 'Invalid' }) }); } });

page.route modify real response

To modify a real response before returning it: await page.route('**/api/user', async route => { const response = await route.fetch(); const json = await response.json(); json.isPremium = true; await route.fulfill({ response, json }); }); This fetches the real response, modifies the JSON, and fulfills with the modified response.

page.route abort error options

route.abort() can abort requests with error types: connectionrefused, timedout, connectionreset, or internetdisconnected. Example: await page.route('**/api/offline', route => route.abort('internetdisconnected'));

page.route delayed response

To simulate network delays in route handlers: await page.route('**/api/slow', async route => { await new Promise(r => setTimeout(r, 3000)); route.fulfill({ body: JSON.stringify({ data: 'loaded' }) }); }); This delays fulfilling the route by 3000 milliseconds.

Named browser sessions with -s flag

Use the -s flag to create and manage named browser sessions in playwright-cli. Each named session is isolated from others. For example: playwright-cli -s=auth open https://app.example.com/login creates a session named 'auth', and playwright-cli -s=public open https://example.com creates a session named 'public'.

Browser session isolation properties

Each browser session has independent: cookies, LocalStorage, SessionStorage, IndexedDB, cache, browsing history, and open tabs. Sessions do not share state with each other.

Browser session commands: list, close, close-all, kill-all, delete-data

playwright-cli list shows all browser sessions. playwright-cli close stops the default browser. playwright-cli -s=mysession close stops a named browser. playwright-cli close-all stops all browser sessions. playwright-cli kill-all forcefully kills all daemon processes for stale/zombie processes. playwright-cli delete-data deletes default browser user data. playwright-cli -s=mysession delete-data deletes named browser user data.

PLAYWRIGHT_CLI_SESSION environment variable

Set the PLAYWRIGHT_CLI_SESSION environment variable to define a default browser session name. When set, playwright-cli commands without a -s flag will use the session name specified in this variable.

Persistent browser profile with --persistent flag

By default, browser profile is kept in memory only. Use the --persistent flag on the open command to persist the browser profile to disk: playwright-cli open https://example.com --persistent uses auto-generated location. Use --profile=/path/to/profile to specify a custom directory: playwright-cli open https://example.com --profile=/path/to/profile.

Attach to running Chrome or Edge by channel name

Use playwright-cli attach --cdp=<channel> to connect to a running browser instance that has remote debugging enabled. Navigate to chrome://inspect/#remote-debugging in the target browser and check 'Allow remote debugging for this browser instance'. Supported channels: chrome, chrome-beta, chrome-dev, chrome-canary, msedge, msedge-beta, msedge-dev, msedge-canary. When --session is not provided, the session is named after the channel (e.g., --cdp=msedge creates a session called 'msedge').

Attach to CDP endpoint

Use playwright-cli attach --cdp=<url> to connect to a browser that exposes a Chrome DevTools Protocol endpoint. Example: playwright-cli attach --cdp=http://localhost:9222.

Attach via browser extension

Use playwright-cli attach --extension to connect to a browser with the Playwright extension installed.

Detach from attached session

Use playwright-cli detach to tear down an attached session without affecting the external browser. The detach command only works on sessions created via attach, not on sessions created via open (use close for open sessions). Use playwright-cli -s=msedge detach to detach a specific named session.

Default browser session when -s is omitted

When the -s flag is omitted, commands use the default browser session. For example, playwright-cli open https://example.com, playwright-cli snapshot, and playwright-cli close all operate on the same default session.

Browser session configuration options

When opening a browser session, use: --config=.playwright/my-cli.json to open with a config file, --browser=firefox to open with a specific browser, --headed to open in headed mode, --persistent to open with persistent profile.

Best practice: name browser sessions semantically

Use clear, descriptive names for browser sessions that indicate their purpose. Good examples: playwright-cli -s=github-auth open https://github.com or playwright-cli -s=docs-scrape open https://docs.example.com. Avoid generic names like -s=s1.

Best practice: always clean up browser sessions

Stop browsers when done using playwright-cli -s=auth close or similar per-session close commands. Use playwright-cli close-all to stop all sessions at once. If browsers become unresponsive or zombie processes remain, use playwright-cli kill-all.

Best practice: delete stale browser data

Use playwright-cli -s=oldsession delete-data to remove old browser data and free disk space.

Concurrent scraping pattern with multiple named sessions

Example: Start multiple browsers concurrently with & in bash, then operate on each independently. playwright-cli -s=site1 open https://site1.com & playwright-cli -s=site2 open https://site2.com & playwright-cli -s=site3 open https://site3.com & wait. Then take snapshots from each: playwright-cli -s=site1 snapshot, playwright-cli -s=site2 snapshot, playwright-cli -s=site3 snapshot. Finally cleanup with playwright-cli close-all.

A/B testing sessions example

Example: Test different user experiences by opening separate sessions. playwright-cli -s=variant-a open 'https://app.com?variant=a' and playwright-cli -s=variant-b open 'https://app.com?variant=b'. Compare results with playwright-cli -s=variant-a screenshot and playwright-cli -s=variant-b screenshot.

Playwright test config: snapshotPathTemplate

The snapshotPathTemplate option in Playwright config controls the location of snapshots generated by toHaveScreenshot(), toMatchAriaSnapshot() and toMatchSnapshot() assertions. Supported tokens: {arg} - relative snapshot path without extension, {ext} - snapshot extension with leading dot, {platform} - value of process.platform, {projectName} - project's file-system-sanitized name, {snapshotDir} - project's snapshotDir, {testDir} - project's testDir, {testFileDir} - directories in relative path from testDir to test file, {testFileBaseName} - test file name without last extension, {testFileName} - test file name with extension, {testFilePath} - relative path from testDir to test file, {testName} - file-system-sanitized test title. Each token can be preceded with a character used only if token has non-empty value.

Playwright snapshotPathTemplate example

Example of snapshotPathTemplate configuration: ```js import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './tests', snapshotPathTemplate: '{testDir}/__screenshots__/{testFilePath}/{arg}{ext}', expect: { toHaveScreenshot: { pathTemplate: '{testDir}/__screenshots__{/projectName}/{testFilePath}/{arg}{ext}', }, toMatchAriaSnapshot: { pathTemplate: '{testDir}/__snapshots__/{testFilePath}/{arg}{ext}', }, }, }); ``` Shows single template for all assertions and assertion-specific templates.

playwright-cli element targeting methods

Elements can be targeted by: refs from snapshot (e15), CSS selectors (#main > button.submit), role locators (getByRole('button', { name: 'Submit' })), or test ids (getByTestId('submit-button')).

playwright-cli tab management commands

Tab management commands include: tab-list (list all tabs), tab-new (open new tab), tab-new https://example.com/page (open new tab with URL), tab-close (close current tab), tab-close 2 (close tab by index), tab-select 0 (select tab by index).

playwright-cli mouse commands

Mouse commands include: mousemove 150 300, mousedown, mousedown right, mouseup, mouseup right, mousewheel 0 100. These are invoked as playwright-cli mousemove 150 300, playwright-cli mousedown, playwright-cli mousedown right, playwright-cli mouseup, playwright-cli mouseup right, playwright-cli mousewheel 0 100.

playwright-cli browser session management

Named browser sessions are created with -s=sessionname flag: playwright-cli -s=mysession open example.com --persistent. Operations on named sessions: playwright-cli -s=mysession click e6, playwright-cli -s=mysession close, playwright-cli -s=mysession delete-data. Global commands: playwright-cli list (list all sessions), playwright-cli close-all (close all browsers), playwright-cli kill-all (forcefully kill all browser processes).

playwright-cli navigation commands

Navigation commands include: go-back, go-forward, reload. These are invoked as playwright-cli go-back, playwright-cli go-forward, playwright-cli reload.

playwright-cli keyboard commands

Keyboard commands include: press Enter, press ArrowDown, keydown Shift, keyup Shift. These are invoked as playwright-cli press Enter, playwright-cli press ArrowDown, playwright-cli keydown Shift, playwright-cli keyup Shift.

playwright-cli open command parameters

The playwright-cli open command accepts the following parameters: --browser (chrome, firefox, webkit, msedge), --mobile (emulate generic mobile device), --device (specific device like iPhone 15), --persistent (use persistent profile), --profile=/path/to/profile (custom profile directory), --extension=chrome (connect via Playwright Extension), --cdp (connect to running Chrome/Edge by channel name or CDP endpoint), --config=my-config.json (start with config file). The open command can optionally navigate to a URL immediately: playwright-cli open https://example.com/

playwright-cli core interaction commands

Core interaction commands include: click e3, dblclick e7, type "search query", fill e5 "user@example.com" with optional --submit flag (presses Enter after filling), drag e2 e8, drop e4 (accepts --path=./image.png or --data="text/plain=hello world"), hover e4, select e9 "option-value", upload ./document.pdf, check e12, uncheck e12, and eval "document.title" or eval "el => el.textContent" e5.

playwright-cli find command for searching snapshots

The find command searches the snapshot for text or regexp patterns and returns matching nodes with surrounding context. Syntax: playwright-cli find "Sign in" or playwright-cli find --regex "Sign (in|up)" or playwright-cli find --regex "/sign (in|up)/i" (flags like /i for case-insensitive are added by wrapping the regexp in slashes).

playwright-cli snapshot command options

The snapshot command accepts: --filename=after-click.yaml (save to specific file), a selector or element ref like "#main" or e34 (snapshot specific element instead of whole page), --depth=4 (limit snapshot depth for efficiency), --boxes (include each element's bounding box as [box=x,y,width,height]).

playwright-cli storage commands: cookies

Cookie commands: cookie-list (list all cookies), cookie-list --domain=example.com (filter by domain), cookie-get session_id (get specific cookie), cookie-set session_id abc123 (set cookie), cookie-set session_id abc123 --domain=example.com --httpOnly --secure (set with options), cookie-delete session_id (delete specific cookie), cookie-clear (clear all cookies).

playwright-cli storage commands: localStorage

LocalStorage commands: localstorage-list, localstorage-get theme, localstorage-set theme dark, localstorage-delete theme, localstorage-clear.

playwright-cli storage commands: sessionStorage

SessionStorage commands: sessionstorage-list, sessionstorage-get step, sessionstorage-set step 3, sessionstorage-delete step, sessionstorage-clear.

playwright-cli state save and load

State management: state-save (save state to auto-named file), state-save auth.json (save state to specific file), state-load auth.json (load state from file).

playwright-cli network routing commands

Network commands: route "**/*.jpg" --status=404 (mock response with status), route "https://api.example.com/**" --body='{"mock": true}' (mock response with body), route-list (list all routes), unroute "**/*.jpg" (remove specific route), unroute (remove all routes).

playwright-cli DevTools commands

DevTools commands include: console (show console messages), console warning (filter to warnings), requests (show network requests), request 5 (show specific request), run-code "async page => await page.context().grantPermissions(['geolocation'])" (execute custom code), run-code --filename=script.js (execute code from file), tracing-start, tracing-stop, video-start video.webm, video-chapter "Chapter Title" --description="Details" --duration=2000, video-stop, video-show-actions --duration=600 --position=top-right (annotate actions with callouts), video-hide-actions.

playwright-cli debugging and annotation commands

Debugging commands: show --annotate (launch dashboard for UI review with user annotation), generate-locator e5 --raw (generate Playwright locator from element ref or selector), highlight e5 (show persistent highlight), highlight e5 --style="outline: 3px dashed red" (highlight with custom style), highlight e5 --hide (hide single highlight), highlight --hide (hide all highlights).

playwright-cli global --raw option

The --raw global option strips page status, generated code, and snapshot sections from output, returning only the result value. Useful for piping command output into other tools. Commands that don't produce output return nothing.

playwright-cli screenshot and PDF commands

screenshot command options: no args (save to timestamped file), --filename=page.png (save to specific file), element ref like e5 or selector (screenshot element instead of page), --hires (high resolution). PDF command: pdf --filename=page.pdf (save page as PDF).

playwright-cli dialog commands

Dialog commands: dialog-accept (accept dialog), dialog-accept "confirmation text" (accept with specific text), dialog-dismiss (dismiss dialog).

playwright-cli resize command

The resize command changes viewport dimensions: playwright-cli resize 1920 1080.

playwright-cli installation methods

playwright-cli can be installed globally via npm install -g @playwright/cli@latest. If not available globally, use local versions: npx --no-install playwright --version or python -m playwright --version. Commands can be run with npx playwright cli or python -m playwright cli.

playwright-cli attach commands

Attach commands: attach --extension=chrome (connect via Playwright Extension), attach --cdp=chrome (connect to running Chrome by channel name), attach --cdp=msedge (connect to running Edge by channel name), attach --cdp=http://localhost:9222 (connect via CDP endpoint).

playwright-cli detach command

The detach command disconnects from an attached browser while leaving the external browser running: playwright-cli -s=msedge detach.

playwright-cli delete-data command

The delete-data command deletes user data for the default session: playwright-cli delete-data.

Give your agent this brain