Best JavaScript code snippet using playwright-internal
cli.ts
Source: cli.ts
...46 .description('mark docker image')47 .allowUnknownOption(true)48 .action(function(dockerImageNameTemplate) {49 assert(dockerImageNameTemplate, 'dockerImageNameTemplate is required');50 writeDockerVersion(dockerImageNameTemplate).catch(logErrorAndExit);51 });52commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', [])53 .action(function(url, options) {54 open(options, url, language()).catch(logErrorAndExit);55 })56 .addHelpText('afterAll', `57Examples:58 $ open $ open -b webkit https://example.com`);59commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions',60 [61 ['-o, --output <file name>', 'saves the generated script to a file'],62 ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()],63 ]).action(function(url, options) {64 codegen(options, url, options.target, options.output).catch(logErrorAndExit);...
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 _userAgent = require("../common/userAgent");28var _utils = require("../utils");29var _spawnAsync = require("../utils/spawnAsync");30var _gridAgent = require("../grid/gridAgent");31var _gridServer = require("../grid/gridServer");32var _server = require("../server");33function _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); }34function _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; }35function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }36const packageJSON = require('../../package.json');37_commander.program.version('Version ' + (process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version)).name(buildBasePlaywrightCLICommand(process.env.PW_LANG_NAME));38_commander.program.command('mark-docker-image > [args...]', {39 hidden: true40}).description('mark docker image').allowUnknownOption(true).action(function (dockerImageNameTemplate) {41 (0, _server.writeDockerVersion)(dockerImageNameTemplate);42});43commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []).action(function (url, options) {44 open(options, url, language()).catch(logErrorAndExit);45}).addHelpText('afterAll', `46Examples:47 $ open $ open -b webkit https://example.com`);48commandWithOpenOptions('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) {49 codegen(options, url, options.target, options.output).catch(logErrorAndExit);50}).addHelpText('afterAll', `51Examples:52 $ codegen53 $ codegen --target=python54 $ codegen -b webkit https://example.com`);55_commander.program.command('debug <app> [args...]', {56 hidden: true57}).description('run command in debug mode: disable timeout, open inspector').allowUnknownOption(true).action(function (app, options) {58 (0, _child_process.spawn)(app, options, {59 env: { ...process.env,60 PWDEBUG: '1'61 },62 stdio: 'inherit'63 });64}).addHelpText('afterAll', `65Examples:66 $ debug node test.js67 $ debug npm run test`);68function suggestedBrowsersToInstall() {69 return _server.registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', ');70}71function checkBrowsersToInstall(args) {72 const faultyArguments = [];73 const executables = [];74 for (const arg of args) {75 const executable = _server.registry.findExecutable(arg);76 if (!executable || executable.installType === 'none') faultyArguments.push(arg);else executables.push(executable);77 }78 if (faultyArguments.length) {79 console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`);80 process.exit(1);81 }82 return executables;83}84_commander.program.command('install [browser...]').description('ensure browsers necessary for this version of Playwright are installed').option('--with-deps', 'install system dependencies for browsers').option('--force', 'force reinstall of stable browser channels').action(async function (args, options) {85 const isLikelyNpxGlobal = process.argv.length >= 2 && process.argv[1].includes('_npx');86 if (isLikelyNpxGlobal) {87 console.error((0, _utils.wrapInASCIIBox)([`WARNING: It looks like you are running 'npx playwright install' without first`, `installing your project's dependencies.`, ``, `To avoid unexpected behavior, please install your dependencies first, and`, `then run Playwright's install command:`, ``, ` npm install`, ` npx playwright install`, ``, `If your project does not yet depend on Playwright, first install the`, `applicable npm package (most commonly @playwright/test), and`, `then run Playwright's install command to download the browsers:`, ``, ` npm install @playwright/test`, ` npx playwright install`, ``].join('\n'), 1));88 }89 try {90 if (!args.length) {91 const executables = _server.registry.defaultExecutables();92 if (options.withDeps) await _server.registry.installDeps(executables, false);93 await _server.registry.install(executables, false94 /* forceReinstall */95 );96 } else {97 const installDockerImage = args.some(arg => arg === 'docker-image');98 args = args.filter(arg => arg !== 'docker-image');99 if (installDockerImage) {100 const imageName = `mcr.microsoft.com/playwright:v${(0, _userAgent.getPlaywrightVersion)()}-focal`;101 const {102 code103 } = await (0, _spawnAsync.spawnAsync)('docker', ['pull', imageName], {104 stdio: 'inherit'105 });106 if (code !== 0) {107 console.log('Failed to pull docker image');108 process.exit(1);109 }110 }111 const executables = checkBrowsersToInstall(args);112 if (options.withDeps) await _server.registry.installDeps(executables, false);113 await _server.registry.install(executables, !!options.force114 /* forceReinstall */115 );116 }117 } catch (e) {118 console.log(`Failed to install browsers\n${e}`);119 process.exit(1);120 }121}).addHelpText('afterAll', `122Examples:123 - $ install124 Install default browsers.125 - $ install chrome firefox126 Install custom browsers, supports ${suggestedBrowsersToInstall()}.`);127_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) {128 try {129 if (!args.length) await _server.registry.installDeps(_server.registry.defaultExecutables(), !!options.dryRun);else await _server.registry.installDeps(checkBrowsersToInstall(args), !!options.dryRun);130 } catch (e) {131 console.log(`Failed to install browser dependencies\n${e}`);132 process.exit(1);133 }134}).addHelpText('afterAll', `135Examples:136 - $ install-deps137 Install dependencies for default browsers.138 - $ install-deps chrome firefox139 Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`);140const browsers = [{141 alias: 'cr',142 name: 'Chromium',143 type: 'chromium'144}, {145 alias: 'ff',146 name: 'Firefox',147 type: 'firefox'148}, {149 alias: 'wk',150 name: 'WebKit',151 type: 'webkit'152}];153for (const {154 alias,155 name,156 type157} of browsers) {158 commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []).action(function (url, options) {159 open({ ...options,160 browser: type161 }, url, options.target).catch(logErrorAndExit);162 }).addHelpText('afterAll', `163Examples:164 $ ${alias} https://example.com`);165}166commandWithOpenOptions('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) {167 screenshot(command, command, url, filename).catch(logErrorAndExit);168}).addHelpText('afterAll', `169Examples:170 $ screenshot -b webkit https://example.com example.png`);171commandWithOpenOptions('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) {172 pdf(options, options, url, filename).catch(logErrorAndExit);173}).addHelpText('afterAll', `174Examples:175 $ pdf https://example.com example.pdf`);176_commander.program.command('experimental-grid-server', {177 hidden: true178}).option('--port <port>', 'grid port; defaults to 3333').option('--address <address>', 'address of the server').option('--agent-factory <factory>', 'path to grid agent factory or npm package').option('--auth-token <authToken>', 'optional authentication token').action(function (options) {179 launchGridServer(options.agentFactory, options.port || 3333, options.address, options.authToken);180});181_commander.program.command('experimental-grid-agent', {182 hidden: true183}).requiredOption('--agent-id <agentId>', 'agent ID').requiredOption('--grid-url <gridURL>', 'grid URL').action(function (options) {184 (0, _gridAgent.launchGridAgent)(options.agentId, options.gridUrl);185});186_commander.program.command('run-driver', {187 hidden: true188}).action(function (options) {189 (0, _driver.runDriver)();190});191_commander.program.command('run-server', {192 hidden: true193}).option('--port <port>', 'Server port').option('--path <path>', 'Endpoint Path', '/').option('--max-clients <maxClients>', 'Maximum clients').option('--no-socks-proxy', 'Disable Socks Proxy').action(function (options) {194 (0, _driver.runServer)(options.port ? +options.port : undefined, options.path, options.maxClients ? +options.maxClients : Infinity, options.socksProxy).catch(logErrorAndExit);195});196_commander.program.command('print-api-json', {197 hidden: true198}).action(function (options) {199 (0, _driver.printApiJson)();200});201_commander.program.command('launch-server', {202 hidden: true203}).requiredOption('--browser <browserName>', 'Browser name, one of "chromium", "firefox" or "webkit"').option('--config <path-to-config-file>', 'JSON file with launchServer options').action(function (options) {204 (0, _driver.launchBrowserServer)(options.browser, options.config);205});206_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 (traces, options) {207 if (options.browser === 'cr') options.browser = 'chromium';208 if (options.browser === 'ff') options.browser = 'firefox';209 if (options.browser === 'wk') options.browser = 'webkit';210 (0, _traceViewer.showTraceViewer)(traces, options.browser, false, 9322).catch(logErrorAndExit);211}).addHelpText('afterAll', `212Examples:213 $ show-trace https://example.com/trace.zip`);214if (!process.env.PW_LANG_NAME) {215 let playwrightTestPackagePath = null;216 try {217 playwrightTestPackagePath = require.resolve('@playwright/test/lib/cli', {218 paths: [__dirname, process.cwd()]219 });220 } catch {}221 if (playwrightTestPackagePath) {222 require(playwrightTestPackagePath).addTestCommand(_commander.program);223 require(playwrightTestPackagePath).addShowReportCommand(_commander.program);224 require(playwrightTestPackagePath).addListFilesCommand(_commander.program);225 } else {226 {227 const command = _commander.program.command('test').allowUnknownOption(true);228 command.description('Run tests with Playwright Test. Available in @playwright/test package.');229 command.action(async () => {230 console.error('Please install @playwright/test package to use Playwright Test.');231 console.error(' npm install -D @playwright/test');232 process.exit(1);233 });234 }235 {236 const command = _commander.program.command('show-report').allowUnknownOption(true);237 command.description('Show Playwright Test HTML report. Available in @playwright/test package.');238 command.action(async () => {239 console.error('Please install @playwright/test package to use Playwright Test.');240 console.error(' npm install -D @playwright/test');241 process.exit(1);242 });243 }244 }245}246_commander.program.parse(process.argv);247async function launchContext(options, headless, executablePath) {248 validateOptions(options);249 const browserType = lookupBrowserType(options);250 const launchOptions = {251 headless,252 executablePath253 };254 if (options.channel) launchOptions.channel = options.channel;255 const contextOptions = // Copy the device descriptor since we have to compare and modify the options.256 options.device ? { ...playwright.devices[options.device]257 } : {}; // In headful mode, use host device scale factor for things to look nice.258 // In headless, keep things the way it works in Playwright by default.259 // Assume high-dpi on MacOS. TODO: this is not perfect.260 if (!headless) contextOptions.deviceScaleFactor = _os.default.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue.261 if (browserType.name() === 'webkit' && process.platform === 'linux') {262 delete contextOptions.hasTouch;263 delete contextOptions.isMobile;264 }265 if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; // Proxy266 if (options.proxyServer) {267 launchOptions.proxy = {268 server: options.proxyServer269 };270 if (options.proxyBypass) launchOptions.proxy.bypass = options.proxyBypass;271 }272 const browser = await browserType.launch(launchOptions); // Viewport size273 if (options.viewportSize) {274 try {275 const [width, height] = options.viewportSize.split(',').map(n => parseInt(n, 10));276 contextOptions.viewport = {277 width,278 height279 };280 } catch (e) {281 console.log('Invalid window size format: use "width, height", for example --window-size=800,600');282 process.exit(0);283 }284 } // Geolocation285 if (options.geolocation) {286 try {287 const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim()));288 contextOptions.geolocation = {289 latitude,290 longitude291 };292 } catch (e) {293 console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"');294 process.exit(0);295 }296 contextOptions.permissions = ['geolocation'];297 } // User agent298 if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang299 if (options.lang) contextOptions.locale = options.lang; // Color scheme300 if (options.colorScheme) contextOptions.colorScheme = options.colorScheme; // Timezone301 if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage302 if (options.loadStorage) contextOptions.storageState = options.loadStorage;303 if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes.304 const context = await browser.newContext(contextOptions);305 let closingBrowser = false;306 async function closeBrowser() {307 // We can come here multiple times. For example, saving storage creates308 // a temporary page and we call closeBrowser again when that page closes.309 if (closingBrowser) return;310 closingBrowser = true;311 if (options.saveTrace) await context.tracing.stop({312 path: options.saveTrace313 });314 if (options.saveStorage) await context.storageState({315 path: options.saveStorage316 }).catch(e => null);317 await browser.close();318 }319 context.on('page', page => {320 page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed.321 page.on('close', () => {322 const hasPage = browser.contexts().some(context => context.pages().length > 0);323 if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed.324 closeBrowser().catch(e => null);325 });326 });327 if (options.timeout) {328 context.setDefaultTimeout(parseInt(options.timeout, 10));329 context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));330 }331 if (options.saveTrace) await context.tracing.start({332 screenshots: true,333 snapshots: true334 }); // Omit options that we add automatically for presentation purpose.335 delete launchOptions.headless;336 delete launchOptions.executablePath;337 delete contextOptions.deviceScaleFactor;338 return {339 browser,340 browserName: browserType.name(),341 context,342 contextOptions,343 launchOptions344 };345}346async function openPage(context, url) {347 const page = await context.newPage();348 if (url) {349 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;350 await page.goto(url);351 }352 return page;353}354async function open(options, url, language) {355 const {356 context,357 launchOptions,358 contextOptions359 } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH);360 await context._enableRecorder({361 language,362 launchOptions,363 contextOptions,364 device: options.device,365 saveStorage: options.saveStorage366 });367 await openPage(context, url);368 if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close()));369}370async function codegen(options, url, language, outputFile) {371 const {372 context,373 launchOptions,374 contextOptions375 } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH);376 await context._enableRecorder({377 language,378 launchOptions,379 contextOptions,380 device: options.device,381 saveStorage: options.saveStorage,382 startRecording: true,383 outputFile: outputFile ? _path.default.resolve(outputFile) : undefined384 });385 await openPage(context, url);386 if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close()));387}388async function waitForPage(page, captureOptions) {389 if (captureOptions.waitForSelector) {390 console.log(`Waiting for selector ${captureOptions.waitForSelector}...`);391 await page.waitForSelector(captureOptions.waitForSelector);392 }393 if (captureOptions.waitForTimeout) {394 console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`);395 await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10));396 }397}398async function screenshot(options, captureOptions, url, path) {399 const {400 browser,401 context402 } = await launchContext(options, true);403 console.log('Navigating to ' + url);404 const page = await openPage(context, url);405 await waitForPage(page, captureOptions);406 console.log('Capturing screenshot into ' + path);407 await page.screenshot({408 path,409 fullPage: !!captureOptions.fullPage410 });411 await browser.close();412}413async function pdf(options, captureOptions, url, path) {414 if (options.browser !== 'chromium') {415 console.error('PDF creation is only working with Chromium');416 process.exit(1);417 }418 const {419 browser,420 context421 } = await launchContext({ ...options,422 browser: 'chromium'423 }, true);424 console.log('Navigating to ' + url);425 const page = await openPage(context, url);426 await waitForPage(page, captureOptions);427 console.log('Saving as pdf into ' + path);428 await page.pdf({429 path430 });431 await browser.close();432}433function lookupBrowserType(options) {434 let name = options.browser;435 if (options.device) {436 const device = playwright.devices[options.device];437 name = device.defaultBrowserType;438 }439 let browserType;440 switch (name) {441 case 'chromium':442 browserType = playwright.chromium;443 break;444 case 'webkit':445 browserType = playwright.webkit;446 break;447 case 'firefox':448 browserType = playwright.firefox;449 break;450 case 'cr':451 browserType = playwright.chromium;452 break;453 case 'wk':454 browserType = playwright.webkit;455 break;456 case 'ff':457 browserType = playwright.firefox;458 break;459 }460 if (browserType) return browserType;461 _commander.program.help();462}463function validateOptions(options) {464 if (options.device && !(options.device in playwright.devices)) {465 console.log(`Device descriptor not found: '${options.device}', available devices are:`);466 for (const name in playwright.devices) console.log(` "${name}"`);467 process.exit(0);468 }469 if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) {470 console.log('Invalid color scheme, should be one of "light", "dark"');471 process.exit(0);472 }473}474function logErrorAndExit(e) {475 console.error(e);476 process.exit(1);477}478function language() {479 return process.env.PW_LANG_NAME || 'test';480}481function commandWithOpenOptions(command, description, options) {482 let result = _commander.program.command(command).description(description);483 for (const option of options) result = result.option(option[0], ...option.slice(1));484 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"');485}486async function launchGridServer(factoryPathOrPackageName, port, address, authToken) {487 if (!factoryPathOrPackageName) factoryPathOrPackageName = _path.default.join('..', 'grid', 'simpleGridFactory');488 let factory;489 try {490 factory = require(_path.default.resolve(factoryPathOrPackageName));491 } catch (e) {492 factory = require(factoryPathOrPackageName);493 }494 if (factory && typeof factory === 'object' && 'default' in factory) factory = factory['default'];495 if (!factory || !factory.launch || typeof factory.launch !== 'function') throw new Error('factory does not export `launch` method');496 factory.name = factory.name || factoryPathOrPackageName;497 const gridServer = new _gridServer.GridServer(factory, authToken, address);498 await gridServer.start(port);499 console.log('Grid server is running at ' + gridServer.urlPrefix());500}501function buildBasePlaywrightCLICommand(cliTargetLang) {502 switch (cliTargetLang) {503 case 'python':504 return `playwright`;505 case 'java':506 return `mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="...options.."`;507 case 'csharp':508 return `pwsh bin\\Debug\\netX\\playwright.ps1`;509 default:510 return `npx playwright`;511 }...
dependencies.js
Source: dependencies.js
...39 */40const BIN_DIRECTORY = _path.default.join(__dirname, '..', '..', '..', 'bin');41const packageJSON = require('../../../package.json');42const dockerVersionFilePath = '/ms-playwright/.docker-info';43async function writeDockerVersion(dockerImageNameTemplate) {44 await _fs.default.promises.mkdir(_path.default.dirname(dockerVersionFilePath), {45 recursive: true46 });47 await _fs.default.promises.writeFile(dockerVersionFilePath, JSON.stringify({48 driverVersion: packageJSON.version,49 dockerImageName: dockerImageNameTemplate.replace('%version%', packageJSON.version)50 }, null, 2), 'utf8'); // Make sure version file is globally accessible.51 await _fs.default.promises.chmod(dockerVersionFilePath, 0o777);52}53async function readDockerVersion() {54 return await _fs.default.promises.readFile(dockerVersionFilePath, 'utf8').then(text => JSON.parse(text)).catch(e => null);55}56const checkExecutable = filePath => _fs.default.promises.access(filePath, _fs.default.constants.X_OK).then(() => true).catch(e => false);57function isSupportedWindowsVersion() {...
index.js
Source: index.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5Object.defineProperty(exports, "DispatcherConnection", {6 enumerable: true,7 get: function () {8 return _dispatcher.DispatcherConnection;9 }10});11Object.defineProperty(exports, "PlaywrightDispatcher", {12 enumerable: true,13 get: function () {14 return _playwrightDispatcher.PlaywrightDispatcher;15 }16});17Object.defineProperty(exports, "Registry", {18 enumerable: true,19 get: function () {20 return _registry.Registry;21 }22});23Object.defineProperty(exports, "Root", {24 enumerable: true,25 get: function () {26 return _dispatcher.Root;27 }28});29Object.defineProperty(exports, "createPlaywright", {30 enumerable: true,31 get: function () {32 return _playwright.createPlaywright;33 }34});35Object.defineProperty(exports, "installBrowsersForNpmInstall", {36 enumerable: true,37 get: function () {38 return _registry.installBrowsersForNpmInstall;39 }40});41Object.defineProperty(exports, "installDefaultBrowsersForNpmInstall", {42 enumerable: true,43 get: function () {44 return _registry.installDefaultBrowsersForNpmInstall;45 }46});47Object.defineProperty(exports, "registry", {48 enumerable: true,49 get: function () {50 return _registry.registry;51 }52});53Object.defineProperty(exports, "registryDirectory", {54 enumerable: true,55 get: function () {56 return _registry.registryDirectory;57 }58});59Object.defineProperty(exports, "writeDockerVersion", {60 enumerable: true,61 get: function () {62 return _registry.writeDockerVersion;63 }64});65var _registry = require("./registry");66var _dispatcher = require("./dispatchers/dispatcher");67var _playwrightDispatcher = require("./dispatchers/playwrightDispatcher");...
Using AI Code Generation
1const { writeDockerVersion } = require('playwright/lib/utils/docker');2const { writeDockerVersion } = require('playwright/lib/utils/docker');3 throw err;4 at Function.Module._resolveFilename (node:internal/modules/cjs/loader:941:15)5 at Function.Module._load (node:internal/modules/cjs/loader:774:27)6 at Module.require (node:internal/modules/cjs/loader:1005:19)7 at require (node:internal/modules/cjs/helpers:93:18)8 at Object.<anonymous> (/Users/xxx/xxx/test.js:1:21)9 at Module._compile (node:internal/modules/cjs/loader:1108:14)10 at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)11 at Module.load (node:internal/modules/cjs/loader:973:32)12 at Function.Module._load (node:internal/modules/cjs/loader:813:14)13 at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {14}
Using AI Code Generation
1const playwright = require('playwright');2const { writeDockerVersion } = require('playwright/lib/server/browserType');3(async () => {4 await writeDockerVersion(playwright.chromium, '1.2.3');5 await writeDockerVersion(playwright.firefox, '4.5.6');6 await writeDockerVersion(playwright.webkit, '7.8.9');7})();
Using AI Code Generation
1const playwright = require('playwright');2const { writeDockerVersion } = require('playwright/lib/server/docker');3writeDockerVersion(playwright.chromium, '1.2.3');4writeDockerVersion(playwright.firefox, '1.2.3');5writeDockerVersion(playwright.webkit, '1.2.3');6### `writeDockerVersion(browser: BrowserType, version: string)`
Using AI Code Generation
1const { writeDockerVersion } = require('playwright/lib/utils/registry');2writeDockerVersion('1.1.1');3const { writeDockerVersion } = require('playwright/lib/utils/registry');4writeDockerVersion('1.1.1');5const { writeDockerVersion } = require('playwright/lib/utils/registry');6writeDockerVersion('1.1.1');7const { writeDockerVersion } = require('playwright/lib/utils/registry');8writeDockerVersion('1.1.1');9const { writeDockerVersion } = require('playwright/lib/utils/registry');10writeDockerVersion('1.1.1');11const { writeDockerVersion } = require('playwright/lib/utils/registry');12writeDockerVersion('1.1.1');13const { writeDockerVersion } = require('playwright/lib/utils/registry');14writeDockerVersion('1.1.1');15const { writeDockerVersion } = require('playwright/lib/utils/registry');16writeDockerVersion('1.1.1');17const { writeDockerVersion } = require('playwright/lib/utils/registry');18writeDockerVersion('1.1.1');19const { writeDockerVersion } = require('playwright/lib/utils/registry');20writeDockerVersion('1.1.1');21const { writeDockerVersion }
Using AI Code Generation
1const { writeDockerVersion } = require('playwright-core/lib/server/playwright');2writeDockerVersion('1.0.0');3const { writeDockerVersion } = require('playwright-core/lib/server/playwright');4writeDockerVersion('1.0.0');5const { writeDockerVersion } = require('playwright-core/lib/server/playwright');6writeDockerVersion('1.0.0');7const { writeDockerVersion } = require('playwright-core/lib/server/playwright');8writeDockerVersion('1.0.0');9const { writeDockerVersion } = require('playwright-core/lib/server/playwright');10writeDockerVersion('1.0.0');11const { writeDockerVersion } = require('playwright-core/lib/server/playwright');12writeDockerVersion('1.0.0');13const { writeDockerVersion } = require('playwright-core/lib/server/playwright');14writeDockerVersion('1.0.0');15const { writeDockerVersion } = require('playwright-core/lib/server/playwright');16writeDockerVersion('1.0.0');17const { writeDockerVersion } = require('playwright-core/lib/server/playwright');18writeDockerVersion('1.0.0');19const { writeDockerVersion } = require('playwright-core/lib/server/playwright');20writeDockerVersion('1.0.0');21const { writeDockerVersion } = require('playwright-core/lib/server/playwright');22writeDockerVersion('1.0.0');23const { writeDockerVersion } = require('playwright-core
Using AI Code Generation
1const { Internal } = require('playwright');2await Internal.writeDockerVersion('1.12.3');3const { Internal } = require('playwright');4await Internal.writeDockerVersion('1.12.3');5const { Internal } = require('playwright');6await Internal.writeDockerVersion('1.12.3');7const { Internal } = require('playwright');8await Internal.writeDockerVersion('1.12.3');9const { Internal } = require('playwright');10await Internal.writeDockerVersion('1.12.3');11const { Internal } = require('playwright');12await Internal.writeDockerVersion('1.12.3');13const { Internal } = require('playwright');14await Internal.writeDockerVersion('1.12.3');15const { Internal } = require('playwright');16await Internal.writeDockerVersion('1.12.3');17const { Internal } = require('playwright');18await Internal.writeDockerVersion('1.12.3');19const { Internal } = require('playwright');20await Internal.writeDockerVersion('1.12.3');21const { Internal } = require('playwright');22await Internal.writeDockerVersion('1.12.3');23const { Internal } = require('playwright');
Using AI Code Generation
1const playwright = require('playwright');2const { writeDockerVersion } = require('playwright/lib/utils/registry');3writeDockerVersion(playwright, 'chromium', '1.2.3');4const playwright = require('playwright');5const { writeDockerVersion } = require('playwright/lib/utils/registry');6writeDockerVersion(playwright, 'chromium', '1.2.3');7const playwright = require('playwright');8const { writeDockerVersion } = require('playwright/lib/utils/registry');9writeDockerVersion(playwright, 'chromium', '1.2.3');10const playwright = require('playwright');11const { writeDockerVersion } = require('playwright/lib/utils/registry');12writeDockerVersion(playwright, 'chromium', '1.2.3');13const playwright = require('playwright');14const { writeDockerVersion } = require('playwright/lib/utils/registry');15writeDockerVersion(playwright, 'chromium', '1.2.3');16const playwright = require('playwright');17const { writeDockerVersion } = require('playwright/lib/utils/registry');18writeDockerVersion(playwright, 'chromium', '1.2.3');19const playwright = require('playwright');20const { writeDockerVersion } = require('playwright/lib/utils/registry');21writeDockerVersion(playwright, 'chromium', '1.2.3');22const playwright = require('playwright');23const { writeDockerVersion } = require('playwright/lib/utils/registry');24writeDockerVersion(playwright, 'chromium', '1.2.3');
Using AI Code Generation
1const { writeDockerVersion } = require('playwright/lib/utils/dockerVersion');2writeDockerVersion('1.0.0');3const playwright = require('playwright');4(async () => {5 const browser = await playwright.chromium.launch({6 });7})();8module.exports = {9 use: {10 },11};
Using AI Code Generation
1const playwright = require('playwright');2const { writeDockerVersion } = playwright._internal;3const fs = require('fs');4(async () => {5 const browser = await playwright.chromium.launch();6 const version = await browser.version();7 writeDockerVersion(version);8 fs.writeFileSync('docker-version.txt', version);9 await browser.close();10})();11RUN npm install playwright@$(cat docker-version.txt)
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!