Best JavaScript code snippet using playwright-internal
cli.ts
Source:cli.ts
...223 .requiredOption('--agent-id <agentId>', 'agent ID')224 .requiredOption('--grid-url <gridURL>', 'grid URL')225 .option('--run-id <github run_id>', 'Workflow run_id')226 .action(function(options) {227 launchGridAgent(options.agentId, options.gridUrl, options.runId);228 });229program230 .command('run-driver', { hidden: true })231 .action(function(options) {232 runDriver();233 });234program235 .command('run-server', { hidden: true })236 .option('--port <port>', 'Server port')237 .option('--path <path>', 'Endpoint Path', '/')238 .option('--max-clients <maxClients>', 'Maximum clients')239 .option('--no-socks-proxy', 'Disable Socks Proxy')240 .action(function(options) {241 runServer(options.port ? +options.port : undefined, options.path, options.maxClients ? +options.maxClients : Infinity, options.socksProxy).catch(logErrorAndExit);...
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 = 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");28var _utils = require("../utils/utils");29var _gridAgent = require("../grid/gridAgent");30var _gridServer = require("../grid/gridServer");31function _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); }32function _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; }33function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }34const packageJSON = require('../../package.json');35_commander.program.version('Version ' + packageJSON.version).name(process.env.PW_CLI_NAME || 'npx playwright');36commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []).action(function (url, options) {37 open(options, url, language()).catch(logErrorAndExit);38}).addHelpText('afterAll', `39Examples:40 $ open $ open -b webkit https://example.com`);41commandWithOpenOptions('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) {42 codegen(options, url, options.target, options.output).catch(logErrorAndExit);43}).addHelpText('afterAll', `44Examples:45 $ codegen46 $ codegen --target=python47 $ codegen -b webkit https://example.com`);48_commander.program.command('debug <app> [args...]', {49 hidden: true50}).description('run command in debug mode: disable timeout, open inspector').allowUnknownOption(true).action(function (app, options) {51 (0, _child_process.spawn)(app, options, {52 env: { ...process.env,53 PWDEBUG: '1'54 },55 stdio: 'inherit'56 });57}).addHelpText('afterAll', `58Examples:59 $ debug node test.js60 $ debug npm run test`);61function suggestedBrowsersToInstall() {62 return _registry.registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', ');63}64function checkBrowsersToInstall(args) {65 const faultyArguments = [];66 const executables = [];67 for (const arg of args) {68 const executable = _registry.registry.findExecutable(arg);69 if (!executable || executable.installType === 'none') faultyArguments.push(arg);else executables.push(executable);70 }71 if (faultyArguments.length) {72 console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`);73 process.exit(1);74 }75 return executables;76}77_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) {78 try {79 if (!args.length) {80 const executables = _registry.registry.defaultExecutables();81 if (options.withDeps) await _registry.registry.installDeps(executables);82 await _registry.registry.install(executables);83 } else {84 const installDockerImage = args.some(arg => arg === 'docker-image');85 args = args.filter(arg => arg !== 'docker-image');86 if (installDockerImage) {87 const imageName = `mcr.microsoft.com/playwright:v${(0, _utils.getPlaywrightVersion)()}`;88 const {89 code90 } = await (0, _utils.spawnAsync)('docker', ['pull', imageName], {91 stdio: 'inherit'92 });93 if (code !== 0) {94 console.log('Failed to pull docker image');95 process.exit(1);96 }97 }98 const executables = checkBrowsersToInstall(args);99 if (options.withDeps) await _registry.registry.installDeps(executables);100 await _registry.registry.install(executables);101 }102 } catch (e) {103 console.log(`Failed to install browsers\n${e}`);104 process.exit(1);105 }106}).addHelpText('afterAll', `107Examples:108 - $ install109 Install default browsers.110 - $ install chrome firefox111 Install custom browsers, supports ${suggestedBrowsersToInstall()}.`);112_commander.program.command('install-deps [browser...]').description('install dependencies necessary to run browsers (will ask for sudo permissions)').action(async function (args) {113 try {114 if (!args.length) await _registry.registry.installDeps(_registry.registry.defaultExecutables());else await _registry.registry.installDeps(checkBrowsersToInstall(args));115 } catch (e) {116 console.log(`Failed to install browser dependencies\n${e}`);117 process.exit(1);118 }119}).addHelpText('afterAll', `120Examples:121 - $ install-deps122 Install dependencies for default browsers.123 - $ install-deps chrome firefox124 Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`);125const browsers = [{126 alias: 'cr',127 name: 'Chromium',128 type: 'chromium'129}, {130 alias: 'ff',131 name: 'Firefox',132 type: 'firefox'133}, {134 alias: 'wk',135 name: 'WebKit',136 type: 'webkit'137}];138for (const {139 alias,140 name,141 type142} of browsers) {143 commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []).action(function (url, options) {144 open({ ...options,145 browser: type146 }, url, options.target).catch(logErrorAndExit);147 }).addHelpText('afterAll', `148Examples:149 $ ${alias} https://example.com`);150}151commandWithOpenOptions('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) {152 screenshot(command, command, url, filename).catch(logErrorAndExit);153}).addHelpText('afterAll', `154Examples:155 $ screenshot -b webkit https://example.com example.png`);156commandWithOpenOptions('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) {157 pdf(options, options, url, filename).catch(logErrorAndExit);158}).addHelpText('afterAll', `159Examples:160 $ pdf https://example.com example.pdf`);161_commander.program.command('experimental-grid-server', {162 hidden: true163}).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) {164 launchGridServer(options.agentFactory, options.port || 3333, options.authToken);165});166_commander.program.command('experimental-grid-agent', {167 hidden: true168}).requiredOption('--agent-id <agentId>', 'agent ID').requiredOption('--grid-url <gridURL>', 'grid URL').action(function (options) {169 (0, _gridAgent.launchGridAgent)(options.agentId, options.gridUrl);170});171_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) {172 if (options.browser === 'cr') options.browser = 'chromium';173 if (options.browser === 'ff') options.browser = 'firefox';174 if (options.browser === 'wk') options.browser = 'webkit';175 (0, _traceViewer.showTraceViewer)(trace, options.browser, false, 9322).catch(logErrorAndExit);176}).addHelpText('afterAll', `177Examples:178 $ show-trace https://example.com/trace.zip`);179if (!process.env.PW_CLI_TARGET_LANG) {180 let playwrightTestPackagePath = null;181 try {182 playwrightTestPackagePath = require.resolve('@playwright/test/lib/cli', {183 paths: [__dirname, process.cwd()]184 });185 } catch {}186 if (playwrightTestPackagePath) {187 require(playwrightTestPackagePath).addTestCommand(_commander.program);188 require(playwrightTestPackagePath).addShowReportCommand(_commander.program);189 } else {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}199if (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);200async function launchContext(options, headless, executablePath) {201 validateOptions(options);202 const browserType = lookupBrowserType(options);203 const launchOptions = {204 headless,205 executablePath206 };207 if (options.channel) launchOptions.channel = options.channel;208 const contextOptions = // Copy the device descriptor since we have to compare and modify the options.209 options.device ? { ...playwright.devices[options.device]210 } : {}; // In headful mode, use host device scale factor for things to look nice.211 // In headless, keep things the way it works in Playwright by default.212 // Assume high-dpi on MacOS. TODO: this is not perfect.213 if (!headless) contextOptions.deviceScaleFactor = _os.default.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue.214 if (browserType.name() === 'webkit' && process.platform === 'linux') {215 delete contextOptions.hasTouch;216 delete contextOptions.isMobile;217 }218 if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined;219 contextOptions.acceptDownloads = true; // Proxy220 if (options.proxyServer) {221 launchOptions.proxy = {222 server: options.proxyServer223 };224 }225 const browser = await browserType.launch(launchOptions); // Viewport size226 if (options.viewportSize) {227 try {228 const [width, height] = options.viewportSize.split(',').map(n => parseInt(n, 10));229 contextOptions.viewport = {230 width,231 height232 };233 } catch (e) {234 console.log('Invalid window size format: use "width, height", for example --window-size=800,600');235 process.exit(0);236 }237 } // Geolocation238 if (options.geolocation) {239 try {240 const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim()));241 contextOptions.geolocation = {242 latitude,243 longitude244 };245 } catch (e) {246 console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"');247 process.exit(0);248 }249 contextOptions.permissions = ['geolocation'];250 } // User agent251 if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang252 if (options.lang) contextOptions.locale = options.lang; // Color scheme253 if (options.colorScheme) contextOptions.colorScheme = options.colorScheme; // Timezone254 if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage255 if (options.loadStorage) contextOptions.storageState = options.loadStorage;256 if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes.257 const context = await browser.newContext(contextOptions);258 let closingBrowser = false;259 async function closeBrowser() {260 // We can come here multiple times. For example, saving storage creates261 // a temporary page and we call closeBrowser again when that page closes.262 if (closingBrowser) return;263 closingBrowser = true;264 if (options.saveTrace) await context.tracing.stop({265 path: options.saveTrace266 });267 if (options.saveStorage) await context.storageState({268 path: options.saveStorage269 }).catch(e => null);270 await browser.close();271 }272 context.on('page', page => {273 page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed.274 page.on('close', () => {275 const hasPage = browser.contexts().some(context => context.pages().length > 0);276 if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed.277 closeBrowser().catch(e => null);278 });279 });280 if (options.timeout) {281 context.setDefaultTimeout(parseInt(options.timeout, 10));282 context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));283 }284 if (options.saveTrace) await context.tracing.start({285 screenshots: true,286 snapshots: true287 }); // Omit options that we add automatically for presentation purpose.288 delete launchOptions.headless;289 delete launchOptions.executablePath;290 delete contextOptions.deviceScaleFactor;291 delete contextOptions.acceptDownloads;292 return {293 browser,294 browserName: browserType.name(),295 context,296 contextOptions,297 launchOptions298 };299}300async function openPage(context, url) {301 const page = await context.newPage();302 if (url) {303 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;304 await page.goto(url);305 }306 return page;307}308async function open(options, url, language) {309 const {310 context,311 launchOptions,312 contextOptions313 } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH);314 await context._enableRecorder({315 language,316 launchOptions,317 contextOptions,318 device: options.device,319 saveStorage: options.saveStorage320 });321 await openPage(context, url);322 if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close()));323}324async function codegen(options, url, language, outputFile) {325 const {326 context,327 launchOptions,328 contextOptions329 } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH);330 await context._enableRecorder({331 language,332 launchOptions,333 contextOptions,334 device: options.device,335 saveStorage: options.saveStorage,336 startRecording: true,337 outputFile: outputFile ? _path.default.resolve(outputFile) : undefined338 });339 await openPage(context, url);340 if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close()));341}342async function waitForPage(page, captureOptions) {343 if (captureOptions.waitForSelector) {344 console.log(`Waiting for selector ${captureOptions.waitForSelector}...`);345 await page.waitForSelector(captureOptions.waitForSelector);346 }347 if (captureOptions.waitForTimeout) {348 console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`);349 await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10));350 }351}352async function screenshot(options, captureOptions, url, path) {353 const {354 browser,355 context356 } = await launchContext(options, true);357 console.log('Navigating to ' + url);358 const page = await openPage(context, url);359 await waitForPage(page, captureOptions);360 console.log('Capturing screenshot into ' + path);361 await page.screenshot({362 path,363 fullPage: !!captureOptions.fullPage364 });365 await browser.close();366}367async function pdf(options, captureOptions, url, path) {368 if (options.browser !== 'chromium') {369 console.error('PDF creation is only working with Chromium');370 process.exit(1);371 }372 const {373 browser,374 context375 } = await launchContext({ ...options,376 browser: 'chromium'377 }, true);378 console.log('Navigating to ' + url);379 const page = await openPage(context, url);380 await waitForPage(page, captureOptions);381 console.log('Saving as pdf into ' + path);382 await page.pdf({383 path384 });385 await browser.close();386}387function lookupBrowserType(options) {388 let name = options.browser;389 if (options.device) {390 const device = playwright.devices[options.device];391 name = device.defaultBrowserType;392 }393 let browserType;394 switch (name) {395 case 'chromium':396 browserType = playwright.chromium;397 break;398 case 'webkit':399 browserType = playwright.webkit;400 break;401 case 'firefox':402 browserType = playwright.firefox;403 break;404 case 'cr':405 browserType = playwright.chromium;406 break;407 case 'wk':408 browserType = playwright.webkit;409 break;410 case 'ff':411 browserType = playwright.firefox;412 break;413 }414 if (browserType) return browserType;415 _commander.program.help();416}417function validateOptions(options) {418 if (options.device && !(options.device in playwright.devices)) {419 console.log(`Device descriptor not found: '${options.device}', available devices are:`);420 for (const name in playwright.devices) console.log(` "${name}"`);421 process.exit(0);422 }423 if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) {424 console.log('Invalid color scheme, should be one of "light", "dark"');425 process.exit(0);426 }427}428function logErrorAndExit(e) {429 console.error(e);430 process.exit(1);431}432function language() {433 return process.env.PW_CLI_TARGET_LANG || 'test';434}435function commandWithOpenOptions(command, description, options) {436 let result = _commander.program.command(command).description(description);437 for (const option of options) result = result.option(option[0], ...option.slice(1));438 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('--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"');439}440async function launchGridServer(factoryPathOrPackageName, port, authToken) {441 if (!factoryPathOrPackageName) factoryPathOrPackageName = _path.default.join('..', 'grid', 'simpleGridFactory');442 let factory;443 try {444 factory = require(_path.default.resolve(factoryPathOrPackageName));445 } catch (e) {446 factory = require(factoryPathOrPackageName);447 }448 if (factory && typeof factory === 'object' && 'default' in factory) factory = factory['default'];449 if (!factory || !factory.launch || typeof factory.launch !== 'function') throw new Error('factory does not export `launch` method');450 factory.name = factory.name || factoryPathOrPackageName;451 const gridServer = new _gridServer.GridServer(factory, authToken);452 await gridServer.start(port);453 console.log('Grid server is running at ' + gridServer.urlPrefix());...
gridAgent.js
Source:gridAgent.js
...22 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.23 * See the License for the specific language governing permissions and24 * limitations under the License.25 */26function launchGridAgent(agentId, gridURL) {27 const log = (0, _debug.default)(`[agent ${agentId}]`);28 log('created');29 const params = new URLSearchParams();30 params.set('pwVersion', (0, _utils.getPlaywrightVersion)(true31 /* majorMinorOnly */32 ));33 params.set('agentId', agentId);34 const ws = new _ws.default(gridURL + `/registerAgent?` + params.toString());35 ws.on('message', workerId => {36 log('Worker requested ' + workerId);37 (0, _child_process.fork)(require.resolve('./gridWorker.js'), [gridURL, agentId, workerId], {38 detached: true39 });40 });...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launchGridAgent({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 await browser.close();8})();9const playwright = require('playwright');10(async () => {11 const browser = await playwright.chromium.launchGridAgent({12 });13 const context = await browser.newContext();14 const page = await context.newPage();15 await browser.close();16})();17const playwright = require('playwright');18(async () => {19 const browser = await playwright.chromium.launchGridAgent({20 credentials: { username: 'user', password: 'pass' },21 });22 const context = await browser.newContext();23 const page = await context.newPage();24 await browser.close();25})();26const playwright = require('playwright');27(async () => {28 const browser = await playwright.chromium.launchGridAgent({29 proxy: {30 },31 });32 const context = await browser.newContext();33 const page = await context.newPage();34 await browser.close();35})();36const playwright = require('playwright');37(async () => {38 const browser = await playwright.chromium.launchGridAgent({39 extraHTTPHeaders: {40 },41 });42 const context = await browser.newContext();43 const page = await context.newPage();44 await browser.close();45})();
Using AI Code Generation
1const playwright = require('playwright');2const { launchGridAgent } = require('playwright/lib/server/gridAgent');3(async () => {4 const browserServer = await playwright.chromium.launchServer({5 });6 const browserWSEndpoint = browserServer.wsEndpoint();7 launchGridAgent({8 });9})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browserServer = await playwright.chromium.launchGridAgent({4 });5 const browser = await browserServer.connect();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();11const playwright = require('playwright');12(async () => {13 const browser = await playwright.chromium.launch({14 });15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.screenshot({ path: 'example.png' });18 await browser.close();19})();20const playwright = require('playwright');21(async () => {22 const browser = await playwright.chromium.launch({ slowMo: 2000 });23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.screenshot({ path: 'example.png' });26 await browser.close();27})();28const playwright = require('playwright');29(async () => {30 const browser = await playwright.chromium.launch({ headless: false });31 const context = await browser.newContext();32 const page = await context.newPage();33 await page.goto('https
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const page = await browser.newPage();4 await page.screenshot({ path: `example.png` });5 await browser.close();6})();7### `const browserServer = await launchGridAgent(options)`
Using AI Code Generation
1const { launchGridAgent } = require('@playwright/test/lib/server/gridAgent');2const { chromium } = require('playwright');3const { devices } = require('playwright');4const iPhone = devices['iPhone 11 Pro'];5const { webkit } = require('playwright');6const { firefox } = require('playwright');7const { createServer } = require('http');8const path = require('path');9const fs = require('fs');10const os = require('os');11const { chromium: chromiumLauncher } = require('playwright');12const { webkit: webkitLauncher } = require('playwright');13const { firefox: firefoxLauncher } = require('playwright');14const browserType = 'chromium';15const browserType1 = 'webkit';16const browserType2 = 'firefox';17const browserType3 = 'chromium';18const browserType4 = 'webkit';19const browserType5 = 'firefox';20const browserType6 = 'chromium';21const browserType7 = 'webkit';22const browserType8 = 'firefox';23const browserType9 = 'chromium';24const browserType10 = 'webkit';25const browserType11 = 'firefox';26const browserType12 = 'chromium';27const browserType13 = 'webkit';28const browserType14 = 'firefox';29const browserType15 = 'chromium';30const browserType16 = 'webkit';31const browserType17 = 'firefox';32const browserType18 = 'chromium';33const browserType19 = 'webkit';34const browserType20 = 'firefox';35const browserType21 = 'chromium';36const browserType22 = 'webkit';37const browserType23 = 'firefox';38const browserType24 = 'chromium';39const browserType25 = 'webkit';40const browserType26 = 'firefox';41const browserType27 = 'chromium';42const browserType28 = 'webkit';43const browserType29 = 'firefox';44const browserType30 = 'chromium';45const browserType31 = 'webkit';46const browserType32 = 'firefox';47const browserType33 = 'chromium';48const browserType34 = 'webkit';49const browserType35 = 'firefox';50const browserType36 = 'chromium';51const browserType37 = 'webkit';52const browserType38 = 'firefox';53const browserType39 = 'chromium';54const browserType40 = 'webkit';55const browserType41 = 'firefox';
Using AI Code Generation
1const { chromium } = require('playwright');2const { launchGridAgent } = require('playwright-core/lib/server/agent');3const { startServer } = require('playwright-core/lib/server/server');4const { createGuid } = require('playwright-core/lib/utils/utils');5(async () => {6 const server = await startServer({
Using AI Code Generation
1const playwright = require('playwright');2const { launchGridAgent } = require('playwright/lib/server/gridAgent');3const gridServerPort = 1337;4const browserName = 'chromium';5const serverOptions = { port: gridServerPort };6const agentOptions = { browserName, serverOptions };7(async () => {8 const { browserServer, wsEndpoint } = await launchGridAgent(agentOptions);9 console.log(`Server running at ${gridServerUrl}`);10 console.log(`Connect your browser using ${wsEndpoint}`);11 await browserServer.close();12})();13const playwright = require('playwright');14const { launchBrowserOnRemoteMachine } = require('playwright/lib/server/gridClient');15const browserName = 'chromium';16const remoteConnectionOptions = { wsEndpoint: `${gridServerUrl}/browser?name=${browserName}` };17const browser = await launchBrowserOnRemoteMachine(remoteConnectionOptions);18const context = await browser.newContext();19const page = await context.newPage();20await page.screenshot({ path: 'example.png' });21await browser.close();22const playwright = require('playwright');23const { launchBrowserOnRemoteMachine } = require('playwright/lib/server/gridClient');24const browserName = 'chromium';25const remoteConnectionOptions = { wsEndpoint: `${gridServerUrl}/browser?name=${browserName}` };26const launchOptions = { headless: false };27const browser = await launchBrowserOnRemoteMachine(remoteConnectionOptions, launchOptions);28const context = await browser.newContext();29const page = await context.newPage();30await page.screenshot({ path: 'example.png' });31await browser.close();
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!!