Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Automate browser interactions for web testing, form filling, screenshots, and data extraction using the playwright-cli tool.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/running-code.md
1# Running Custom Playwright Code23Use `run-code` to execute arbitrary Playwright code for advanced scenarios not covered by CLI commands.45## Syntax67```bash8playwright-cli run-code "async page => {9// Your Playwright code here10// Access page.context() for browser context operations11}"12```1314You can also load the function from a file:1516```bash17playwright-cli run-code --filename=./my-script.js18```192021The code must be a single function expression, it is wrapped in `(...)` and evaluated.22import/export/require syntax is not supported.2324## Geolocation2526```bash27# Grant geolocation permission and set location28playwright-cli run-code "async page => {29await page.context().grantPermissions(['geolocation']);30await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });31}"3233# Set location to London34playwright-cli run-code "async page => {35await page.context().grantPermissions(['geolocation']);36await page.context().setGeolocation({ latitude: 51.5074, longitude: -0.1278 });37}"3839# Clear geolocation override40playwright-cli run-code "async page => {41await page.context().clearPermissions();42}"43```4445## Permissions4647```bash48# Grant multiple permissions49playwright-cli run-code "async page => {50await page.context().grantPermissions([51'geolocation',52'notifications',53'camera',54'microphone'55]);56}"5758# Grant permissions for specific origin59playwright-cli run-code "async page => {60await page.context().grantPermissions(['clipboard-read'], {61origin: 'https://example.com'62});63}"64```6566## Media Emulation6768```bash69# Emulate dark color scheme70playwright-cli run-code "async page => {71await page.emulateMedia({ colorScheme: 'dark' });72}"7374# Emulate light color scheme75playwright-cli run-code "async page => {76await page.emulateMedia({ colorScheme: 'light' });77}"7879# Emulate reduced motion80playwright-cli run-code "async page => {81await page.emulateMedia({ reducedMotion: 'reduce' });82}"8384# Emulate print media85playwright-cli run-code "async page => {86await page.emulateMedia({ media: 'print' });87}"88```8990## Wait Strategies9192```bash93# Wait for network idle94playwright-cli run-code "async page => {95await page.waitForLoadState('networkidle');96}"9798# Wait for specific element99playwright-cli run-code "async page => {100await page.locator('.loading').waitFor({ state: 'hidden' });101}"102103# Wait for function to return true104playwright-cli run-code "async page => {105await page.waitForFunction(() => window.appReady === true);106}"107108# Wait with timeout109playwright-cli run-code "async page => {110await page.locator('.result').waitFor({ timeout: 10000 });111}"112```113114## Frames and Iframes115116```bash117# Work with iframe118playwright-cli run-code "async page => {119const frame = page.locator('iframe#my-iframe').contentFrame();120await frame.locator('button').click();121}"122123# Get all frames124playwright-cli run-code "async page => {125const frames = page.frames();126return frames.map(f => f.url());127}"128```129130## File Downloads131132```bash133# Handle file download134playwright-cli run-code "async page => {135const downloadPromise = page.waitForEvent('download');136await page.getByRole('link', { name: 'Download' }).click();137const download = await downloadPromise;138await download.saveAs('./downloaded-file.pdf');139return download.suggestedFilename();140}"141```142143## Clipboard144145```bash146# Read clipboard (requires permission)147playwright-cli run-code "async page => {148await page.context().grantPermissions(['clipboard-read']);149return await page.evaluate(() => navigator.clipboard.readText());150}"151152# Write to clipboard153playwright-cli run-code "async page => {154await page.evaluate(text => navigator.clipboard.writeText(text), 'Hello clipboard!');155}"156```157158## Page Information159160```bash161# Get page title162playwright-cli run-code "async page => {163return await page.title();164}"165166# Get current URL167playwright-cli run-code "async page => {168return page.url();169}"170171# Get page content172playwright-cli run-code "async page => {173return await page.content();174}"175176# Get viewport size177playwright-cli run-code "async page => {178return page.viewportSize();179}"180```181182## JavaScript Execution183184```bash185# Execute JavaScript and return result186playwright-cli run-code "async page => {187return await page.evaluate(() => {188return {189userAgent: navigator.userAgent,190language: navigator.language,191cookiesEnabled: navigator.cookieEnabled192};193});194}"195196# Pass arguments to evaluate197playwright-cli run-code "async page => {198const multiplier = 5;199return await page.evaluate(m => document.querySelectorAll('li').length * m, multiplier);200}"201```202203## Error Handling204205```bash206# Try-catch in run-code207playwright-cli run-code "async page => {208try {209await page.getByRole('button', { name: 'Submit' }).click({ timeout: 1000 });210return 'clicked';211} catch (e) {212return 'element not found';213}214}"215```216217## Complex Workflows218219```bash220# Login and save state221playwright-cli run-code "async page => {222await page.goto('https://example.com/login');223await page.getByRole('textbox', { name: 'Email' }).fill('[email protected]');224await page.getByRole('textbox', { name: 'Password' }).fill('secret');225await page.getByRole('button', { name: 'Sign in' }).click();226await page.waitForURL('**/dashboard');227await page.context().storageState({ path: 'auth.json' });228return 'Login successful';229}"230231# Scrape data from multiple pages232playwright-cli run-code "async page => {233const results = [];234for (let i = 1; i <= 3; i++) {235await page.goto(\`https://example.com/page/\${i}\`);236const items = await page.locator('.item').allTextContents();237results.push(...items);238}239return results;240}"241```242