Best JavaScript code snippet using playwright-internal
frame.js
Source:frame.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.Frame = void 0;6exports.verifyLoadState = verifyLoadState;7var _utils = require("../utils/utils");8var _channelOwner = require("./channelOwner");9var _locator = require("./locator");10var _elementHandle = require("./elementHandle");11var _jsHandle = require("./jsHandle");12var _fs = _interopRequireDefault(require("fs"));13var network = _interopRequireWildcard(require("./network"));14var _events = require("events");15var _waiter = require("./waiter");16var _events2 = require("./events");17var _types = require("./types");18var _clientHelper = require("./clientHelper");19function _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); }20function _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; }21function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }22/**23 * Copyright 2017 Google Inc. All rights reserved.24 * Modifications 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 */38class Frame extends _channelOwner.ChannelOwner {39 static from(frame) {40 return frame._object;41 }42 static fromNullable(frame) {43 return frame ? Frame.from(frame) : null;44 }45 constructor(parent, type, guid, initializer) {46 super(parent, type, guid, initializer);47 this._eventEmitter = void 0;48 this._loadStates = void 0;49 this._parentFrame = null;50 this._url = '';51 this._name = '';52 this._detached = false;53 this._childFrames = new Set();54 this._page = void 0;55 this._eventEmitter = new _events.EventEmitter();56 this._eventEmitter.setMaxListeners(0);57 this._parentFrame = Frame.fromNullable(initializer.parentFrame);58 if (this._parentFrame) this._parentFrame._childFrames.add(this);59 this._name = initializer.name;60 this._url = initializer.url;61 this._loadStates = new Set(initializer.loadStates);62 this._channel.on('loadstate', event => {63 if (event.add) {64 this._loadStates.add(event.add);65 this._eventEmitter.emit('loadstate', event.add);66 }67 if (event.remove) this._loadStates.delete(event.remove);68 });69 this._channel.on('navigated', event => {70 this._url = event.url;71 this._name = event.name;72 this._eventEmitter.emit('navigated', event);73 if (!event.error && this._page) this._page.emit(_events2.Events.Page.FrameNavigated, this);74 });75 }76 page() {77 return this._page;78 }79 async goto(url, options = {}) {80 const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);81 return network.Response.fromNullable((await this._channel.goto({82 url,83 ...options,84 waitUntil85 })).response);86 }87 _setupNavigationWaiter(options) {88 const waiter = new _waiter.Waiter(this._page, '');89 if (this._page.isClosed()) waiter.rejectImmediately(new Error('Navigation failed because page was closed!'));90 waiter.rejectOnEvent(this._page, _events2.Events.Page.Close, new Error('Navigation failed because page was closed!'));91 waiter.rejectOnEvent(this._page, _events2.Events.Page.Crash, new Error('Navigation failed because page crashed!'));92 waiter.rejectOnEvent(this._page, _events2.Events.Page.FrameDetached, new Error('Navigating frame was detached!'), frame => frame === this);93 const timeout = this._page._timeoutSettings.navigationTimeout(options);94 waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded.`);95 return waiter;96 }97 async waitForNavigation(options = {}) {98 return this._page._wrapApiCall(async () => {99 const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);100 const waiter = this._setupNavigationWaiter(options);101 const toUrl = typeof options.url === 'string' ? ` to "${options.url}"` : '';102 waiter.log(`waiting for navigation${toUrl} until "${waitUntil}"`);103 const navigatedEvent = await waiter.waitForEvent(this._eventEmitter, 'navigated', event => {104 var _this$_page;105 // Any failed navigation results in a rejection.106 if (event.error) return true;107 waiter.log(` navigated to "${event.url}"`);108 return (0, _clientHelper.urlMatches)((_this$_page = this._page) === null || _this$_page === void 0 ? void 0 : _this$_page.context()._options.baseURL, event.url, options.url);109 });110 if (navigatedEvent.error) {111 const e = new Error(navigatedEvent.error);112 e.stack = '';113 await waiter.waitForPromise(Promise.reject(e));114 }115 if (!this._loadStates.has(waitUntil)) {116 await waiter.waitForEvent(this._eventEmitter, 'loadstate', s => {117 waiter.log(` "${s}" event fired`);118 return s === waitUntil;119 });120 }121 const request = navigatedEvent.newDocument ? network.Request.fromNullable(navigatedEvent.newDocument.request) : null;122 const response = request ? await waiter.waitForPromise(request._finalRequest()._internalResponse()) : null;123 waiter.dispose();124 return response;125 });126 }127 async waitForLoadState(state = 'load', options = {}) {128 state = verifyLoadState('state', state);129 if (this._loadStates.has(state)) return;130 return this._page._wrapApiCall(async () => {131 const waiter = this._setupNavigationWaiter(options);132 await waiter.waitForEvent(this._eventEmitter, 'loadstate', s => {133 waiter.log(` "${s}" event fired`);134 return s === state;135 });136 waiter.dispose();137 });138 }139 async waitForURL(url, options = {}) {140 var _this$_page2;141 if ((0, _clientHelper.urlMatches)((_this$_page2 = this._page) === null || _this$_page2 === void 0 ? void 0 : _this$_page2.context()._options.baseURL, this.url(), url)) return await this.waitForLoadState(options.waitUntil, options);142 await this.waitForNavigation({143 url,144 ...options145 });146 }147 async frameElement() {148 return _elementHandle.ElementHandle.from((await this._channel.frameElement()).element);149 }150 async evaluateHandle(pageFunction, arg) {151 (0, _jsHandle.assertMaxArguments)(arguments.length, 2);152 const result = await this._channel.evaluateExpressionHandle({153 expression: String(pageFunction),154 isFunction: typeof pageFunction === 'function',155 arg: (0, _jsHandle.serializeArgument)(arg)156 });157 return _jsHandle.JSHandle.from(result.handle);158 }159 async evaluate(pageFunction, arg) {160 (0, _jsHandle.assertMaxArguments)(arguments.length, 2);161 const result = await this._channel.evaluateExpression({162 expression: String(pageFunction),163 isFunction: typeof pageFunction === 'function',164 arg: (0, _jsHandle.serializeArgument)(arg)165 });166 return (0, _jsHandle.parseResult)(result.value);167 }168 async $(selector, options) {169 const result = await this._channel.querySelector({170 selector,171 ...options172 });173 return _elementHandle.ElementHandle.fromNullable(result.element);174 }175 async waitForSelector(selector, options = {}) {176 if (options.visibility) throw new Error('options.visibility is not supported, did you mean options.state?');177 if (options.waitFor && options.waitFor !== 'visible') throw new Error('options.waitFor is not supported, did you mean options.state?');178 const result = await this._channel.waitForSelector({179 selector,180 ...options181 });182 return _elementHandle.ElementHandle.fromNullable(result.element);183 }184 async dispatchEvent(selector, type, eventInit, options = {}) {185 await this._channel.dispatchEvent({186 selector,187 type,188 eventInit: (0, _jsHandle.serializeArgument)(eventInit),189 ...options190 });191 }192 async $eval(selector, pageFunction, arg) {193 (0, _jsHandle.assertMaxArguments)(arguments.length, 3);194 const result = await this._channel.evalOnSelector({195 selector,196 expression: String(pageFunction),197 isFunction: typeof pageFunction === 'function',198 arg: (0, _jsHandle.serializeArgument)(arg)199 });200 return (0, _jsHandle.parseResult)(result.value);201 }202 async $$eval(selector, pageFunction, arg) {203 (0, _jsHandle.assertMaxArguments)(arguments.length, 3);204 const result = await this._channel.evalOnSelectorAll({205 selector,206 expression: String(pageFunction),207 isFunction: typeof pageFunction === 'function',208 arg: (0, _jsHandle.serializeArgument)(arg)209 });210 return (0, _jsHandle.parseResult)(result.value);211 }212 async $$(selector) {213 const result = await this._channel.querySelectorAll({214 selector215 });216 return result.elements.map(e => _elementHandle.ElementHandle.from(e));217 }218 async _queryCount(selector) {219 return (await this._channel.queryCount({220 selector221 })).value;222 }223 async content() {224 return (await this._channel.content()).value;225 }226 async setContent(html, options = {}) {227 const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);228 await this._channel.setContent({229 html,230 ...options,231 waitUntil232 });233 }234 name() {235 return this._name || '';236 }237 url() {238 return this._url;239 }240 parentFrame() {241 return this._parentFrame;242 }243 childFrames() {244 return Array.from(this._childFrames);245 }246 isDetached() {247 return this._detached;248 }249 async addScriptTag(options = {}) {250 const copy = { ...options251 };252 if (copy.path) {253 copy.content = (await _fs.default.promises.readFile(copy.path)).toString();254 copy.content += '//# sourceURL=' + copy.path.replace(/\n/g, '');255 }256 return _elementHandle.ElementHandle.from((await this._channel.addScriptTag({ ...copy257 })).element);258 }259 async addStyleTag(options = {}) {260 const copy = { ...options261 };262 if (copy.path) {263 copy.content = (await _fs.default.promises.readFile(copy.path)).toString();264 copy.content += '/*# sourceURL=' + copy.path.replace(/\n/g, '') + '*/';265 }266 return _elementHandle.ElementHandle.from((await this._channel.addStyleTag({ ...copy267 })).element);268 }269 async click(selector, options = {}) {270 return await this._channel.click({271 selector,272 ...options273 });274 }275 async dblclick(selector, options = {}) {276 return await this._channel.dblclick({277 selector,278 ...options279 });280 }281 async dragAndDrop(source, target, options = {}) {282 return await this._channel.dragAndDrop({283 source,284 target,285 ...options286 });287 }288 async tap(selector, options = {}) {289 return await this._channel.tap({290 selector,291 ...options292 });293 }294 async fill(selector, value, options = {}) {295 return await this._channel.fill({296 selector,297 value,298 ...options299 });300 }301 async _highlight(selector) {302 return await this._channel.highlight({303 selector304 });305 }306 locator(selector, options) {307 return new _locator.Locator(this, selector, options);308 }309 frameLocator(selector) {310 return new _locator.FrameLocator(this, selector);311 }312 async focus(selector, options = {}) {313 await this._channel.focus({314 selector,315 ...options316 });317 }318 async textContent(selector, options = {}) {319 const value = (await this._channel.textContent({320 selector,321 ...options322 })).value;323 return value === undefined ? null : value;324 }325 async innerText(selector, options = {}) {326 return (await this._channel.innerText({327 selector,328 ...options329 })).value;330 }331 async innerHTML(selector, options = {}) {332 return (await this._channel.innerHTML({333 selector,334 ...options335 })).value;336 }337 async getAttribute(selector, name, options = {}) {338 const value = (await this._channel.getAttribute({339 selector,340 name,341 ...options342 })).value;343 return value === undefined ? null : value;344 }345 async inputValue(selector, options = {}) {346 return (await this._channel.inputValue({347 selector,348 ...options349 })).value;350 }351 async isChecked(selector, options = {}) {352 return (await this._channel.isChecked({353 selector,354 ...options355 })).value;356 }357 async isDisabled(selector, options = {}) {358 return (await this._channel.isDisabled({359 selector,360 ...options361 })).value;362 }363 async isEditable(selector, options = {}) {364 return (await this._channel.isEditable({365 selector,366 ...options367 })).value;368 }369 async isEnabled(selector, options = {}) {370 return (await this._channel.isEnabled({371 selector,372 ...options373 })).value;374 }375 async isHidden(selector, options = {}) {376 return (await this._channel.isHidden({377 selector,378 ...options379 })).value;380 }381 async isVisible(selector, options = {}) {382 return (await this._channel.isVisible({383 selector,384 ...options385 })).value;386 }387 async hover(selector, options = {}) {388 await this._channel.hover({389 selector,390 ...options391 });392 }393 async selectOption(selector, values, options = {}) {394 return (await this._channel.selectOption({395 selector,396 ...(0, _elementHandle.convertSelectOptionValues)(values),397 ...options398 })).values;399 }400 async setInputFiles(selector, files, options = {}) {401 await this._channel.setInputFiles({402 selector,403 files: await (0, _elementHandle.convertInputFiles)(files),404 ...options405 });406 }407 async type(selector, text, options = {}) {408 await this._channel.type({409 selector,410 text,411 ...options412 });413 }414 async press(selector, key, options = {}) {415 await this._channel.press({416 selector,417 key,418 ...options419 });420 }421 async check(selector, options = {}) {422 await this._channel.check({423 selector,424 ...options425 });426 }427 async uncheck(selector, options = {}) {428 await this._channel.uncheck({429 selector,430 ...options431 });432 }433 async setChecked(selector, checked, options) {434 if (checked) await this.check(selector, options);else await this.uncheck(selector, options);435 }436 async waitForTimeout(timeout) {437 await this._channel.waitForTimeout({438 timeout439 });440 }441 async waitForFunction(pageFunction, arg, options = {}) {442 if (typeof options.polling === 'string') (0, _utils.assert)(options.polling === 'raf', 'Unknown polling option: ' + options.polling);443 const result = await this._channel.waitForFunction({ ...options,444 pollingInterval: options.polling === 'raf' ? undefined : options.polling,445 expression: String(pageFunction),446 isFunction: typeof pageFunction === 'function',447 arg: (0, _jsHandle.serializeArgument)(arg)448 });449 return _jsHandle.JSHandle.from(result.handle);450 }451 async title() {452 return (await this._channel.title()).value;453 }454}455exports.Frame = Frame;456function verifyLoadState(name, waitUntil) {457 if (waitUntil === 'networkidle0') waitUntil = 'networkidle';458 if (!_types.kLifecycleEvents.has(waitUntil)) throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`);459 return waitUntil;...
elementHandle.js
Source:elementHandle.js
...109 async tap(options = {}) {110 return await this._elementChannel.tap(options);111 }112 async selectOption(values, options = {}) {113 const result = await this._elementChannel.selectOption({ ...convertSelectOptionValues(values),114 ...options115 });116 return result.values;117 }118 async fill(value, options = {}) {119 return await this._elementChannel.fill({120 value,121 ...options122 });123 }124 async selectText(options = {}) {125 await this._elementChannel.selectText(options);126 }127 async setInputFiles(files, options = {}) {128 await this._elementChannel.setInputFiles({129 files: await convertInputFiles(files),130 ...options131 });132 }133 async focus() {134 await this._elementChannel.focus();135 }136 async type(text, options = {}) {137 await this._elementChannel.type({138 text,139 ...options140 });141 }142 async press(key, options = {}) {143 await this._elementChannel.press({144 key,145 ...options146 });147 }148 async check(options = {}) {149 return await this._elementChannel.check(options);150 }151 async uncheck(options = {}) {152 return await this._elementChannel.uncheck(options);153 }154 async setChecked(checked, options) {155 if (checked) await this.check(options);else await this.uncheck(options);156 }157 async boundingBox() {158 const value = (await this._elementChannel.boundingBox()).value;159 return value === undefined ? null : value;160 }161 async screenshot(options = {}) {162 const copy = { ...options163 };164 if (!copy.type) copy.type = determineScreenshotType(options);165 const result = await this._elementChannel.screenshot(copy);166 const buffer = Buffer.from(result.binary, 'base64');167 if (options.path) {168 await (0, _utils.mkdirIfNeeded)(options.path);169 await _fs.default.promises.writeFile(options.path, buffer);170 }171 return buffer;172 }173 async $(selector) {174 return ElementHandle.fromNullable((await this._elementChannel.querySelector({175 selector176 })).element);177 }178 async $$(selector) {179 const result = await this._elementChannel.querySelectorAll({180 selector181 });182 return result.elements.map(h => ElementHandle.from(h));183 }184 async $eval(selector, pageFunction, arg) {185 const result = await this._elementChannel.evalOnSelector({186 selector,187 expression: String(pageFunction),188 isFunction: typeof pageFunction === 'function',189 arg: (0, _jsHandle.serializeArgument)(arg)190 });191 return (0, _jsHandle.parseResult)(result.value);192 }193 async $$eval(selector, pageFunction, arg) {194 const result = await this._elementChannel.evalOnSelectorAll({195 selector,196 expression: String(pageFunction),197 isFunction: typeof pageFunction === 'function',198 arg: (0, _jsHandle.serializeArgument)(arg)199 });200 return (0, _jsHandle.parseResult)(result.value);201 }202 async waitForElementState(state, options = {}) {203 return await this._elementChannel.waitForElementState({204 state,205 ...options206 });207 }208 async waitForSelector(selector, options = {}) {209 const result = await this._elementChannel.waitForSelector({210 selector,211 ...options212 });213 return ElementHandle.fromNullable(result.element);214 }215}216exports.ElementHandle = ElementHandle;217function convertSelectOptionValues(values) {218 if (values === null) return {};219 if (!Array.isArray(values)) values = [values];220 if (!values.length) return {};221 for (let i = 0; i < values.length; i++) (0, _utils.assert)(values[i] !== null, `options[${i}]: expected object, got null`);222 if (values[0] instanceof ElementHandle) return {223 elements: values.map(v => v._elementChannel)224 };225 if ((0, _utils.isString)(values[0])) return {226 options: values.map(value => ({227 value228 }))229 };230 return {231 options: values...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.selectOption('select[name="q"]', 'Playwright');7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('[placeholder="Select a state..."]');7 await page.click('[placeholder="Select a state..."]');8 await page.click('text=Alaska');9 await page.click('[placeholder="Select a state..."]');10 await page.click('text=California');11 await page.click('[placeholder="Select a state..."]');12 await page.click('text=Georgia');13 await page.click('[placeholder="Select a state..."]');14 await page.click('text=Hawaii');15 await page.click('[placeholder="Select a state..."]');16 await page.click('text=Idaho');17 await page.click('[placeholder="Select a state..."]');18 await page.click('text=Kansas');19 await page.click('[placeholder="Select a state..."]');20 await page.click('text=Maine');21 await page.click('[placeholder="Select a state..."]');22 await page.click('text=Michigan');23 await page.click('[placeholder="Select a state..."]');24 await page.click('text=New Jersey');25 await page.click('[placeholder="Select a state..."]');
Using AI Code Generation
1const { convertSelectOptionValues } = require('playwright/lib/server/frames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const select = await page.$('#searchLanguage');8 const options = await select.$$('option');9 const values = await convertSelectOptionValues(page, options);10 console.log(values);11 await browser.close();12})();13const { chromium } = require('playwright');14const { convertSelectOptionValues } = require('playwright-internal-api');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 const select = await page.$('#searchLanguage');20 const options = await select.$$('option');21 const values = await convertSelectOptionValues(page, options);22 console.log(values);23 await browser.close();24})();25convertSelectOptionValues: (page: Page, options: ElementHandle[]) => Promise<string[]>;26convertSelectOptionValues: (page: Page, options: ElementHandle[]) => Promise<string[]>;27[MIT](LICENSE)
Using AI Code Generation
1const { convertSelectOptionValues } = require('@playwright/test/lib/server/frames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const selectElement = await page.$('select');8 const options = await selectElement.$$('option');9 const optionValues = await convertSelectOptionValues(page, options);10 await browser.close();11})();12#### page.convertSelectOptionValues(page, options)
Using AI Code Generation
1const { chromium } = require('playwright');2const { convertSelectOptionValues } = require('playwright/lib/server/chromium/crPage');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await page.selectOption('#searchDropdownBox', convertSelectOptionValues(['Books']));7 await page.fill('#twotabsearchtextbox', 'playwright');8 await page.click('#nav-search-submit-button');9 await page.waitForSelector('.a-color-state.a-text-bold');10 await page.screenshot({ path: `example.png` });11 await browser.close();12})();
Using AI Code Generation
1const { convertSelectOptionValues } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');2const values = convertSelectOptionValues(['foo', 'bar']);3console.log(values);4const { getSelectOptionValues } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');5const values = getSelectOptionValues(['foo', 'bar']);6console.log(values);7### `convertSelectOptionValues(values)`8### `getSelectOptionValues(values)`9[Apache-2.0](LICENSE)
Using AI Code Generation
1const { convertSelectOptionValues } = require('@playwright/test/lib/server/selectors');2const values = ['Option 2', 'Option 3'];3const convertedValues = convertSelectOptionValues(values);4const { waitForEvent } = require('@playwright/test/lib/server/page');5const page = await context.newPage();6await waitForEvent(page, 'domcontentloaded');7const { waitForRequest } = require('@playwright/test/lib/server/page');8const page = await context.newPage();9const { waitForResponse } = require('@playwright/test/lib/server/page');10const page = await context.newPage();
Using AI Code Generation
1const { convertSelectOptionValues } = require('playwright/lib/client/selectors');2### `convertSelectOptionValues(page, selector, values)`3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const page = await browser.newPage();7 await page.selectOption('select#dropdown', 'Option 1');8 await page.screenshot({ path: 'select-option-value.png' });9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const page = await browser.newPage();15 await page.goto('
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!!