How to use commandWithOpenOptions method in Playwright Internal

Best JavaScript code snippet using playwright-internal

innerCli.js

Source:innerCli.js Github

copy

Full Screen

...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');...

Full Screen

Full Screen

cli.js

Source:cli.js Github

copy

Full Screen

...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"');...

Full Screen

Full Screen

cli.ts

Source:cli.ts Github

copy

Full Screen

...32import { allBrowserNames } from '../utils/registry';33program34 .version('Version ' + require('../../package.json').version)35 .name('npx playwright');36commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', [])37 .action(function(url, command) {38 open(command, url, language()).catch(logErrorAndExit);39 })40 .on('--help', function() {41 console.log('');42 console.log('Examples:');43 console.log('');44 console.log(' $ open');45 console.log(' $ open -b webkit https://example.com');46 });47commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions',48 [49 ['-o, --output <file name>', 'saves the generated script to a file'],50 ['--target <language>', `language to use, one of javascript, python, python-async, csharp`, language()],51 ]).action(function(url, command) {52 codegen(command, url, command.target, command.output).catch(logErrorAndExit);53}).on('--help', function() {54 console.log('');55 console.log('Examples:');56 console.log('');57 console.log(' $ codegen');58 console.log(' $ codegen --target=python');59 console.log(' $ codegen -b webkit https://example.com');60});61program62 .command('debug <app> [args...]')63 .description('run command in debug mode: disable timeout, open inspector')64 .action(function(app, args) {65 spawn(app, args, {66 env: { ...process.env, PWDEBUG: '1' },67 stdio: 'inherit'68 });69 }).on('--help', function() {70 console.log('');71 console.log('Examples:');72 console.log('');73 console.log(' $ debug node test.js');74 console.log(' $ debug npm run test');75 });76program77 .command('install [browserType...]')78 .description('ensure browsers necessary for this version of Playwright are installed')79 .action(async function(browserType) {80 try {81 const allBrowsers = new Set(allBrowserNames);82 for (const type of browserType) {83 if (!allBrowsers.has(type)) {84 console.log(`Invalid browser name: '${type}'. Expecting one of: ${allBrowserNames.map(name => `'${name}'`).join(', ')}`);85 process.exit(1);86 }87 }88 if (browserType.length && browserType.includes('chromium'))89 browserType = browserType.concat('ffmpeg');90 await installBrowsers(browserType.length ? browserType : undefined);91 } catch (e) {92 console.log(`Failed to install browsers\n${e}`);93 process.exit(1);94 }95 });96program97 .command('install-deps [browserType...]')98 .description('install dependencies necessary to run browsers (will ask for sudo permissions)')99 .action(async function(browserType) {100 try {101 await installDeps(browserType);102 } catch (e) {103 console.log(`Failed to install browser dependencies\n${e}`);104 process.exit(1);105 }106 });107const browsers = [108 { alias: 'cr', name: 'Chromium', type: 'chromium' },109 { alias: 'ff', name: 'Firefox', type: 'firefox' },110 { alias: 'wk', name: 'WebKit', type: 'webkit' },111];112for (const {alias, name, type} of browsers) {113 commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, [])114 .action(function(url, command) {115 open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit);116 }).on('--help', function() {117 console.log('');118 console.log('Examples:');119 console.log('');120 console.log(` $ ${alias} https://example.com`);121 });122}123commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot',124 [125 ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'],126 ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'],127 ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'],128 ]).action(function(url, filename, command) {129 screenshot(command, command, url, filename).catch(logErrorAndExit);130}).on('--help', function() {131 console.log('');132 console.log('Examples:');133 console.log('');134 console.log(' $ screenshot -b webkit https://example.com example.png');135});136commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf',137 [138 ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'],139 ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'],140 ]).action(function(url, filename, command) {141 pdf(command, command, url, filename).catch(logErrorAndExit);142}).on('--help', function() {143 console.log('');144 console.log('Examples:');145 console.log('');146 console.log(' $ pdf https://example.com example.pdf');147});148if (process.env.PWTRACE) {149 program150 .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);169else170 program.parse(process.argv);171type Options = {172 browser: string;173 channel?: string;174 colorScheme?: string;175 device?: string;176 geolocation?: string;177 lang?: string;178 loadStorage?: string;179 proxyServer?: string;180 saveStorage?: string;181 timeout: string;182 timezone?: string;183 viewportSize?: string;184 userAgent?: string;185};186type CaptureOptions = {187 waitForSelector?: string;188 waitForTimeout?: string;189 fullPage: boolean;190};191async function launchContext(options: Options, headless: boolean): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> {192 validateOptions(options);193 const browserType = lookupBrowserType(options);194 const launchOptions: LaunchOptions = { headless };195 if (options.channel)196 launchOptions.channel = options.channel as any;197 const contextOptions: BrowserContextOptions =198 // Copy the device descriptor since we have to compare and modify the options.199 options.device ? { ...playwright.devices[options.device] } : {};200 // In headful mode, use host device scale factor for things to look nice.201 // In headless, keep things the way it works in Playwright by default.202 // Assume high-dpi on MacOS. TODO: this is not perfect.203 if (!headless)204 contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1;205 // Work around the WebKit GTK scrolling issue.206 if (browserType.name() === 'webkit' && process.platform === 'linux') {207 delete contextOptions.hasTouch;208 delete contextOptions.isMobile;209 }210 if (contextOptions.isMobile && browserType.name() === 'firefox')211 contextOptions.isMobile = undefined;212 if (process.env.PWTRACE)213 (contextOptions as any)._traceDir = path.join(process.cwd(), '.trace');214 // Proxy215 if (options.proxyServer) {216 launchOptions.proxy = {217 server: options.proxyServer218 };219 }220 const browser = await browserType.launch(launchOptions);221 // Viewport size222 if (options.viewportSize) {223 try {224 const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10));225 contextOptions.viewport = { width, height };226 } catch (e) {227 console.log('Invalid window size format: use "width, height", for example --window-size=800,600');228 process.exit(0);229 }230 }231 // Geolocation232 if (options.geolocation) {233 try {234 const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim()));235 contextOptions.geolocation = {236 latitude,237 longitude238 };239 } catch (e) {240 console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"');241 process.exit(0);242 }243 contextOptions.permissions = ['geolocation'];244 }245 // User agent246 if (options.userAgent)247 contextOptions.userAgent = options.userAgent;248 // Lang249 if (options.lang)250 contextOptions.locale = options.lang;251 // Color scheme252 if (options.colorScheme)253 contextOptions.colorScheme = options.colorScheme as 'dark' | 'light';254 // Timezone255 if (options.timezone)256 contextOptions.timezoneId = options.timezone;257 // Storage258 if (options.loadStorage)259 contextOptions.storageState = options.loadStorage;260 // Close app when the last window closes.261 const context = await browser.newContext(contextOptions);262 let closingBrowser = false;263 async function closeBrowser() {264 // We can come here multiple times. For example, saving storage creates265 // a temporary page and we call closeBrowser again when that page closes.266 if (closingBrowser)267 return;268 closingBrowser = true;269 if (options.saveStorage)270 await context.storageState({ path: options.saveStorage }).catch(e => null);271 await browser.close();272 }273 context.on('page', page => {274 page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed.275 page.on('close', () => {276 const hasPage = browser.contexts().some(context => context.pages().length > 0);277 if (hasPage)278 return;279 // Avoid the error when the last page is closed because the browser has been closed.280 closeBrowser().catch(e => null);281 });282 });283 if (options.timeout) {284 context.setDefaultTimeout(parseInt(options.timeout, 10));285 context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));286 }287 // Omit options that we add automatically for presentation purpose.288 delete launchOptions.headless;289 delete contextOptions.deviceScaleFactor;290 return { browser, browserName: browserType.name(), context, contextOptions, launchOptions };291}292async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> {293 const page = await context.newPage();294 if (url) {295 if (fs.existsSync(url))296 url = 'file://' + path.resolve(url);297 else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:'))298 url = 'http://' + url;299 await page.goto(url);300 }301 return page;302}303async function open(options: Options, url: string | undefined, language: string) {304 const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS);305 await context._enableRecorder({306 language,307 launchOptions,308 contextOptions,309 device: options.device,310 saveStorage: options.saveStorage,311 });312 await openPage(context, url);313 if (process.env.PWTEST_CLI_EXIT)314 await Promise.all(context.pages().map(p => p.close()));315}316async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) {317 const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS);318 if (process.env.PWTRACE)319 contextOptions._traceDir = path.join(process.cwd(), '.trace');320 await context._enableRecorder({321 language,322 launchOptions,323 contextOptions,324 device: options.device,325 saveStorage: options.saveStorage,326 startRecording: true,327 outputFile: outputFile ? path.resolve(outputFile) : undefined328 });329 await openPage(context, url);330 if (process.env.PWTEST_CLI_EXIT)331 await Promise.all(context.pages().map(p => p.close()));332}333async function waitForPage(page: Page, captureOptions: CaptureOptions) {334 if (captureOptions.waitForSelector) {335 console.log(`Waiting for selector ${captureOptions.waitForSelector}...`);336 await page.waitForSelector(captureOptions.waitForSelector);337 }338 if (captureOptions.waitForTimeout) {339 console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`);340 await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10));341 }342}343async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) {344 const { browser, context } = await launchContext(options, true);345 console.log('Navigating to ' + url);346 const page = await openPage(context, url);347 await waitForPage(page, captureOptions);348 console.log('Capturing screenshot into ' + path);349 await page.screenshot({ path, fullPage: !!captureOptions.fullPage });350 await browser.close();351}352async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) {353 if (options.browser !== 'chromium') {354 console.error('PDF creation is only working with Chromium');355 process.exit(1);356 }357 const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true);358 console.log('Navigating to ' + url);359 const page = await openPage(context, url);360 await waitForPage(page, captureOptions);361 console.log('Saving as pdf into ' + path);362 await page.pdf!({ path });363 await browser.close();364}365function lookupBrowserType(options: Options): BrowserType {366 let name = options.browser;367 if (options.device) {368 const device = playwright.devices[options.device];369 name = device.defaultBrowserType;370 }371 let browserType: any;372 switch (name) {373 case 'chromium': browserType = playwright.chromium; break;374 case 'webkit': browserType = playwright.webkit; break;375 case 'firefox': browserType = playwright.firefox; break;376 case 'cr': browserType = playwright.chromium; break;377 case 'wk': browserType = playwright.webkit; break;378 case 'ff': browserType = playwright.firefox; break;379 }380 if (browserType)381 return browserType;382 program.help();383}384function validateOptions(options: Options) {385 if (options.device && !(options.device in playwright.devices)) {386 console.log(`Device descriptor not found: '${options.device}', available devices are:`);387 for (const name in playwright.devices)388 console.log(` "${name}"`);389 process.exit(0);390 }391 if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) {392 console.log('Invalid color scheme, should be one of "light", "dark"');393 process.exit(0);394 }395}396function logErrorAndExit(e: Error) {397 console.error(e);398 process.exit(1);399}400function language(): string {401 return process.env.PW_CLI_TARGET_LANG || 'javascript';402}403function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command {404 let result = program.command(command).description(description);405 for (const option of options)406 result = result.option(option[0], ...option.slice(1));407 return result408 .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium')409 .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc')410 .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"')411 .option('--device <deviceName>', 'emulate device, for example "iPhone 11"')412 .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"')413 .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage')414 .option('--lang <language>', 'specify language / locale, for example "en-GB"')415 .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"')416 .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage')417 .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"')...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('input[name="q"]');7 await page.keyboard.type('Playwright');8 await page.keyboard.press('Enter');9 await page.waitForNavigation();10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch({ headless: false });15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.click('input[name="q"]');18 await page.keyboard.type('Playwright');19 await page.keyboard.press('Enter');20 await page.waitForNavigation();21 await browser.close();22})();23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch({ headless: false });26 const context = await browser.newContext();27 const page = await context.newPage();28 await page.click('input[name="q"]');29 await page.keyboard.type('Playwright');30 await page.keyboard.press('Enter');31 await page.waitForNavigation();32 await browser.close();33})();34const { chromium } = require('playwright');35(async () => {36 const browser = await chromium.launch({ headless: false });37 const context = await browser.newContext();38 const page = await context.newPage();39 await page.click('input[name="q"]');40 await page.keyboard.type('Playwright');41 await page.keyboard.press('Enter');42 await page.waitForNavigation();43 await browser.close();44})();45const { chromium } = require('playwright');46(async () => {47 const browser = await chromium.launch({ headless: false });48 const context = await browser.newContext();49 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const element = await page.$('text=Get Started');6 await element.click();7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 const element = await page.$('text=Get Started');14 await element.click();15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const page = await browser.newPage();21 const element = await page.$('text=Get Started');22 await element.click();23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const page = await browser.newPage();29 const element = await page.$('text=Get Started');30 await element.click();31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const page = await browser.newPage();37 const element = await page.$('text=Get Started');38 await element.click();39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const page = await browser.newPage();45 const element = await page.$('text=Get Started');46 await element.click();

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const { commandWithOpenOptions } = require('playwright/lib/server/browserType');3(async () => {4 const browser = await playwright.chromium.launch({5 });6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();11module.exports = {12 use: {13 },14};

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch({headless: false});12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: `example.png` });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch({headless: false});20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: `example.png` });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch({headless: false});28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: `example.png` });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch({headless: false});36 const context = await browser.newContext();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { commandWithOpenOptions } = require('playwright/lib/server/browserType');2(async () => {3 const browserType = 'chromium';4 const browserOptions = {5 };6 const contextOptions = {7 };8 const pageOptions = {9 };10 const result = await commandWithOpenOptions(11 );12 console.log(result);13})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2const {commandWithOpenOptions} = require('playwright/lib/server/browserType');3const {launchProcess} = require('playwright/lib/server/processLauncher');4(async () => {5 const { launchedProcess, gracefullyClose } = await launchProcess({6 executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',

Full Screen

Using AI Code Generation

copy

Full Screen

1const { commandWithOpenOptions } = require('playwright/lib/internal/transport');2await commandWithOpenOptions('open', {3 options: {4 }5});6const { commandWithOpenOptions } = require('playwright/lib/internal/transport');7await commandWithOpenOptions('open', {8 options: {9 }10});11const { commandWithOpenOptions } = require('playwright/lib/internal/transport');12await commandWithOpenOptions('open', {13 options: {14 }15});16const { commandWithOpenOptions } = require('playwright/lib/internal/transport');17await commandWithOpenOptions('open', {18 options: {19 }20});21const { commandWithOpenOptions } = require('playwright/lib/internal/transport');22await commandWithOpenOptions('open', {23 options: {24 }25});26const { commandWithOpenOptions } = require('playwright/lib/internal/transport');27await commandWithOpenOptions('open', {28 options: {29 }30});31const { commandWithOpenOptions } = require('playwright/lib/internal/transport');32await commandWithOpenOptions('open', {33 options: {34 }35});36const { commandWithOpenOptions } = require('playwright/lib/internal

Full Screen

Using AI Code Generation

copy

Full Screen

1const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');2const options = {3};4await commandWithOpenOptions(options);5const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');6const options = {7};8await commandWithOpenOptions(options);9const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');10const options = {11};12await commandWithOpenOptions(options);13const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');14const options = {15};16await commandWithOpenOptions(options);17const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');18const options = {19};20await commandWithOpenOptions(options);21const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');22const options = {23};24await commandWithOpenOptions(options);25const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');26const options = {27};28await commandWithOpenOptions(options);29const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');30const options = {31};32await commandWithOpenOptions(options);33const { commandWithOpenOptions } = require('@playwright/test/lib/internal/runner');34const options = {35};36await commandWithOpenOptions(options);

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful