How to use envObjectToArray method in Playwright Internal

Best JavaScript code snippet using playwright-internal

browserType.js

Source:browserType.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.BrowserType = void 0;6var _browser3 = require("./browser");7var _browserContext = require("./browserContext");8var _channelOwner = require("./channelOwner");9var _connection = require("./connection");10var _events = require("./events");11var _clientHelper = require("./clientHelper");12var _utils = require("../utils/utils");13var _errors = require("../utils/errors");14var _async = require("../utils/async");15/**16 * Copyright (c) Microsoft Corporation.17 *18 * Licensed under the Apache License, Version 2.0 (the "License");19 * you may not use this file except in compliance with the License.20 * You may obtain a copy of the License at21 *22 * http://www.apache.org/licenses/LICENSE-2.023 *24 * Unless required by applicable law or agreed to in writing, software25 * distributed under the License is distributed on an "AS IS" BASIS,26 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.27 * See the License for the specific language governing permissions and28 * limitations under the License.29 */30class BrowserType extends _channelOwner.ChannelOwner {31 constructor(...args) {32 super(...args);33 this._serverLauncher = void 0;34 this._contexts = new Set();35 this._playwright = void 0;36 this._defaultContextOptions = {};37 this._defaultLaunchOptions = {};38 this._onDidCreateContext = void 0;39 this._onWillCloseContext = void 0;40 }41 static from(browserType) {42 return browserType._object;43 }44 executablePath() {45 if (!this._initializer.executablePath) throw new Error('Browser is not supported on current platform');46 return this._initializer.executablePath;47 }48 name() {49 return this._initializer.name;50 }51 async launch(options = {}) {52 const logger = options.logger || this._defaultLaunchOptions.logger;53 (0, _utils.assert)(!options.userDataDir, 'userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead');54 (0, _utils.assert)(!options.port, 'Cannot specify a port without launching as a server.');55 options = { ...this._defaultLaunchOptions,56 ...options57 };58 const launchOptions = { ...options,59 ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : undefined,60 ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),61 env: options.env ? (0, _clientHelper.envObjectToArray)(options.env) : undefined62 };63 const browser = _browser3.Browser.from((await this._channel.launch(launchOptions)).browser);64 browser._logger = logger;65 browser._setBrowserType(this);66 browser._localUtils = this._playwright._utils;67 return browser;68 }69 async launchServer(options = {}) {70 if (!this._serverLauncher) throw new Error('Launching server is not supported');71 options = { ...this._defaultLaunchOptions,72 ...options73 };74 return this._serverLauncher.launchServer(options);75 }76 async launchPersistentContext(userDataDir, options = {}) {77 var _this$_onDidCreateCon;78 const logger = options.logger || this._defaultLaunchOptions.logger;79 (0, _utils.assert)(!options.port, 'Cannot specify a port without launching as a server.');80 options = { ...this._defaultLaunchOptions,81 ...this._defaultContextOptions,82 ...options83 };84 const contextParams = await (0, _browserContext.prepareBrowserContextParams)(options);85 const persistentParams = { ...contextParams,86 ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : undefined,87 ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),88 env: options.env ? (0, _clientHelper.envObjectToArray)(options.env) : undefined,89 channel: options.channel,90 userDataDir91 };92 const result = await this._channel.launchPersistentContext(persistentParams);93 const context = _browserContext.BrowserContext.from(result.context);94 context._options = contextParams;95 context._logger = logger;96 context._setBrowserType(this);97 context._localUtils = this._playwright._utils;98 await ((_this$_onDidCreateCon = this._onDidCreateContext) === null || _this$_onDidCreateCon === void 0 ? void 0 : _this$_onDidCreateCon.call(this, context));99 return context;100 }101 async connect(optionsOrWsEndpoint, options) {102 if (typeof optionsOrWsEndpoint === 'string') return this._connect(optionsOrWsEndpoint, options);103 (0, _utils.assert)(optionsOrWsEndpoint.wsEndpoint, 'options.wsEndpoint is required');104 return this._connect(optionsOrWsEndpoint.wsEndpoint, optionsOrWsEndpoint);105 }106 async _connect(wsEndpoint, params = {}) {107 const logger = params.logger;108 return await this._wrapApiCall(async () => {109 const deadline = params.timeout ? (0, _utils.monotonicTime)() + params.timeout : 0;110 let browser;111 const {112 pipe113 } = await this._channel.connect({114 wsEndpoint,115 headers: params.headers,116 slowMo: params.slowMo,117 timeout: params.timeout118 });119 const closePipe = () => pipe.close().catch(() => {});120 const connection = new _connection.Connection();121 connection.markAsRemote();122 connection.on('close', closePipe);123 const onPipeClosed = () => {124 var _browser2;125 // Emulate all pages, contexts and the browser closing upon disconnect.126 for (const context of ((_browser = browser) === null || _browser === void 0 ? void 0 : _browser.contexts()) || []) {127 var _browser;128 for (const page of context.pages()) page._onClose();129 context._onClose();130 }131 (_browser2 = browser) === null || _browser2 === void 0 ? void 0 : _browser2._didClose();132 connection.close(_errors.kBrowserClosedError);133 };134 pipe.on('closed', onPipeClosed);135 connection.onmessage = message => pipe.send({136 message137 }).catch(onPipeClosed);138 pipe.on('message', ({139 message140 }) => {141 try {142 connection.dispatch(message);143 } catch (e) {144 console.error(`Playwright: Connection dispatch error`);145 console.error(e);146 closePipe();147 }148 });149 const createBrowserPromise = new Promise(async (fulfill, reject) => {150 try {151 // For tests.152 if (params.__testHookBeforeCreateBrowser) await params.__testHookBeforeCreateBrowser();153 const playwright = await connection.initializePlaywright();154 if (!playwright._initializer.preLaunchedBrowser) {155 reject(new Error('Malformed endpoint. Did you use launchServer method?'));156 closePipe();157 return;158 }159 playwright._setSelectors(this._playwright.selectors);160 browser = _browser3.Browser.from(playwright._initializer.preLaunchedBrowser);161 browser._logger = logger;162 browser._shouldCloseConnectionOnClose = true;163 browser._setBrowserType(playwright[browser._name]);164 browser._localUtils = this._playwright._utils;165 browser.on(_events.Events.Browser.Disconnected, closePipe);166 fulfill(browser);167 } catch (e) {168 reject(e);169 }170 });171 const result = await (0, _async.raceAgainstDeadline)(createBrowserPromise, deadline);172 if (!result.timedOut) {173 return result.result;174 } else {175 closePipe();176 throw new Error(`Timeout ${params.timeout}ms exceeded`);177 }178 });179 }180 connectOverCDP(endpointURLOrOptions, options) {181 if (typeof endpointURLOrOptions === 'string') return this._connectOverCDP(endpointURLOrOptions, options);182 const endpointURL = 'endpointURL' in endpointURLOrOptions ? endpointURLOrOptions.endpointURL : endpointURLOrOptions.wsEndpoint;183 (0, _utils.assert)(endpointURL, 'Cannot connect over CDP without wsEndpoint.');184 return this.connectOverCDP(endpointURL, endpointURLOrOptions);185 }186 async _connectOverCDP(endpointURL, params = {}) {187 if (this.name() !== 'chromium') throw new Error('Connecting over CDP is only supported in Chromium.');188 const headers = params.headers ? (0, _utils.headersObjectToArray)(params.headers) : undefined;189 const result = await this._channel.connectOverCDP({190 endpointURL,191 headers,192 slowMo: params.slowMo,193 timeout: params.timeout194 });195 const browser = _browser3.Browser.from(result.browser);196 if (result.defaultContext) browser._contexts.add(_browserContext.BrowserContext.from(result.defaultContext));197 browser._logger = params.logger;198 browser._setBrowserType(this);199 browser._localUtils = this._playwright._utils;200 return browser;201 }202}...

Full Screen

Full Screen

clientHelper.js

Source:clientHelper.js Github

copy

Full Screen

...32 if (deprecatedHits.has(methodName)) return;33 deprecatedHits.add(methodName);34 console.warn(message);35}36function envObjectToArray(env) {37 const result = [];38 for (const name in env) {39 if (!Object.is(env[name], undefined)) result.push({40 name,41 value: String(env[name])42 });43 }44 return result;45}46async function evaluationScript(fun, arg, addSourceUrl = true) {47 if (typeof fun === 'function') {48 const source = fun.toString();49 const argString = Object.is(arg, undefined) ? 'undefined' : JSON.stringify(arg);50 return `(${source})(${argString})`;...

Full Screen

Full Screen

browserServerImpl.js

Source:browserServerImpl.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.BrowserServerLauncherImpl = void 0;6var _ws = require("ws");7var _clientHelper = require("./client/clientHelper");8var _utils = require("./utils/utils");9var _instrumentation = require("./server/instrumentation");10var _playwright = require("./server/playwright");11var _playwrightServer = require("./remote/playwrightServer");12var _helper = require("./server/helper");13var _stackTrace = require("./utils/stackTrace");14/**15 * Copyright (c) Microsoft Corporation.16 *17 * Licensed under the Apache License, Version 2.0 (the 'License");18 * you may not use this file except in compliance with the License.19 * You may obtain a copy of the License at20 *21 * http://www.apache.org/licenses/LICENSE-2.022 *23 * Unless required by applicable law or agreed to in writing, software24 * distributed under the License is distributed on an "AS IS" BASIS,25 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.26 * See the License for the specific language governing permissions and27 * limitations under the License.28 */29class BrowserServerLauncherImpl {30 constructor(browserName) {31 this._browserName = void 0;32 this._browserName = browserName;33 }34 async launchServer(options = {}) {35 const playwright = (0, _playwright.createPlaywright)('javascript'); // 1. Pre-launch the browser36 const metadata = (0, _instrumentation.internalCallMetadata)();37 const browser = await playwright[this._browserName].launch(metadata, { ...options,38 ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : undefined,39 ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),40 env: options.env ? (0, _clientHelper.envObjectToArray)(options.env) : undefined41 }, toProtocolLogger(options.logger)).catch(e => {42 const log = _helper.helper.formatBrowserLogs(metadata.log);43 (0, _stackTrace.rewriteErrorMessage)(e, `${e.message} Failed to launch browser.${log}`);44 throw e;45 });46 let path = `/${(0, _utils.createGuid)()}`;47 if (options.wsPath) path = options.wsPath.startsWith('/') ? options.wsPath : `/${options.wsPath}`; // 2. Start the server48 const server = new _playwrightServer.PlaywrightServer(path, Infinity, false, browser);49 const wsEndpoint = await server.listen(options.port); // 3. Return the BrowserServer interface50 const browserServer = new _ws.EventEmitter();51 browserServer.process = () => browser.options.browserProcess.process;52 browserServer.wsEndpoint = () => wsEndpoint;53 browserServer.close = () => browser.options.browserProcess.close();54 browserServer.kill = () => browser.options.browserProcess.kill();55 browserServer._disconnectForTest = () => server.close();56 browser.options.browserProcess.onclose = async (exitCode, signal) => {57 server.close();58 browserServer.emit('close', exitCode, signal);59 };60 return browserServer;61 }62}63exports.BrowserServerLauncherImpl = BrowserServerLauncherImpl;64function toProtocolLogger(logger) {65 return logger ? (direction, message) => {66 if (logger.isEnabled('protocol', 'verbose')) logger.log('protocol', 'verbose', (direction === 'send' ? 'SEND ► ' : '◀ RECV ') + JSON.stringify(message), [], {});67 } : undefined;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const envObjectToArray = require('playwright/lib/utils/utils').envObjectToArray;3(async () => {4 const browser = await chromium.launch({5 env: {6 }7 });8 const page = await browser.newPage();9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 context.on('console', msg => console.log('PAGE LOG:', msg.text()));6 const page = await context.newPage();7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch({headless: false});13 const context = await browser.newContext();14 context.on('console', msg => console.log('PAGE LOG:', msg.text()));15 const page = await context.newPage();16 await page.screenshot({ path: `example.png` });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch({headless: false});22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.screenshot({ path: `example.png` });25 const envObject = { 'key1': 'value1', 'key2': 'value2' };26 const envArray = playwright.envObjectToArray(envObject);27 await browser.close();28})();29const { chromium } =

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

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

Run Playwright Internal automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful