How to use _onBindingCalled method in Puppeteer

Best JavaScript code snippet using puppeteer

Page.js

Source:Page.js Github

copy

Full Screen

...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...

Full Screen

Full Screen

DOMWorld.js

Source:DOMWorld.js Github

copy

Full Screen

...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' ||...

Full Screen

Full Screen

ffPage.js

Source:ffPage.js Github

copy

Full Screen

...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;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page._client.send('Network.enable');6 await page._client.on('Network.requestWillBeSent', (data) => {7 console.log(data);8 });9 await browser.close();10})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page._client.send('Network.enable');6 await page._client.on('Network.requestWillBeSent', (params) => {7 console.log(params.request.url);8 });9 await page.screenshot({path: 'example.png'});10 await browser.close();11})();12const puppeteer = require('puppeteer');13(async () => {14 const browser = await puppeteer.launch();15 const page = await browser.newPage();16 await page._client.send('Network.enable');17 await page._client.on('Network.requestWillBeSent', (params) => {18 console.log(params.request.url);19 });20 await page.screenshot({path: 'example.png'});21 await browser.close();22})();23const puppeteer = require('puppeteer');24(async () => {25 const browser = await puppeteer.launch();26 const page = await browser.newPage();27 await page._client.send('Network.enable');28 await page._client.on('Network.requestWillBeSent', (params) => {29 console.log(params.request.url);30 });31 await page.screenshot({path: 'example.png'});32 await browser.close();33})();34const puppeteer = require('puppeteer');35(async () => {36 const browser = await puppeteer.launch();37 const page = await browser.newPage();38 await page._client.send('Network.enable');39 await page._client.on('Network.requestWillBeSent', (params) => {40 console.log(params.request.url);41 });42 await page.screenshot({path: 'example.png'});43 await browser.close();44})();45const puppeteer = require('puppeteer');46(async () => {47 const browser = await puppeteer.launch();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const browser = await puppeteer.launch({headless: false});3const page = await browser.newPage();4await page.evaluate(() => {5 document.querySelector('input').addEventListener('click', (e) => {6 console.log('clicked');7 });8});9await page.click('input');10await page.close();11await browser.close();12const {chromium} = require('playwright');13const browser = await chromium.launch({headless: false});14const page = await browser.newPage();15await page.evaluate(() => {16 document.querySelector('input').addEventListener('click', (e) => {17 console.log('clicked');18 });19});20await page.click('input');21await page.close();22await browser.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const { generateText, checkAndGenerate } = require('./util');5test('should output data-less text', () => {6 const text = generateText('', null);7 expect(text).toBe(' (null years old)');8});9test('should create an element with text and correct class', async () => {10 const browser = await puppeteer.launch({11 });12 const page = await browser.newPage();13 await page.goto(14 );15 await page.click('input#name');16 await page.type('input#name', 'Anna');17 await page.click('input#age');18 await page.type('input#age', '28');19 await page.click('#btnAddUser');20 const finalText = await page.$eval('.user-item', el => el.textContent);21 expect(finalText).toBe('Anna (28 years old)');22}, 10000);

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const browser = await puppeteer.launch();3const page = await browser.newPage();4await page._onBindingCalled('myFunction', async () => {5 return 'hello';6});7await page.evaluate(() => {8 return myFunction();9});10await browser.close();11const puppeteer = require('puppeteer');12const browser = await puppeteer.launch();13const page = await browser.newPage();14await page._onBindingCalled('myFunction', async () => {15 return 'hello';16});17await page.evaluate(() => {18 return myFunction();19});20await browser.close();21const puppeteer = require('puppeteer');22const browser = await puppeteer.launch();23const page = await browser.newPage();24const frame = page.mainFrame();25await frame._onBindingCalled('myFunction', async () => {26 return 'hello';27});28await frame.evaluate(() => {29 return myFunction();30});31await browser.close();32const puppeteer = require('puppeteer');33const browser = await puppeteer.launch();34const page = await browser.newPage();35const frame = page.mainFrame();36const context = frame.executionContext();37await context._onBindingCalled('myFunction', async () => {38 return 'hello';39});40await context.evaluate(() => {41 return myFunction();42});43await browser.close();44const puppeteer = require('puppeteer');45const browser = await puppeteer.launch();46const page = await browser.newPage();47const worker = page.serviceWorker();48await worker._onBindingCalled('myFunction', async () => {49 return 'hello';50});51await worker.evaluate(() => {52 return myFunction();53});54await browser.close();55const puppeteer = require('puppeteer');56const browser = await puppeteer.launch();57const page = await browser.newPage();58const handle = page.evaluateHandle(() => {59 return {60 myFunction: () => 'hello',61 };62});63await handle._onBindingCalled('myFunction', async () => {64 return 'hello';65});66await handle.evaluate((obj) => {67 return obj.myFunction();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require("puppeteer");2let browser;3let page;4let context;5let pageTitle;6let pageUrl;7let pageContent;8let pageCookies;9let pageHtml;10let pageText;11let pagePdf;12let pageScreeshot;13let pageTitle2;14let pageUrl2;15let pageContent2;16let pageCookies2;17let pageHtml2;18let pageText2;19let pagePdf2;20let pageScreeshot2;21let pageTitle3;22let pageUrl3;23let pageContent3;24let pageCookies3;25let pageHtml3;26let pageText3;27let pagePdf3;28let pageScreeshot3;29let pageTitle4;30let pageUrl4;31let pageContent4;32let pageCookies4;

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer 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