Best JavaScript code snippet using playwright-internal
Page.js
Source:Page.js
...176 }177 /**178 * @param {!Protocol.Runtime.bindingCalledPayload} event179 */180 async _onBindingCalled(event) {181 const {name, seq, args} = JSON.parse(event.payload);182 let expression = null;183 try {184 const result = await this._pageBindings.get(name)(...args);185 expression = helper.evaluationString(deliverResult, name, seq, result);186 } catch (error) {187 if (error instanceof Error)188 expression = helper.evaluationString(deliverError, name, seq, error.message, error.stack);189 else190 expression = helper.evaluationString(deliverErrorValue, name, seq, error);191 }192 this._session.send('Runtime.evaluate', { expression, executionContextId: event.executionContextId }).catch(debugError);193 /**194 * @param {string} name...
DOMWorld.js
Source:DOMWorld.js
...45 this._frameManager = frameManager;46 this._frame = frame;47 this._timeoutSettings = timeoutSettings;48 this._setContext(null);49 frameManager._client.on('Runtime.bindingCalled', (event) => this._onBindingCalled(event));50 }51 frame() {52 return this._frame;53 }54 async _setContext(context) {55 if (context) {56 this._contextResolveCallback.call(null, context);57 this._contextResolveCallback = null;58 for (const waitTask of this._waitTasks)59 waitTask.rerun();60 }61 else {62 this._documentPromise = null;63 this._contextPromise = new Promise((fulfill) => {64 this._contextResolveCallback = fulfill;65 });66 }67 }68 _hasContext() {69 return !this._contextResolveCallback;70 }71 _detach() {72 this._detached = true;73 for (const waitTask of this._waitTasks)74 waitTask.terminate(new Error('waitForFunction failed: frame got detached.'));75 }76 executionContext() {77 if (this._detached)78 throw new Error(`Execution context is not available in detached frame "${this._frame.url()}" (are you trying to evaluate?)`);79 return this._contextPromise;80 }81 async evaluateHandle(pageFunction, ...args) {82 const context = await this.executionContext();83 return context.evaluateHandle(pageFunction, ...args);84 }85 async evaluate(pageFunction, ...args) {86 const context = await this.executionContext();87 return context.evaluate(pageFunction, ...args);88 }89 async $(selector) {90 const document = await this._document();91 const value = await document.$(selector);92 return value;93 }94 async _document() {95 if (this._documentPromise)96 return this._documentPromise;97 this._documentPromise = this.executionContext().then(async (context) => {98 const document = await context.evaluateHandle('document');99 return document.asElement();100 });101 return this._documentPromise;102 }103 async $x(expression) {104 const document = await this._document();105 const value = await document.$x(expression);106 return value;107 }108 async $eval(selector, pageFunction, ...args) {109 const document = await this._document();110 return document.$eval(selector, pageFunction, ...args);111 }112 async $$eval(selector, pageFunction, ...args) {113 const document = await this._document();114 const value = await document.$$eval(selector, pageFunction, ...args);115 return value;116 }117 async $$(selector) {118 const document = await this._document();119 const value = await document.$$(selector);120 return value;121 }122 async content() {123 return await this.evaluate(() => {124 let retVal = '';125 if (document.doctype)126 retVal = new XMLSerializer().serializeToString(document.doctype);127 if (document.documentElement)128 retVal += document.documentElement.outerHTML;129 return retVal;130 });131 }132 async setContent(html, options = {}) {133 const { waitUntil = ['load'], timeout = this._timeoutSettings.navigationTimeout(), } = options;134 // We rely upon the fact that document.open() will reset frame lifecycle with "init"135 // lifecycle event. @see https://crrev.com/608658136 await this.evaluate((html) => {137 document.open();138 document.write(html);139 document.close();140 }, html);141 const watcher = new LifecycleWatcher(this._frameManager, this._frame, waitUntil, timeout);142 const error = await Promise.race([143 watcher.timeoutOrTerminationPromise(),144 watcher.lifecyclePromise(),145 ]);146 watcher.dispose();147 if (error)148 throw error;149 }150 /**151 * Adds a script tag into the current context.152 *153 * @remarks154 *155 * You can pass a URL, filepath or string of contents. Note that when running Puppeteer156 * in a browser environment you cannot pass a filepath and should use either157 * `url` or `content`.158 */159 async addScriptTag(options) {160 const { url = null, path = null, content = null, type = '' } = options;161 if (url !== null) {162 try {163 const context = await this.executionContext();164 return (await context.evaluateHandle(addScriptUrl, url, type)).asElement();165 }166 catch (error) {167 throw new Error(`Loading script from ${url} failed`);168 }169 }170 if (path !== null) {171 if (!isNode) {172 throw new Error('Cannot pass a filepath to addScriptTag in the browser environment.');173 }174 const fs = await helper.importFSModule();175 let contents = await fs.promises.readFile(path, 'utf8');176 contents += '//# sourceURL=' + path.replace(/\n/g, '');177 const context = await this.executionContext();178 return (await context.evaluateHandle(addScriptContent, contents, type)).asElement();179 }180 if (content !== null) {181 const context = await this.executionContext();182 return (await context.evaluateHandle(addScriptContent, content, type)).asElement();183 }184 throw new Error('Provide an object with a `url`, `path` or `content` property');185 async function addScriptUrl(url, type) {186 const script = document.createElement('script');187 script.src = url;188 if (type)189 script.type = type;190 const promise = new Promise((res, rej) => {191 script.onload = res;192 script.onerror = rej;193 });194 document.head.appendChild(script);195 await promise;196 return script;197 }198 function addScriptContent(content, type = 'text/javascript') {199 const script = document.createElement('script');200 script.type = type;201 script.text = content;202 let error = null;203 script.onerror = (e) => (error = e);204 document.head.appendChild(script);205 if (error)206 throw error;207 return script;208 }209 }210 /**211 * Adds a style tag into the current context.212 *213 * @remarks214 *215 * You can pass a URL, filepath or string of contents. Note that when running Puppeteer216 * in a browser environment you cannot pass a filepath and should use either217 * `url` or `content`.218 *219 */220 async addStyleTag(options) {221 const { url = null, path = null, content = null } = options;222 if (url !== null) {223 try {224 const context = await this.executionContext();225 return (await context.evaluateHandle(addStyleUrl, url)).asElement();226 }227 catch (error) {228 throw new Error(`Loading style from ${url} failed`);229 }230 }231 if (path !== null) {232 if (!isNode) {233 throw new Error('Cannot pass a filepath to addStyleTag in the browser environment.');234 }235 const fs = await helper.importFSModule();236 let contents = await fs.promises.readFile(path, 'utf8');237 contents += '/*# sourceURL=' + path.replace(/\n/g, '') + '*/';238 const context = await this.executionContext();239 return (await context.evaluateHandle(addStyleContent, contents)).asElement();240 }241 if (content !== null) {242 const context = await this.executionContext();243 return (await context.evaluateHandle(addStyleContent, content)).asElement();244 }245 throw new Error('Provide an object with a `url`, `path` or `content` property');246 async function addStyleUrl(url) {247 const link = document.createElement('link');248 link.rel = 'stylesheet';249 link.href = url;250 const promise = new Promise((res, rej) => {251 link.onload = res;252 link.onerror = rej;253 });254 document.head.appendChild(link);255 await promise;256 return link;257 }258 async function addStyleContent(content) {259 const style = document.createElement('style');260 style.type = 'text/css';261 style.appendChild(document.createTextNode(content));262 const promise = new Promise((res, rej) => {263 style.onload = res;264 style.onerror = rej;265 });266 document.head.appendChild(style);267 await promise;268 return style;269 }270 }271 async click(selector, options) {272 const handle = await this.$(selector);273 assert(handle, 'No node found for selector: ' + selector);274 await handle.click(options);275 await handle.dispose();276 }277 async focus(selector) {278 const handle = await this.$(selector);279 assert(handle, 'No node found for selector: ' + selector);280 await handle.focus();281 await handle.dispose();282 }283 async hover(selector) {284 const handle = await this.$(selector);285 assert(handle, 'No node found for selector: ' + selector);286 await handle.hover();287 await handle.dispose();288 }289 async select(selector, ...values) {290 const handle = await this.$(selector);291 assert(handle, 'No node found for selector: ' + selector);292 const result = await handle.select(...values);293 await handle.dispose();294 return result;295 }296 async tap(selector) {297 const handle = await this.$(selector);298 await handle.tap();299 await handle.dispose();300 }301 async type(selector, text, options) {302 const handle = await this.$(selector);303 assert(handle, 'No node found for selector: ' + selector);304 await handle.type(text, options);305 await handle.dispose();306 }307 async waitForSelector(selector, options) {308 const { updatedSelector, queryHandler } = getQueryHandlerAndSelector(selector);309 return queryHandler.waitFor(this, updatedSelector, options);310 }311 /**312 * @internal313 */314 async addBindingToContext(context, name) {315 // Previous operation added the binding so we are done.316 if (this._ctxBindings.has(DOMWorld.bindingIdentifier(name, context._contextId))) {317 return;318 }319 // Wait for other operation to finish320 if (this._settingUpBinding) {321 await this._settingUpBinding;322 return this.addBindingToContext(context, name);323 }324 const bind = async (name) => {325 const expression = helper.pageBindingInitString('internal', name);326 try {327 await context._client.send('Runtime.addBinding', {328 name,329 executionContextId: context._contextId,330 });331 await context.evaluate(expression);332 }333 catch (error) {334 // We could have tried to evaluate in a context which was already335 // destroyed. This happens, for example, if the page is navigated while336 // we are trying to add the binding337 const ctxDestroyed = error.message.includes('Execution context was destroyed');338 const ctxNotFound = error.message.includes('Cannot find context with specified id');339 if (ctxDestroyed || ctxNotFound) {340 return;341 }342 else {343 debugError(error);344 return;345 }346 }347 this._ctxBindings.add(DOMWorld.bindingIdentifier(name, context._contextId));348 };349 this._settingUpBinding = bind(name);350 await this._settingUpBinding;351 this._settingUpBinding = null;352 }353 async _onBindingCalled(event) {354 let payload;355 if (!this._hasContext())356 return;357 const context = await this.executionContext();358 try {359 payload = JSON.parse(event.payload);360 }361 catch {362 // The binding was either called by something in the page or it was363 // called before our wrapper was initialized.364 return;365 }366 const { type, name, seq, args } = payload;367 if (type !== 'internal' ||...
ffPage.js
Source:ffPage.js
...201 promptText202 });203 }, params.defaultValue));204 }205 async _onBindingCalled(event) {206 const pageOrError = await this.pageOrError();207 if (!(pageOrError instanceof Error)) {208 const context = this._contextIdToContext.get(event.executionContextId);209 if (context) await this._page._onBindingCalled(event.payload, context);210 }211 }212 async _onFileChooserOpened(payload) {213 const {214 executionContextId,215 element216 } = payload;217 const context = this._contextIdToContext.get(executionContextId);218 if (!context) return;219 const handle = context.createHandle(element).asElement();220 await this._page._onFileChooserOpened(handle);221 }222 async _onWorkerCreated(event) {223 const workerId = event.workerId;...
Using AI Code Generation
1const { chromium } = require('playwright');2const path = require('path');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.fill('#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input', 'playwright');8 await page.click('#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input.gNO89b');9 await page.waitForNavigation();10 await page.screenshot({ path: path.join(__dirname, 'google-playwright.png') });11 await browser.close();12})();13const { chromium } = require('playwright');14const path = require('path');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 await page.fill('#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input', 'playwright');20 await page.click('#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input.gNO89b');21 await page.waitForNavigation();22 await page.screenshot({ path: path.join(__dirname, 'google-playwright.png') });23 await browser.close();24})();25const { chromium } = require('playwright');26const path = require('path');27(async () => {28 const browser = await chromium.launch();29 const context = await browser.newContext();30 const page = await context.newPage();31 await page.fill('#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input', 'playwright');32 await page.click('#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input.gNO89b');33 await page.waitForNavigation();
Using AI Code Generation
1const { _onBindingCalled } = require('playwright/lib/server/frames');2const { Frame } = require('playwright/lib/server/frames');3const { Page } = require('playwright/lib/server/page');4const { BrowserContext } = require('playwright/lib/server/browserContext');5const { BrowserServer } = require('playwright/lib/server/browserServer');6const { Browser } = require('playwright/lib/server/browser');7const { BrowserType } = require('playwright/lib/server/browserType');8const { BrowserContextDispatcher } = require('playwright/lib/server/chromium/crBrowser');9const { BrowserServerDispatcher } = require('playwright/lib/server/chromium/crBrowser');10const { BrowserDispatcher } = require('playwright/lib/server/chromium/crBrowser');11const { BrowserTypeDispatcher } = require('playwright/lib/server/chromium/crBrowser');12const { _onBindingCalled } = require('playwright/lib/server/frames');13const { Frame } = require('playwright/lib/server/frames');14const { Page } = require('playwright/lib/server/page');15const { BrowserContext } = require('playwright/lib/server/browserContext');16const { BrowserServer } = require('playwright/lib/server/browserServer');17const { Browser } = require('playwright/lib/server/browser');18const { BrowserType } = require('playwright/lib/server/browserType');19const { BrowserContextDispatcher } = require('playwright/lib/server/chromium/crBrowser');20const { BrowserServerDispatcher } = require('playwright/lib/server/chromium/crBrowser');21const { BrowserDispatcher } = require('playwright/lib/server/chromium/crBrowser');22const { BrowserTypeDispatcher } = require('playwright/lib/server/chromium/crBrowser');23const { _onBindingCalled } = require('playwright/lib/server/frames');24const { Frame } = require('playwright/lib/server/frames');25const { Page } = require('playwright/lib/server/page');26const { BrowserContext } = require('playwright/lib/server/browserContext');27const { BrowserServer } = require('playwright/lib/server/browserServer');28const { Browser } = require('playwright/lib/server/browser');29const { BrowserType } = require('playwright/lib/server/browserType');30const { BrowserContextDispatcher } = require('playwright/lib/server/ch
Using AI Code Generation
1const { _onBindingCalled } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2_onBindingCalled((source, name, ...args) => {3 if (name === 'playwright:log') {4 console.log(...args);5 }6});
Using AI Code Generation
1const { test } = require('@playwright/test');2const { _onBindingCalled } = require('@playwright/test/lib/server/frames');3test('test', async ({ page }) => {4 await page.addInitScript(() => {5 window.testBinding = (arg) => {6 console.log(arg);7 };8 });9 _onBindingCalled('testBinding', (source, arg) => {10 console.log(arg);11 });12 await page.evaluate(() => window.testBinding('test'));13});
Using AI Code Generation
1const { Playwright } = require('playwright');2const { _onBindingCalled } = Playwright;3_onBindingCalled = (source, ...args) => {4 console.log('Binding called with args: ', args);5 return 'Hello';6};7const { Playwright } = require('playwright');8const { _onBindingCalled } = Playwright;9_onBindingCalled = (source, ...args) => {10 console.log('Binding called with args: ', args);11 return 'Hello';12};13const { Playwright } = require('playwright');14const { _onBindingCalled } = Playwright;15_onBindingCalled = (source, ...args) => {16 console.log('Binding called with args: ', args);17 return 'Hello';18};19const { Playwright } = require('playwright');20const { _onBindingCalled } = Playwright;21_onBindingCalled = (source, ...args) => {22 console.log('Binding called with args: ', args);23 return 'Hello';24};25const { Playwright } = require('playwright');26const { _onBindingCalled } = Playwright;27_onBindingCalled = (source, ...args) => {28 console.log('Binding called with args: ', args);29 return 'Hello';30};31const { Playwright } = require('playwright');32const { _onBindingCalled } = Playwright;33_onBindingCalled = (source, ...args) => {34 console.log('Binding called with args: ', args);35 return 'Hello';36};37const { Playwright } = require('playwright');38const { _onBindingCalled }
Using AI Code Generation
1const { Playwright } = require("@playwright/test");2const { PlaywrightInternal } = Playwright;3const internal = new PlaywrightInternal();4const { _onBindingCalled } = internal;5_onBindingCalled("test", (source, ...args) => {6 return args;7});8- **Miguel Angel Garcia** - _Initial work_ - [miguelgarciaortiz](
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!!