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 _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}...
clientHelper.js
Source: clientHelper.js
...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})`;...
browserServerImpl.js
Source: browserServerImpl.js
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;...
Using AI Code Generation
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})();
Using AI Code Generation
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 } =
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!!