Best JavaScript code snippet using playwright-internal
browserType.js
Source:browserType.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.BrowserType = void 0;6var _fs = _interopRequireDefault(require("fs"));7var os = _interopRequireWildcard(require("os"));8var _path = _interopRequireDefault(require("path"));9var _browserContext = require("./browserContext");10var _registry = require("../utils/registry");11var _transport = require("./transport");12var _processLauncher = require("../utils/processLauncher");13var _pipeTransport = require("./pipeTransport");14var _progress = require("./progress");15var _timeoutSettings = require("../utils/timeoutSettings");16var _utils = require("../utils/utils");17var _helper = require("./helper");18var _debugLogger = require("../utils/debugLogger");19var _instrumentation = require("./instrumentation");20function _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); }21function _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; }22function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }23/**24 * Copyright (c) Microsoft Corporation.25 *26 * Licensed under the Apache License, Version 2.0 (the "License");27 * you may not use this file except in compliance with the License.28 * You may obtain a copy of the License at29 *30 * http://www.apache.org/licenses/LICENSE-2.031 *32 * Unless required by applicable law or agreed to in writing, software33 * distributed under the License is distributed on an "AS IS" BASIS,34 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.35 * See the License for the specific language governing permissions and36 * limitations under the License.37 */38const ARTIFACTS_FOLDER = _path.default.join(os.tmpdir(), 'playwright-artifacts-');39class BrowserType extends _instrumentation.SdkObject {40 constructor(browserName, playwrightOptions) {41 super(playwrightOptions.rootSdkObject, 'browser-type');42 this._name = void 0;43 this._playwrightOptions = void 0;44 this.attribution.browserType = this;45 this._playwrightOptions = playwrightOptions;46 this._name = browserName;47 }48 executablePath() {49 return _registry.registry.findExecutable(this._name).executablePath(this._playwrightOptions.sdkLanguage) || '';50 }51 name() {52 return this._name;53 }54 async launch(metadata, options, protocolLogger) {55 options = this._validateLaunchOptions(options);56 const controller = new _progress.ProgressController(metadata, this);57 controller.setLogName('browser');58 const browser = await controller.run(progress => {59 const seleniumHubUrl = options.__testHookSeleniumRemoteURL || process.env.SELENIUM_REMOTE_URL;60 if (seleniumHubUrl) return this._launchWithSeleniumHub(progress, seleniumHubUrl, options);61 return this._innerLaunchWithRetries(progress, options, undefined, _helper.helper.debugProtocolLogger(protocolLogger)).catch(e => {62 throw this._rewriteStartupError(e);63 });64 }, _timeoutSettings.TimeoutSettings.timeout(options));65 return browser;66 }67 async launchPersistentContext(metadata, userDataDir, options) {68 options = this._validateLaunchOptions(options);69 const controller = new _progress.ProgressController(metadata, this);70 const persistent = options;71 controller.setLogName('browser');72 const browser = await controller.run(progress => {73 return this._innerLaunchWithRetries(progress, options, persistent, _helper.helper.debugProtocolLogger(), userDataDir).catch(e => {74 throw this._rewriteStartupError(e);75 });76 }, _timeoutSettings.TimeoutSettings.timeout(options));77 return browser._defaultContext;78 }79 async _innerLaunchWithRetries(progress, options, persistent, protocolLogger, userDataDir) {80 try {81 return this._innerLaunch(progress, options, persistent, protocolLogger, userDataDir);82 } catch (error) {83 // @see https://github.com/microsoft/playwright/issues/521484 const errorMessage = typeof error === 'object' && typeof error.message === 'string' ? error.message : '';85 if (errorMessage.includes('Inconsistency detected by ld.so')) {86 progress.log(`<restarting browser due to hitting race condition in glibc>`);87 return this._innerLaunch(progress, options, persistent, protocolLogger, userDataDir);88 }89 throw error;90 }91 }92 async _innerLaunch(progress, options, persistent, protocolLogger, userDataDir) {93 options.proxy = options.proxy ? (0, _browserContext.normalizeProxySettings)(options.proxy) : undefined;94 const browserLogsCollector = new _debugLogger.RecentLogsCollector();95 const {96 browserProcess,97 artifactsDir,98 transport99 } = await this._launchProcess(progress, options, !!persistent, browserLogsCollector, userDataDir);100 if (options.__testHookBeforeCreateBrowser) await options.__testHookBeforeCreateBrowser();101 const browserOptions = { ...this._playwrightOptions,102 name: this._name,103 isChromium: this._name === 'chromium',104 channel: options.channel,105 slowMo: options.slowMo,106 persistent,107 headful: !options.headless,108 artifactsDir,109 downloadsPath: options.downloadsPath || artifactsDir,110 tracesDir: options.tracesDir || artifactsDir,111 browserProcess,112 customExecutablePath: options.executablePath,113 proxy: options.proxy,114 protocolLogger,115 browserLogsCollector,116 wsEndpoint: options.useWebSocket ? transport.wsEndpoint : undefined117 };118 if (persistent) (0, _browserContext.validateBrowserContextOptions)(persistent, browserOptions);119 copyTestHooks(options, browserOptions);120 const browser = await this._connectToTransport(transport, browserOptions); // We assume no control when using custom arguments, and do not prepare the default context in that case.121 if (persistent && !options.ignoreAllDefaultArgs) await browser._defaultContext._loadDefaultContext(progress);122 return browser;123 }124 async _launchProcess(progress, options, isPersistent, browserLogsCollector, userDataDir) {125 var _options$args;126 const {127 ignoreDefaultArgs,128 ignoreAllDefaultArgs,129 args = [],130 executablePath = null,131 handleSIGINT = true,132 handleSIGTERM = true,133 handleSIGHUP = true134 } = options;135 const env = options.env ? (0, _processLauncher.envArrayToObject)(options.env) : process.env;136 const tempDirectories = [];137 if (options.downloadsPath) await _fs.default.promises.mkdir(options.downloadsPath, {138 recursive: true139 });140 if (options.tracesDir) await _fs.default.promises.mkdir(options.tracesDir, {141 recursive: true142 });143 const artifactsDir = await _fs.default.promises.mkdtemp(ARTIFACTS_FOLDER);144 tempDirectories.push(artifactsDir);145 if (userDataDir) {146 // Firefox bails if the profile directory does not exist, Chrome creates it. We ensure consistent behavior here.147 if (!(await (0, _utils.existsAsync)(userDataDir))) await _fs.default.promises.mkdir(userDataDir, {148 recursive: true,149 mode: 0o700150 });151 } else {152 userDataDir = await _fs.default.promises.mkdtemp(_path.default.join(os.tmpdir(), `playwright_${this._name}dev_profile-`));153 tempDirectories.push(userDataDir);154 }155 const browserArguments = [];156 if (ignoreAllDefaultArgs) browserArguments.push(...args);else if (ignoreDefaultArgs) browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir).filter(arg => ignoreDefaultArgs.indexOf(arg) === -1));else browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir));157 let executable;158 if (executablePath) {159 if (!(await (0, _utils.existsAsync)(executablePath))) throw new Error(`Failed to launch ${this._name} because executable doesn't exist at ${executablePath}`);160 executable = executablePath;161 } else {162 const registryExecutable = _registry.registry.findExecutable(options.channel || this._name);163 if (!registryExecutable || registryExecutable.browserName !== this._name) throw new Error(`Unsupported ${this._name} channel "${options.channel}"`);164 executable = registryExecutable.executablePathOrDie(this._playwrightOptions.sdkLanguage);165 await registryExecutable.validateHostRequirements(this._playwrightOptions.sdkLanguage);166 }167 let wsEndpointCallback;168 const shouldWaitForWSListening = options.useWebSocket || ((_options$args = options.args) === null || _options$args === void 0 ? void 0 : _options$args.some(a => a.startsWith('--remote-debugging-port')));169 const waitForWSEndpoint = shouldWaitForWSListening ? new Promise(f => wsEndpointCallback = f) : undefined; // Note: it is important to define these variables before launchProcess, so that we don't get170 // "Cannot access 'browserServer' before initialization" if something went wrong.171 let transport = undefined;172 let browserProcess = undefined;173 const {174 launchedProcess,175 gracefullyClose,176 kill177 } = await (0, _processLauncher.launchProcess)({178 command: executable,179 args: browserArguments,180 env: this._amendEnvironment(env, userDataDir, executable, browserArguments),181 handleSIGINT,182 handleSIGTERM,183 handleSIGHUP,184 log: message => {185 if (wsEndpointCallback) {186 const match = message.match(/DevTools listening on (.*)/);187 if (match) wsEndpointCallback(match[1]);188 }189 progress.log(message);190 browserLogsCollector.log(message);191 },192 stdio: 'pipe',193 tempDirectories,194 attemptToGracefullyClose: async () => {195 if (options.__testHookGracefullyClose) await options.__testHookGracefullyClose(); // We try to gracefully close to prevent crash reporting and core dumps.196 // Note that it's fine to reuse the pipe transport, since197 // our connection ignores kBrowserCloseMessageId.198 this._attemptToGracefullyCloseBrowser(transport);199 },200 onExit: (exitCode, signal) => {201 if (browserProcess && browserProcess.onclose) browserProcess.onclose(exitCode, signal);202 }203 });204 async function closeOrKill(timeout) {205 let timer;206 try {207 await Promise.race([gracefullyClose(), new Promise((resolve, reject) => timer = setTimeout(reject, timeout))]);208 } catch (ignored) {209 await kill().catch(ignored => {}); // Make sure to await actual process exit.210 } finally {211 clearTimeout(timer);212 }213 }214 browserProcess = {215 onclose: undefined,216 process: launchedProcess,217 close: () => closeOrKill(options.__testHookBrowserCloseTimeout || _timeoutSettings.DEFAULT_TIMEOUT),218 kill219 };220 progress.cleanupWhenAborted(() => closeOrKill(progress.timeUntilDeadline()));221 let wsEndpoint;222 if (shouldWaitForWSListening) wsEndpoint = await waitForWSEndpoint;223 if (options.useWebSocket) {224 transport = await _transport.WebSocketTransport.connect(progress, wsEndpoint);225 } else {226 const stdio = launchedProcess.stdio;227 transport = new _pipeTransport.PipeTransport(stdio[3], stdio[4]);228 }229 return {230 browserProcess,231 artifactsDir,232 transport233 };234 }235 async connectOverCDP(metadata, endpointURL, options, timeout) {236 throw new Error('CDP connections are only supported by Chromium');237 }238 async _launchWithSeleniumHub(progress, hubUrl, options) {239 throw new Error('Connecting to SELENIUM_REMOTE_URL is only supported by Chromium');240 }241 _validateLaunchOptions(options) {242 const {243 devtools = false244 } = options;245 let {246 headless = !devtools,247 downloadsPath,248 proxy249 } = options;250 if ((0, _utils.debugMode)()) headless = false;251 if (downloadsPath && !_path.default.isAbsolute(downloadsPath)) downloadsPath = _path.default.join(process.cwd(), downloadsPath);252 if (this._playwrightOptions.socksProxyPort) proxy = {253 server: `socks5://127.0.0.1:${this._playwrightOptions.socksProxyPort}`254 };255 return { ...options,256 devtools,257 headless,258 downloadsPath,259 proxy260 };261 }262}263exports.BrowserType = BrowserType;264function copyTestHooks(from, to) {265 for (const [key, value] of Object.entries(from)) {266 if (key.startsWith('__testHook')) to[key] = value;267 }...
electron.js
Source:electron.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.ElectronApplication = exports.Electron = void 0;6var _fs = _interopRequireDefault(require("fs"));7var _os = _interopRequireDefault(require("os"));8var _path = _interopRequireDefault(require("path"));9var _crBrowser = require("../chromium/crBrowser");10var _crConnection = require("../chromium/crConnection");11var _crExecutionContext = require("../chromium/crExecutionContext");12var js = _interopRequireWildcard(require("../javascript"));13var _timeoutSettings = require("../../utils/timeoutSettings");14var _transport = require("../transport");15var _processLauncher = require("../../utils/processLauncher");16var _browserContext = require("../browserContext");17var _progress = require("../progress");18var _helper = require("../helper");19var _eventsHelper = require("../../utils/eventsHelper");20var readline = _interopRequireWildcard(require("readline"));21var _debugLogger = require("../../utils/debugLogger");22var _instrumentation = require("../instrumentation");23function _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); }24function _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; }25function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }26/**27 * Copyright (c) Microsoft Corporation.28 *29 * Licensed under the Apache License, Version 2.0 (the "License");30 * you may not use this file except in compliance with the License.31 * You may obtain a copy of the License at32 *33 * http://www.apache.org/licenses/LICENSE-2.034 *35 * Unless required by applicable law or agreed to in writing, software36 * distributed under the License is distributed on an "AS IS" BASIS,37 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.38 * See the License for the specific language governing permissions and39 * limitations under the License.40 */41const ARTIFACTS_FOLDER = _path.default.join(_os.default.tmpdir(), 'playwright-artifacts-');42class ElectronApplication extends _instrumentation.SdkObject {43 constructor(parent, browser, nodeConnection) {44 super(parent, 'electron-app');45 this._browserContext = void 0;46 this._nodeConnection = void 0;47 this._nodeSession = void 0;48 this._nodeExecutionContext = void 0;49 this._nodeElectronHandlePromise = void 0;50 this._timeoutSettings = new _timeoutSettings.TimeoutSettings();51 this._browserContext = browser._defaultContext;52 this._browserContext.on(_browserContext.BrowserContext.Events.Close, () => {53 // Emit application closed after context closed.54 Promise.resolve().then(() => this.emit(ElectronApplication.Events.Close));55 });56 this._nodeConnection = nodeConnection;57 this._nodeSession = nodeConnection.rootSession;58 this._nodeElectronHandlePromise = new Promise(f => {59 this._nodeSession.on('Runtime.executionContextCreated', async event => {60 if (event.context.auxData && event.context.auxData.isDefault) {61 this._nodeExecutionContext = new js.ExecutionContext(this, new _crExecutionContext.CRExecutionContext(this._nodeSession, event.context));62 f(await js.evaluate(this._nodeExecutionContext, false63 /* returnByValue */64 , `process.mainModule.require('electron')`));65 }66 });67 });68 this._browserContext.setCustomCloseHandler(async () => {69 const electronHandle = await this._nodeElectronHandlePromise;70 await electronHandle.evaluate(({71 app72 }) => app.quit());73 });74 this._nodeSession.send('Runtime.enable', {}).catch(e => {});75 }76 context() {77 return this._browserContext;78 }79 async close() {80 const progressController = new _progress.ProgressController((0, _instrumentation.internalCallMetadata)(), this);81 const closed = progressController.run(progress => _helper.helper.waitForEvent(progress, this, ElectronApplication.Events.Close).promise);82 await this._browserContext.close((0, _instrumentation.internalCallMetadata)());83 this._nodeConnection.close();84 await closed;85 }86 async browserWindow(page) {87 // Assume CRPage as Electron is always Chromium.88 const targetId = page._delegate._targetId;89 const electronHandle = await this._nodeElectronHandlePromise;90 return await electronHandle.evaluateHandle(({91 BrowserWindow,92 webContents93 }, targetId) => {94 const wc = webContents.fromDevToolsTargetId(targetId);95 return BrowserWindow.fromWebContents(wc);96 }, targetId);97 }98}99exports.ElectronApplication = ElectronApplication;100ElectronApplication.Events = {101 Close: 'close'102};103class Electron extends _instrumentation.SdkObject {104 constructor(playwrightOptions) {105 super(playwrightOptions.rootSdkObject, 'electron');106 this._playwrightOptions = void 0;107 this._playwrightOptions = playwrightOptions;108 }109 async launch(options) {110 const {111 args = []112 } = options;113 const controller = new _progress.ProgressController((0, _instrumentation.internalCallMetadata)(), this);114 controller.setLogName('browser');115 return controller.run(async progress => {116 let app = undefined;117 const electronArguments = ['--inspect=0', '--remote-debugging-port=0', ...args];118 if (_os.default.platform() === 'linux') {119 const runningAsRoot = process.geteuid && process.geteuid() === 0;120 if (runningAsRoot && electronArguments.indexOf('--no-sandbox') === -1) electronArguments.push('--no-sandbox');121 }122 const artifactsDir = await _fs.default.promises.mkdtemp(ARTIFACTS_FOLDER);123 const browserLogsCollector = new _debugLogger.RecentLogsCollector();124 const {125 launchedProcess,126 gracefullyClose,127 kill128 } = await (0, _processLauncher.launchProcess)({129 command: options.executablePath || require('electron/index.js'),130 args: electronArguments,131 env: options.env ? (0, _processLauncher.envArrayToObject)(options.env) : process.env,132 log: message => {133 progress.log(message);134 browserLogsCollector.log(message);135 },136 stdio: 'pipe',137 cwd: options.cwd,138 tempDirectories: [artifactsDir],139 attemptToGracefullyClose: () => app.close(),140 handleSIGINT: true,141 handleSIGTERM: true,142 handleSIGHUP: true,143 onExit: () => {}144 });145 const waitForXserverError = new Promise(async (resolve, reject) => {146 waitForLine(progress, launchedProcess, /Unable to open X display/).then(() => reject(new Error(['Unable to open X display!', `================================`, 'Most likely this is because there is no X server available.', "Use 'xvfb-run' on Linux to launch your tests with an emulated display server.", "For example: 'xvfb-run npm run test:e2e'", `================================`, progress.metadata.log].join('\n')))).catch(() => {});147 });148 const nodeMatch = await waitForLine(progress, launchedProcess, /^Debugger listening on (ws:\/\/.*)$/);149 const nodeTransport = await _transport.WebSocketTransport.connect(progress, nodeMatch[1]);150 const nodeConnection = new _crConnection.CRConnection(nodeTransport, _helper.helper.debugProtocolLogger(), browserLogsCollector);151 const chromeMatch = await Promise.race([waitForLine(progress, launchedProcess, /^DevTools listening on (ws:\/\/.*)$/), waitForXserverError]);152 const chromeTransport = await _transport.WebSocketTransport.connect(progress, chromeMatch[1]);153 const browserProcess = {154 onclose: undefined,155 process: launchedProcess,156 close: gracefullyClose,157 kill158 };159 const contextOptions = { ...options,160 noDefaultViewport: true161 };162 const browserOptions = { ...this._playwrightOptions,163 name: 'electron',164 isChromium: true,165 headful: true,166 persistent: contextOptions,167 browserProcess,168 protocolLogger: _helper.helper.debugProtocolLogger(),169 browserLogsCollector,170 artifactsDir,171 downloadsPath: artifactsDir,172 tracesDir: artifactsDir173 };174 (0, _browserContext.validateBrowserContextOptions)(contextOptions, browserOptions);175 const browser = await _crBrowser.CRBrowser.connect(chromeTransport, browserOptions);176 app = new ElectronApplication(this, browser, nodeConnection);177 return app;178 }, _timeoutSettings.TimeoutSettings.timeout(options));179 }180}181exports.Electron = Electron;182function waitForLine(progress, process, regex) {183 return new Promise((resolve, reject) => {184 const rl = readline.createInterface({185 input: process.stderr186 });187 const failError = new Error('Process failed to launch!');188 const listeners = [_eventsHelper.eventsHelper.addEventListener(rl, 'line', onLine), _eventsHelper.eventsHelper.addEventListener(rl, 'close', reject.bind(null, failError)), _eventsHelper.eventsHelper.addEventListener(process, 'exit', reject.bind(null, failError)), // It is Ok to remove error handler because we did not create process and there is another listener.189 _eventsHelper.eventsHelper.addEventListener(process, 'error', reject.bind(null, failError))];190 progress.cleanupWhenAborted(cleanup);191 function onLine(line) {192 const match = line.match(regex);193 if (!match) return;194 cleanup();195 resolve(match);196 }197 function cleanup() {198 _eventsHelper.eventsHelper.removeEventListeners(listeners);199 }200 });...
processLauncher.js
Source:processLauncher.js
...172 gracefullyClose,173 kill: killAndWait174 };175}176function envArrayToObject(env) {177 const result = {};178 for (const {179 name,180 value181 } of env) result[name] = value;182 return result;...
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!!