Best JavaScript code snippet using playwright-internal
innerCli.js
Source:innerCli.js  
1"use strict";2var _fs = _interopRequireDefault(require("fs"));3var _os = _interopRequireDefault(require("os"));4var _path = _interopRequireDefault(require("path"));5var _commander = require("commander");6var _driver = require("./driver");7var _traceViewer = require("../server/trace/viewer/traceViewer");8var playwright = _interopRequireWildcard(require("../.."));9var _child_process = require("child_process");10var _registry = require("../utils/registry");11var _utils = require("../utils/utils");12var _gridAgent = require("../grid/gridAgent");13var _gridServer = require("../grid/gridServer");14function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }15function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }16function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }17/**18 * Copyright (c) Microsoft Corporation.19 *20 * Licensed under the Apache License, Version 2.0 (the "License");21 * you may not use this file except in compliance with the License.22 * You may obtain a copy of the License at23 *24 * http://www.apache.org/licenses/LICENSE-2.025 *26 * Unless required by applicable law or agreed to in writing, software27 * distributed under the License is distributed on an "AS IS" BASIS,28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.29 * See the License for the specific language governing permissions and30 * limitations under the License.31 */32/* eslint-disable no-console */33const packageJSON = require('../../package.json');34_commander.program.version('Version ' + (process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version)).name(buildBasePlaywrightCLICommand(process.env.PW_CLI_TARGET_LANG));35commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []).action(function (url, options) {36  open(options, url, language()).catch(logErrorAndExit);37}).addHelpText('afterAll', `38Examples:39  $ open  $ open -b webkit https://example.com`);40commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()]]).action(function (url, options) {41  codegen(options, url, options.target, options.output).catch(logErrorAndExit);42}).addHelpText('afterAll', `43Examples:44  $ codegen45  $ codegen --target=python46  $ codegen -b webkit https://example.com`);47_commander.program.command('debug <app> [args...]', {48  hidden: true49}).description('run command in debug mode: disable timeout, open inspector').allowUnknownOption(true).action(function (app, options) {50  (0, _child_process.spawn)(app, options, {51    env: { ...process.env,52      PWDEBUG: '1'53    },54    stdio: 'inherit'55  });56}).addHelpText('afterAll', `57Examples:58  $ debug node test.js59  $ debug npm run test`);60function suggestedBrowsersToInstall() {61  return _registry.registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', ');62}63function checkBrowsersToInstall(args) {64  const faultyArguments = [];65  const executables = [];66  for (const arg of args) {67    const executable = _registry.registry.findExecutable(arg);68    if (!executable || executable.installType === 'none') faultyArguments.push(arg);else executables.push(executable);69  }70  if (faultyArguments.length) {71    console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`);72    process.exit(1);73  }74  return executables;75}76_commander.program.command('install [browser...]').description('ensure browsers necessary for this version of Playwright are installed').option('--with-deps', 'install system dependencies for browsers').action(async function (args, options) {77  try {78    if (!args.length) {79      const executables = _registry.registry.defaultExecutables();80      if (options.withDeps) await _registry.registry.installDeps(executables, false);81      await _registry.registry.install(executables);82    } else {83      const installDockerImage = args.some(arg => arg === 'docker-image');84      args = args.filter(arg => arg !== 'docker-image');85      if (installDockerImage) {86        const imageName = `mcr.microsoft.com/playwright:v${(0, _utils.getPlaywrightVersion)()}-focal`;87        const {88          code89        } = await (0, _utils.spawnAsync)('docker', ['pull', imageName], {90          stdio: 'inherit'91        });92        if (code !== 0) {93          console.log('Failed to pull docker image');94          process.exit(1);95        }96      }97      const executables = checkBrowsersToInstall(args);98      if (options.withDeps) await _registry.registry.installDeps(executables, false);99      await _registry.registry.install(executables);100    }101  } catch (e) {102    console.log(`Failed to install browsers\n${e}`);103    process.exit(1);104  }105}).addHelpText('afterAll', `106Examples:107  - $ install108    Install default browsers.109  - $ install chrome firefox110    Install custom browsers, supports ${suggestedBrowsersToInstall()}.`);111_commander.program.command('install-deps [browser...]').description('install dependencies necessary to run browsers (will ask for sudo permissions)').option('--dry-run', 'Do not execute installation commands, only print them').action(async function (args, options) {112  try {113    if (!args.length) await _registry.registry.installDeps(_registry.registry.defaultExecutables(), !!options.dryRun);else await _registry.registry.installDeps(checkBrowsersToInstall(args), !!options.dryRun);114  } catch (e) {115    console.log(`Failed to install browser dependencies\n${e}`);116    process.exit(1);117  }118}).addHelpText('afterAll', `119Examples:120  - $ install-deps121    Install dependencies for default browsers.122  - $ install-deps chrome firefox123    Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`);124const browsers = [{125  alias: 'cr',126  name: 'Chromium',127  type: 'chromium'128}, {129  alias: 'ff',130  name: 'Firefox',131  type: 'firefox'132}, {133  alias: 'wk',134  name: 'WebKit',135  type: 'webkit'136}];137for (const {138  alias,139  name,140  type141} of browsers) {142  commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []).action(function (url, options) {143    open({ ...options,144      browser: type145    }, url, options.target).catch(logErrorAndExit);146  }).addHelpText('afterAll', `147Examples:148  $ ${alias} https://example.com`);149}150commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)']]).action(function (url, filename, command) {151  screenshot(command, command, url, filename).catch(logErrorAndExit);152}).addHelpText('afterAll', `153Examples:154  $ screenshot -b webkit https://example.com example.png`);155commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf']]).action(function (url, filename, options) {156  pdf(options, options, url, filename).catch(logErrorAndExit);157}).addHelpText('afterAll', `158Examples:159  $ pdf https://example.com example.pdf`);160_commander.program.command('experimental-grid-server', {161  hidden: true162}).option('--port <port>', 'grid port; defaults to 3333').option('--agent-factory <factory>', 'path to grid agent factory or npm package').option('--auth-token <authToken>', 'optional authentication token').action(function (options) {163  launchGridServer(options.agentFactory, options.port || 3333, options.authToken);164});165_commander.program.command('experimental-grid-agent', {166  hidden: true167}).requiredOption('--agent-id <agentId>', 'agent ID').requiredOption('--grid-url <gridURL>', 'grid URL').action(function (options) {168  (0, _gridAgent.launchGridAgent)(options.agentId, options.gridUrl);169});170_commander.program.command('show-trace [trace]').option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium').description('Show trace viewer').action(function (trace, options) {171  if (options.browser === 'cr') options.browser = 'chromium';172  if (options.browser === 'ff') options.browser = 'firefox';173  if (options.browser === 'wk') options.browser = 'webkit';174  (0, _traceViewer.showTraceViewer)(trace, options.browser, false, 9322).catch(logErrorAndExit);175}).addHelpText('afterAll', `176Examples:177  $ show-trace https://example.com/trace.zip`);178if (!process.env.PW_CLI_TARGET_LANG) {179  let playwrightTestPackagePath = null;180  try {181    playwrightTestPackagePath = require.resolve('@playwright/test/lib/cli', {182      paths: [__dirname, process.cwd()]183    });184  } catch {}185  if (playwrightTestPackagePath) {186    require(playwrightTestPackagePath).addTestCommand(_commander.program);187    require(playwrightTestPackagePath).addShowReportCommand(_commander.program);188  } else {189    {190      const command = _commander.program.command('test').allowUnknownOption(true);191      command.description('Run tests with Playwright Test. Available in @playwright/test package.');192      command.action(async () => {193        console.error('Please install @playwright/test package to use Playwright Test.');194        console.error('  npm install -D @playwright/test');195        process.exit(1);196      });197    }198    {199      const command = _commander.program.command('show-report').allowUnknownOption(true);200      command.description('Show Playwright Test HTML report. Available in @playwright/test package.');201      command.action(async () => {202        console.error('Please install @playwright/test package to use Playwright Test.');203        console.error('  npm install -D @playwright/test');204        process.exit(1);205      });206    }207  }208}209if (process.argv[2] === 'run-driver') (0, _driver.runDriver)();else if (process.argv[2] === 'run-server') (0, _driver.runServer)(process.argv[3] ? +process.argv[3] : undefined).catch(logErrorAndExit);else if (process.argv[2] === 'print-api-json') (0, _driver.printApiJson)();else if (process.argv[2] === 'launch-server') (0, _driver.launchBrowserServer)(process.argv[3], process.argv[4]).catch(logErrorAndExit);else _commander.program.parse(process.argv);210async function launchContext(options, headless, executablePath) {211  validateOptions(options);212  const browserType = lookupBrowserType(options);213  const launchOptions = {214    headless,215    executablePath216  };217  if (options.channel) launchOptions.channel = options.channel;218  const contextOptions = // Copy the device descriptor since we have to compare and modify the options.219  options.device ? { ...playwright.devices[options.device]220  } : {}; // In headful mode, use host device scale factor for things to look nice.221  // In headless, keep things the way it works in Playwright by default.222  // Assume high-dpi on MacOS. TODO: this is not perfect.223  if (!headless) contextOptions.deviceScaleFactor = _os.default.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue.224  if (browserType.name() === 'webkit' && process.platform === 'linux') {225    delete contextOptions.hasTouch;226    delete contextOptions.isMobile;227  }228  if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; // Proxy229  if (options.proxyServer) {230    launchOptions.proxy = {231      server: options.proxyServer232    };233    if (options.proxyBypass) launchOptions.proxy.bypass = options.proxyBypass;234  }235  const browser = await browserType.launch(launchOptions); // Viewport size236  if (options.viewportSize) {237    try {238      const [width, height] = options.viewportSize.split(',').map(n => parseInt(n, 10));239      contextOptions.viewport = {240        width,241        height242      };243    } catch (e) {244      console.log('Invalid window size format: use "width, height", for example --window-size=800,600');245      process.exit(0);246    }247  } // Geolocation248  if (options.geolocation) {249    try {250      const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim()));251      contextOptions.geolocation = {252        latitude,253        longitude254      };255    } catch (e) {256      console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"');257      process.exit(0);258    }259    contextOptions.permissions = ['geolocation'];260  } // User agent261  if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang262  if (options.lang) contextOptions.locale = options.lang; // Color scheme263  if (options.colorScheme) contextOptions.colorScheme = options.colorScheme; // Timezone264  if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage265  if (options.loadStorage) contextOptions.storageState = options.loadStorage;266  if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes.267  const context = await browser.newContext(contextOptions);268  let closingBrowser = false;269  async function closeBrowser() {270    // We can come here multiple times. For example, saving storage creates271    // a temporary page and we call closeBrowser again when that page closes.272    if (closingBrowser) return;273    closingBrowser = true;274    if (options.saveTrace) await context.tracing.stop({275      path: options.saveTrace276    });277    if (options.saveStorage) await context.storageState({278      path: options.saveStorage279    }).catch(e => null);280    await browser.close();281  }282  context.on('page', page => {283    page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed.284    page.on('close', () => {285      const hasPage = browser.contexts().some(context => context.pages().length > 0);286      if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed.287      closeBrowser().catch(e => null);288    });289  });290  if (options.timeout) {291    context.setDefaultTimeout(parseInt(options.timeout, 10));292    context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));293  }294  if (options.saveTrace) await context.tracing.start({295    screenshots: true,296    snapshots: true297  }); // Omit options that we add automatically for presentation purpose.298  delete launchOptions.headless;299  delete launchOptions.executablePath;300  delete contextOptions.deviceScaleFactor;301  return {302    browser,303    browserName: browserType.name(),304    context,305    contextOptions,306    launchOptions307  };308}309async function openPage(context, url) {310  const page = await context.newPage();311  if (url) {312    if (_fs.default.existsSync(url)) url = 'file://' + _path.default.resolve(url);else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:')) url = 'http://' + url;313    await page.goto(url);314  }315  return page;316}317async function open(options, url, language) {318  const {319    context,320    launchOptions,321    contextOptions322  } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH);323  await context._enableRecorder({324    language,325    launchOptions,326    contextOptions,327    device: options.device,328    saveStorage: options.saveStorage329  });330  await openPage(context, url);331  if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close()));332}333async function codegen(options, url, language, outputFile) {334  const {335    context,336    launchOptions,337    contextOptions338  } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH);339  await context._enableRecorder({340    language,341    launchOptions,342    contextOptions,343    device: options.device,344    saveStorage: options.saveStorage,345    startRecording: true,346    outputFile: outputFile ? _path.default.resolve(outputFile) : undefined347  });348  await openPage(context, url);349  if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close()));350}351async function waitForPage(page, captureOptions) {352  if (captureOptions.waitForSelector) {353    console.log(`Waiting for selector ${captureOptions.waitForSelector}...`);354    await page.waitForSelector(captureOptions.waitForSelector);355  }356  if (captureOptions.waitForTimeout) {357    console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`);358    await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10));359  }360}361async function screenshot(options, captureOptions, url, path) {362  const {363    browser,364    context365  } = await launchContext(options, true);366  console.log('Navigating to ' + url);367  const page = await openPage(context, url);368  await waitForPage(page, captureOptions);369  console.log('Capturing screenshot into ' + path);370  await page.screenshot({371    path,372    fullPage: !!captureOptions.fullPage373  });374  await browser.close();375}376async function pdf(options, captureOptions, url, path) {377  if (options.browser !== 'chromium') {378    console.error('PDF creation is only working with Chromium');379    process.exit(1);380  }381  const {382    browser,383    context384  } = await launchContext({ ...options,385    browser: 'chromium'386  }, true);387  console.log('Navigating to ' + url);388  const page = await openPage(context, url);389  await waitForPage(page, captureOptions);390  console.log('Saving as pdf into ' + path);391  await page.pdf({392    path393  });394  await browser.close();395}396function lookupBrowserType(options) {397  let name = options.browser;398  if (options.device) {399    const device = playwright.devices[options.device];400    name = device.defaultBrowserType;401  }402  let browserType;403  switch (name) {404    case 'chromium':405      browserType = playwright.chromium;406      break;407    case 'webkit':408      browserType = playwright.webkit;409      break;410    case 'firefox':411      browserType = playwright.firefox;412      break;413    case 'cr':414      browserType = playwright.chromium;415      break;416    case 'wk':417      browserType = playwright.webkit;418      break;419    case 'ff':420      browserType = playwright.firefox;421      break;422  }423  if (browserType) return browserType;424  _commander.program.help();425}426function validateOptions(options) {427  if (options.device && !(options.device in playwright.devices)) {428    console.log(`Device descriptor not found: '${options.device}', available devices are:`);429    for (const name in playwright.devices) console.log(`  "${name}"`);430    process.exit(0);431  }432  if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) {433    console.log('Invalid color scheme, should be one of "light", "dark"');434    process.exit(0);435  }436}437function logErrorAndExit(e) {438  console.error(e);439  process.exit(1);440}441function language() {442  return process.env.PW_CLI_TARGET_LANG || 'test';443}444function commandWithOpenOptions(command, description, options) {445  let result = _commander.program.command(command).description(description);446  for (const option of options) result = result.option(option[0], ...option.slice(1));447  return result.option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium').option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc').option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"').option('--device <deviceName>', 'emulate device, for example  "iPhone 11"').option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"').option('--ignore-https-errors', 'ignore https errors').option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage').option('--lang <language>', 'specify language / locale, for example "en-GB"').option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"').option('--proxy-bypass <bypass>', 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"').option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage').option('--save-trace <filename>', 'record a trace for the session and save it to a file').option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"').option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000').option('--user-agent <ua string>', 'specify user agent string').option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"');448}449async function launchGridServer(factoryPathOrPackageName, port, authToken) {450  if (!factoryPathOrPackageName) factoryPathOrPackageName = _path.default.join('..', 'grid', 'simpleGridFactory');451  let factory;452  try {453    factory = require(_path.default.resolve(factoryPathOrPackageName));454  } catch (e) {455    factory = require(factoryPathOrPackageName);456  }457  if (factory && typeof factory === 'object' && 'default' in factory) factory = factory['default'];458  if (!factory || !factory.launch || typeof factory.launch !== 'function') throw new Error('factory does not export `launch` method');459  factory.name = factory.name || factoryPathOrPackageName;460  const gridServer = new _gridServer.GridServer(factory, authToken);461  await gridServer.start(port);462  console.log('Grid server is running at ' + gridServer.urlPrefix());463}464function buildBasePlaywrightCLICommand(cliTargetLang) {465  switch (cliTargetLang) {466    case 'python':467      return `playwright`;468    case 'java':469      return `mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="...options.."`;470    case 'csharp':471      return `playwright`;472    default:473      return `npx playwright`;474  }...cli.js
Source:cli.js  
1#!/usr/bin/env node2/**3 * Copyright (c) Microsoft Corporation.4 *5 * Licensed under the Apache License, Version 2.0 (the "License");6 * you may not use this file except in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17/* eslint-disable no-console */18"use strict";19var _fs = _interopRequireDefault(require("fs"));20var _os = _interopRequireDefault(require("os"));21var _path = _interopRequireDefault(require("path"));22var _commander = _interopRequireDefault(require("commander"));23var _driver = require("./driver");24var _traceViewer = require("../server/trace/viewer/traceViewer");25var playwright = _interopRequireWildcard(require("../.."));26var _child_process = require("child_process");27var _registry = require("../utils/registry");28function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }29function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }30function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }31const packageJSON = require('../../package.json');32_commander.default.version('Version ' + packageJSON.version).name(process.env.PW_CLI_NAME || 'npx playwright');33commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []).action(function (url, command) {34  open(command, url, language()).catch(logErrorAndExit);35}).on('--help', function () {36  console.log('');37  console.log('Examples:');38  console.log('');39  console.log('  $ open');40  console.log('  $ open -b webkit https://example.com');41});42commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()]]).action(function (url, command) {43  codegen(command, url, command.target, command.output).catch(logErrorAndExit);44}).on('--help', function () {45  console.log('');46  console.log('Examples:');47  console.log('');48  console.log('  $ codegen');49  console.log('  $ codegen --target=python');50  console.log('  $ codegen -b webkit https://example.com');51});52_commander.default.command('debug <app> [args...]').description('run command in debug mode: disable timeout, open inspector').action(function (app, args) {53  (0, _child_process.spawn)(app, args, {54    env: { ...process.env,55      PWDEBUG: '1'56    },57    stdio: 'inherit'58  });59}).on('--help', function () {60  console.log('');61  console.log('Examples:');62  console.log('');63  console.log('  $ debug node test.js');64  console.log('  $ debug npm run test');65});66function suggestedBrowsersToInstall() {67  return _registry.registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', ');68}69function checkBrowsersToInstall(args) {70  const faultyArguments = [];71  const executables = [];72  for (const arg of args) {73    const executable = _registry.registry.findExecutable(arg);74    if (!executable || executable.installType === 'none') faultyArguments.push(arg);else executables.push(executable);75  }76  if (faultyArguments.length) {77    console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`);78    process.exit(1);79  }80  return executables;81}82_commander.default.command('install [browser...]').description('ensure browsers necessary for this version of Playwright are installed').option('--with-deps', 'install system dependencies for browsers').action(async function (args, command) {83  try {84    if (!args.length) {85      if (command.opts().withDeps) await _registry.registry.installDeps();86      await _registry.registry.install();87    } else {88      const executables = checkBrowsersToInstall(args);89      if (command.opts().withDeps) await _registry.registry.installDeps(executables);90      await _registry.registry.install(executables);91    }92  } catch (e) {93    console.log(`Failed to install browsers\n${e}`);94    process.exit(1);95  }96}).on('--help', function () {97  console.log(``);98  console.log(`Examples:`);99  console.log(`  - $ install`);100  console.log(`    Install default browsers.`);101  console.log(``);102  console.log(`  - $ install chrome firefox`);103  console.log(`    Install custom browsers, supports ${suggestedBrowsersToInstall()}.`);104});105_commander.default.command('install-deps [browser...]').description('install dependencies necessary to run browsers (will ask for sudo permissions)').action(async function (args) {106  try {107    if (!args.length) await _registry.registry.installDeps();else await _registry.registry.installDeps(checkBrowsersToInstall(args));108  } catch (e) {109    console.log(`Failed to install browser dependencies\n${e}`);110    process.exit(1);111  }112}).on('--help', function () {113  console.log(``);114  console.log(`Examples:`);115  console.log(`  - $ install-deps`);116  console.log(`    Install dependencies for default browsers.`);117  console.log(``);118  console.log(`  - $ install-deps chrome firefox`);119  console.log(`    Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`);120});121const browsers = [{122  alias: 'cr',123  name: 'Chromium',124  type: 'chromium'125}, {126  alias: 'ff',127  name: 'Firefox',128  type: 'firefox'129}, {130  alias: 'wk',131  name: 'WebKit',132  type: 'webkit'133}];134for (const {135  alias,136  name,137  type138} of browsers) {139  commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []).action(function (url, command) {140    open({ ...command,141      browser: type142    }, url, command.target).catch(logErrorAndExit);143  }).on('--help', function () {144    console.log('');145    console.log('Examples:');146    console.log('');147    console.log(`  $ ${alias} https://example.com`);148  });149}150commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)']]).action(function (url, filename, command) {151  screenshot(command, command, url, filename).catch(logErrorAndExit);152}).on('--help', function () {153  console.log('');154  console.log('Examples:');155  console.log('');156  console.log('  $ screenshot -b webkit https://example.com example.png');157});158commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf']]).action(function (url, filename, command) {159  pdf(command, command, url, filename).catch(logErrorAndExit);160}).on('--help', function () {161  console.log('');162  console.log('Examples:');163  console.log('');164  console.log('  $ pdf https://example.com example.pdf');165});166_commander.default.command('show-trace [trace]').option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium').description('Show trace viewer').action(function (trace, command) {167  if (command.browser === 'cr') command.browser = 'chromium';168  if (command.browser === 'ff') command.browser = 'firefox';169  if (command.browser === 'wk') command.browser = 'webkit';170  (0, _traceViewer.showTraceViewer)(trace, command.browser).catch(logErrorAndExit);171}).on('--help', function () {172  console.log('');173  console.log('Examples:');174  console.log('');175  console.log('  $ show-trace trace/directory');176});177if (!process.env.PW_CLI_TARGET_LANG) {178  let playwrightTestPackagePath = null;179  try {180    const isLocal = packageJSON.name === '@playwright/test' || process.env.PWTEST_CLI_ALLOW_TEST_COMMAND;181    if (isLocal) {182      playwrightTestPackagePath = '../test/cli';183    } else {184      playwrightTestPackagePath = require.resolve('@playwright/test/lib/test/cli', {185        paths: [__dirname, process.cwd()]186      });187    }188  } catch {}189  if (playwrightTestPackagePath) {190    require(playwrightTestPackagePath).addTestCommand(_commander.default);191  } else {192    const command = _commander.default.command('test').allowUnknownOption(true);193    command.description('Run tests with Playwright Test. Available in @playwright/test package.');194    command.action(async (args, opts) => {195      console.error('Please install @playwright/test package to use Playwright Test.');196      console.error('  npm install -D @playwright/test');197      process.exit(1);198    });199  }200}201if (process.argv[2] === 'run-driver') (0, _driver.runDriver)();else if (process.argv[2] === 'run-server') (0, _driver.runServer)(process.argv[3] ? +process.argv[3] : undefined, process.argv[4]).catch(logErrorAndExit);else if (process.argv[2] === 'print-api-json') (0, _driver.printApiJson)();else if (process.argv[2] === 'launch-server') (0, _driver.launchBrowserServer)(process.argv[3], process.argv[4]).catch(logErrorAndExit);else _commander.default.parse(process.argv);202async function launchContext(options, headless, executablePath) {203  validateOptions(options);204  const browserType = lookupBrowserType(options);205  const launchOptions = {206    headless,207    executablePath208  };209  if (options.channel) launchOptions.channel = options.channel;210  const contextOptions = // Copy the device descriptor since we have to compare and modify the options.211  options.device ? { ...playwright.devices[options.device]212  } : {}; // In headful mode, use host device scale factor for things to look nice.213  // In headless, keep things the way it works in Playwright by default.214  // Assume high-dpi on MacOS. TODO: this is not perfect.215  if (!headless) contextOptions.deviceScaleFactor = _os.default.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue.216  if (browserType.name() === 'webkit' && process.platform === 'linux') {217    delete contextOptions.hasTouch;218    delete contextOptions.isMobile;219  }220  if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined;221  contextOptions.acceptDownloads = true; // Proxy222  if (options.proxyServer) {223    launchOptions.proxy = {224      server: options.proxyServer225    };226  }227  const browser = await browserType.launch(launchOptions); // Viewport size228  if (options.viewportSize) {229    try {230      const [width, height] = options.viewportSize.split(',').map(n => parseInt(n, 10));231      contextOptions.viewport = {232        width,233        height234      };235    } catch (e) {236      console.log('Invalid window size format: use "width, height", for example --window-size=800,600');237      process.exit(0);238    }239  } // Geolocation240  if (options.geolocation) {241    try {242      const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim()));243      contextOptions.geolocation = {244        latitude,245        longitude246      };247    } catch (e) {248      console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"');249      process.exit(0);250    }251    contextOptions.permissions = ['geolocation'];252  } // User agent253  if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang254  if (options.lang) contextOptions.locale = options.lang; // Color scheme255  if (options.colorScheme) contextOptions.colorScheme = options.colorScheme; // Timezone256  if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage257  if (options.loadStorage) contextOptions.storageState = options.loadStorage;258  if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes.259  const context = await browser.newContext(contextOptions);260  let closingBrowser = false;261  async function closeBrowser() {262    // We can come here multiple times. For example, saving storage creates263    // a temporary page and we call closeBrowser again when that page closes.264    if (closingBrowser) return;265    closingBrowser = true;266    if (options.saveStorage) await context.storageState({267      path: options.saveStorage268    }).catch(e => null);269    await browser.close();270  }271  context.on('page', page => {272    page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed.273    page.on('close', () => {274      const hasPage = browser.contexts().some(context => context.pages().length > 0);275      if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed.276      closeBrowser().catch(e => null);277    });278  });279  if (options.timeout) {280    context.setDefaultTimeout(parseInt(options.timeout, 10));281    context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));282  } // Omit options that we add automatically for presentation purpose.283  delete launchOptions.headless;284  delete launchOptions.executablePath;285  delete contextOptions.deviceScaleFactor;286  delete contextOptions.acceptDownloads;287  return {288    browser,289    browserName: browserType.name(),290    context,291    contextOptions,292    launchOptions293  };294}295async function openPage(context, url) {296  const page = await context.newPage();297  if (url) {298    if (_fs.default.existsSync(url)) url = 'file://' + _path.default.resolve(url);else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:')) url = 'http://' + url;299    await page.goto(url);300  }301  return page;302}303async function open(options, url, language) {304  const {305    context,306    launchOptions,307    contextOptions308  } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH);309  await context._enableRecorder({310    language,311    launchOptions,312    contextOptions,313    device: options.device,314    saveStorage: options.saveStorage315  });316  await openPage(context, url);317  if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close()));318}319async function codegen(options, url, language, outputFile) {320  const {321    context,322    launchOptions,323    contextOptions324  } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH);325  await context._enableRecorder({326    language,327    launchOptions,328    contextOptions,329    device: options.device,330    saveStorage: options.saveStorage,331    startRecording: true,332    outputFile: outputFile ? _path.default.resolve(outputFile) : undefined333  });334  await openPage(context, url);335  if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close()));336}337async function waitForPage(page, captureOptions) {338  if (captureOptions.waitForSelector) {339    console.log(`Waiting for selector ${captureOptions.waitForSelector}...`);340    await page.waitForSelector(captureOptions.waitForSelector);341  }342  if (captureOptions.waitForTimeout) {343    console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`);344    await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10));345  }346}347async function screenshot(options, captureOptions, url, path) {348  const {349    browser,350    context351  } = await launchContext(options, true);352  console.log('Navigating to ' + url);353  const page = await openPage(context, url);354  await waitForPage(page, captureOptions);355  console.log('Capturing screenshot into ' + path);356  await page.screenshot({357    path,358    fullPage: !!captureOptions.fullPage359  });360  await browser.close();361}362async function pdf(options, captureOptions, url, path) {363  if (options.browser !== 'chromium') {364    console.error('PDF creation is only working with Chromium');365    process.exit(1);366  }367  const {368    browser,369    context370  } = await launchContext({ ...options,371    browser: 'chromium'372  }, true);373  console.log('Navigating to ' + url);374  const page = await openPage(context, url);375  await waitForPage(page, captureOptions);376  console.log('Saving as pdf into ' + path);377  await page.pdf({378    path379  });380  await browser.close();381}382function lookupBrowserType(options) {383  let name = options.browser;384  if (options.device) {385    const device = playwright.devices[options.device];386    name = device.defaultBrowserType;387  }388  let browserType;389  switch (name) {390    case 'chromium':391      browserType = playwright.chromium;392      break;393    case 'webkit':394      browserType = playwright.webkit;395      break;396    case 'firefox':397      browserType = playwright.firefox;398      break;399    case 'cr':400      browserType = playwright.chromium;401      break;402    case 'wk':403      browserType = playwright.webkit;404      break;405    case 'ff':406      browserType = playwright.firefox;407      break;408  }409  if (browserType) return browserType;410  _commander.default.help();411}412function validateOptions(options) {413  if (options.device && !(options.device in playwright.devices)) {414    console.log(`Device descriptor not found: '${options.device}', available devices are:`);415    for (const name in playwright.devices) console.log(`  "${name}"`);416    process.exit(0);417  }418  if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) {419    console.log('Invalid color scheme, should be one of "light", "dark"');420    process.exit(0);421  }422}423function logErrorAndExit(e) {424  console.error(e);425  process.exit(1);426}427function language() {428  return process.env.PW_CLI_TARGET_LANG || 'test';429}430function commandWithOpenOptions(command, description, options) {431  let result = _commander.default.command(command).description(description);432  for (const option of options) result = result.option(option[0], ...option.slice(1));433  return result.option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium').option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc').option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"').option('--device <deviceName>', 'emulate device, for example  "iPhone 11"').option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"').option('--ignore-https-errors', 'ignore https errors').option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage').option('--lang <language>', 'specify language / locale, for example "en-GB"').option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"').option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage').option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"').option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000').option('--user-agent <ua string>', 'specify user agent string').option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"');...cli.ts
Source:cli.ts  
...150      .command('show-trace [trace]')151      .option('--resources <dir>', 'load resources from shared folder')152      .description('Show trace viewer')153      .action(function(trace, command) {154        showTraceViewer(trace, command.resources).catch(logErrorAndExit);155      }).on('--help', function() {156        console.log('');157        console.log('Examples:');158        console.log('');159        console.log('  $ show-trace --resources=resources trace/file.trace');160        console.log('  $ show-trace trace/directory');161      });162}163if (process.argv[2] === 'run-driver')164  runServer();165else if (process.argv[2] === 'print-api-json')166  printApiJson();167else if (process.argv[2] === 'launch-server')168  launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit);...traceViewer.js
Source:traceViewer.js  
...30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.31 * See the License for the specific language governing permissions and32 * limitations under the License.33 */34async function showTraceViewer(traceUrl, browserName, headless = false, port) {35  if (traceUrl && !traceUrl.startsWith('http://') && !traceUrl.startsWith('https://') && !_fs.default.existsSync(traceUrl)) {36    console.error(`Trace file ${traceUrl} does not exist!`);37    process.exit(1);38  }39  const server = new _httpServer.HttpServer();40  server.routePrefix('/trace', (request, response) => {41    const url = new URL('http://localhost' + request.url);42    const relativePath = url.pathname.slice('/trace'.length);43    if (relativePath.startsWith('/file')) {44      try {45        return server.serveFile(request, response, url.searchParams.get('path'));46      } catch (e) {47        return false;48      }...Using AI Code Generation
1(asyncplaywright = require('playwright');2  const browser = await playwright.chromium.launch();3  const context = await browser.newContext();4( con)t page = await context.newPage();5  a>ait page.click('text=English');6  await page.click('text=Español');7  await page.click('text=日本語');8  await page.click('text=Deutsch');9  await page.click('text=Русский');10  await page.click('text=Français');11  await page.click('text=Italiano');12  await page.click('text=中文');13  await page.click('text=Português');14  await page.click('text=Polski');15  await page.click('text=한국어');16  await page.click('text=Nederlands');17  await page.click('text=Čeština');18  await page.click('text=العربية');19  await page.click('text=हिन्दी');20  await page.click('text=ไทย');21  await page.click('text= ü{kçe');22  await page.click('text=فارسی');23  await page.click('text=Română');24  await page.click('text=Українська');25  await page.click('text=עברית');26  await pge.clik('txt=Tiếng iệt');27  await page.clck('txt=Български');28  aait page.click('txt=Ελληνικά');29  await page.click('text=Српски');30  await page.click('text=Español');31  await page.click('text=日本語');32  await page.click('text=Deutsch');33  await page.click('text=Русский');34  await page.click('text=Français');35  await page.click('text=Italiano');36  await page.click('text=中文');37  await page.click('text=Português');38  await page.click('text=Polski');39  await page.click('text=한국어');40  await page.click('text=Nederlands');41  await page.click('text=Čeština');42  await page.click('text=العربية');Using AI Code Generation
1(async () => {2  const browser = await chromium.launch();3  const context = await browser.newContext();4  const page = await context.newPage();5  await page.click('text=Get started');6  await page.click('text=Docs');7  await page.click('text=API');8  await page.click('text=class: Browser');9  await browser.close();10  await browser._showTraceViewer();11})();Using AI Code Generation
1const { showTraceViewer 2  const browser = await chromium.launch();3  const context = await browser.newContext();4  const page = await context.newPage();5  await page.click('text=Get started');6  await page.click('text=Docs');7  await page.click('text=API');8  await page.click('text=class: Browser');9  await browser.close();10  await browser._showTraceViewer();11})();Using AI Code Generation
1const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');2const trace = require('./trace.json');3showTraceViewer(trace);4const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');5const trace = require('./trace.json');6showTraceViewer(trace);7const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');8const trace = require('./trace.json');9showTraceViewer(trace);10const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');11const trace = require('./trace.json');12showTraceViewer(trace);13const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');14const trace = require('./trace.json');15showTraceViewer(trace);16const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');17const trace = require('./trace.json');18showTraceViewer(trace);19const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');20const trace = require('./trace.json');21showTraceViewer(trace);22const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');23const trace = require('./trace.json');24showTraceViewer(trace);Using AI Code Generation
1const { showTraceViewer } = require('playwright/lib/utils/traceViewer');2(async () => {3  await showTraceViewer('trace.zip');4})();5const { showTraceViewer } = require('playwright/lib/utils/traceViewer');6(async () => {7  await showTraceViewer('trace.zip');8})();9const { showTraceViewer } = require('playwright/lib/utils/traceViewer');10(async () => {11  await showTraceViewer('trace.zip');12})();13const { showTraceViewer } = require('playwright/lib/utils/traceViewer');14(async () => {15  await showTraceViewer('trace.zip');16})();17const { showTraceViewer } = require('playwright/lib/utils/traceViewer');18(async () => {19  await showTraceViewer('trace.zip');20})();21const { showTraceViewer } = require('playwright/lib/utils/traceViewer');22(async () => {23  await showTraceViewer('trace.zip');24})();25const { showTraceViewer } = require('playwright/lib/utils/traceViewer');26(async () => {27  await showTraceViewer('trace.zip');28})();29const { showTraceViewer } = require('playwright/lib/utils/traceViewer');30(async () => {31  await showTraceViewer('trace.zip');32})();33const { showTraceViewer } = require('playwright/lib/utils/traceViewer');34(async () => {35  await showTraceViewer('trace.zip');36})();37const { showTraceViewer } = require('playwright/lib/utils/traceViewer');38(async () => {39  await showTraceViewer('trace.zip');40})();41const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');42const trace = require('./trace.json');43showTraceViewer(trace);44const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');45const trace = require('./trace.json');46showTraceViewer(trace);47const { showTraceViewer } = require('@playwright/test/lib/utils/traceViewer');48const trace = require('./trace.json');49showTraceViewer(trace);50const {Using AI Code Generation
1const { showTraceViewer } = require('playwright/lib/utils/traceViewer');2(async () => {3  await showTraceViewer('trace.zip');4})();5const { showTraceViewer } = require('playwright/lib/utils/traceViewer');6(async () => {7  await showTraceViewer('trace.zip');8})();9const { showTraceViewer } = require('playwright/lib/utils/traceViewer');10(async () => {11  await showTraceViewer('trace.zip');12})();13const { showTraceViewer } = require('playwright/lib/utils/traceViewer');14(async () => {15  await showTraceViewer('trace.zip');16})();17const { showTraceViewer } = require('playwright/lib/utils/traceViewer');18(async () => {19  await showTraceViewer('trace.zip');20})();21const { showTraceViewer } = require('playwright/lib/utils/traceViewer');22(async () => {23  await showTraceViewer('trace.zip');24})();25const { showTraceViewer } = require('playwright/lib/utils/traceViewer');26(async () => {27  await showTraceViewer('trace.zip');28})();29const { showTraceViewer } = require('playwright/lib/utils/traceViewer');30(async () => {31  await showTraceViewer('trace.zip');32})();33const { showTraceViewer } = require('playwright/lib/utils/traceViewer');34(async () => {35  await showTraceViewer('trace.zip');36})();37const { showTraceViewer } = require('playwright/lib/utils/traceViewer');38(async () => {39  await showTraceViewer('trace.zip');40})();LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
