How to use addBindingToContext method in Puppeteer

Best JavaScript code snippet using puppeteer

DOMWorld.js

Source:DOMWorld.js Github

copy

Full Screen

...53 this._contextResolveCallback.call(null, context);54 this._contextResolveCallback = null;55 this._ctxBindings.clear();56 for (const name of this._boundFunctions.keys()) {57 await this.addBindingToContext(name);58 }59 for (const waitTask of this._waitTasks)60 waitTask.rerun();61 }62 else {63 this._documentPromise = null;64 this._contextPromise = new Promise((fulfill) => {65 this._contextResolveCallback = fulfill;66 });67 }68 }69 _hasContext() {70 return !this._contextResolveCallback;71 }72 _detach() {73 this._detached = true;74 for (const waitTask of this._waitTasks)75 waitTask.terminate(new Error('waitForFunction failed: frame got detached.'));76 }77 executionContext() {78 if (this._detached)79 throw new Error(`Execution context is not available in detached frame "${this._frame.url()}" (are you trying to evaluate?)`);80 return this._contextPromise;81 }82 async evaluateHandle(pageFunction, ...args) {83 const context = await this.executionContext();84 return context.evaluateHandle(pageFunction, ...args);85 }86 async evaluate(pageFunction, ...args) {87 const context = await this.executionContext();88 return context.evaluate(pageFunction, ...args);89 }90 async $(selector) {91 const document = await this._document();92 const value = await document.$(selector);93 return value;94 }95 async _document() {96 if (this._documentPromise)97 return this._documentPromise;98 this._documentPromise = this.executionContext().then(async (context) => {99 const document = await context.evaluateHandle('document');100 return document.asElement();101 });102 return this._documentPromise;103 }104 async $x(expression) {105 const document = await this._document();106 const value = await document.$x(expression);107 return value;108 }109 async $eval(selector, pageFunction, ...args) {110 const document = await this._document();111 return document.$eval(selector, pageFunction, ...args);112 }113 async $$eval(selector, pageFunction, ...args) {114 const document = await this._document();115 const value = await document.$$eval(selector, pageFunction, ...args);116 return value;117 }118 async $$(selector) {119 const document = await this._document();120 const value = await document.$$(selector);121 return value;122 }123 async content() {124 return await this.evaluate(() => {125 let retVal = '';126 if (document.doctype)127 retVal = new XMLSerializer().serializeToString(document.doctype);128 if (document.documentElement)129 retVal += document.documentElement.outerHTML;130 return retVal;131 });132 }133 async setContent(html, options = {}) {134 const { waitUntil = ['load'], timeout = this._timeoutSettings.navigationTimeout(), } = options;135 // We rely upon the fact that document.open() will reset frame lifecycle with "init"136 // lifecycle event. @see https://crrev.com/608658137 await this.evaluate((html) => {138 document.open();139 document.write(html);140 document.close();141 }, html);142 const watcher = new LifecycleWatcher(this._frameManager, this._frame, waitUntil, timeout);143 const error = await Promise.race([144 watcher.timeoutOrTerminationPromise(),145 watcher.lifecyclePromise(),146 ]);147 watcher.dispose();148 if (error)149 throw error;150 }151 /**152 * Adds a script tag into the current context.153 *154 * @remarks155 *156 * You can pass a URL, filepath or string of contents. Note that when running Puppeteer157 * in a browser environment you cannot pass a filepath and should use either158 * `url` or `content`.159 */160 async addScriptTag(options) {161 const { url = null, path = null, content = null, type = '' } = options;162 if (url !== null) {163 try {164 const context = await this.executionContext();165 return (await context.evaluateHandle(addScriptUrl, url, type)).asElement();166 }167 catch (error) {168 throw new Error(`Loading script from ${url} failed`);169 }170 }171 if (path !== null) {172 if (!isNode) {173 throw new Error('Cannot pass a filepath to addScriptTag in the browser environment.');174 }175 const fs = await helper.importFSModule();176 let contents = await fs.promises.readFile(path, 'utf8');177 contents += '//# sourceURL=' + path.replace(/\n/g, '');178 const context = await this.executionContext();179 return (await context.evaluateHandle(addScriptContent, contents, type)).asElement();180 }181 if (content !== null) {182 const context = await this.executionContext();183 return (await context.evaluateHandle(addScriptContent, content, type)).asElement();184 }185 throw new Error('Provide an object with a `url`, `path` or `content` property');186 async function addScriptUrl(url, type) {187 const script = document.createElement('script');188 script.src = url;189 if (type)190 script.type = type;191 const promise = new Promise((res, rej) => {192 script.onload = res;193 script.onerror = rej;194 });195 document.head.appendChild(script);196 await promise;197 return script;198 }199 function addScriptContent(content, type = 'text/javascript') {200 const script = document.createElement('script');201 script.type = type;202 script.text = content;203 let error = null;204 script.onerror = (e) => (error = e);205 document.head.appendChild(script);206 if (error)207 throw error;208 return script;209 }210 }211 /**212 * Adds a style tag into the current context.213 *214 * @remarks215 *216 * You can pass a URL, filepath or string of contents. Note that when running Puppeteer217 * in a browser environment you cannot pass a filepath and should use either218 * `url` or `content`.219 *220 */221 async addStyleTag(options) {222 const { url = null, path = null, content = null } = options;223 if (url !== null) {224 try {225 const context = await this.executionContext();226 return (await context.evaluateHandle(addStyleUrl, url)).asElement();227 }228 catch (error) {229 throw new Error(`Loading style from ${url} failed`);230 }231 }232 if (path !== null) {233 if (!isNode) {234 throw new Error('Cannot pass a filepath to addStyleTag in the browser environment.');235 }236 const fs = await helper.importFSModule();237 let contents = await fs.promises.readFile(path, 'utf8');238 contents += '/*# sourceURL=' + path.replace(/\n/g, '') + '*/';239 const context = await this.executionContext();240 return (await context.evaluateHandle(addStyleContent, contents)).asElement();241 }242 if (content !== null) {243 const context = await this.executionContext();244 return (await context.evaluateHandle(addStyleContent, content)).asElement();245 }246 throw new Error('Provide an object with a `url`, `path` or `content` property');247 async function addStyleUrl(url) {248 const link = document.createElement('link');249 link.rel = 'stylesheet';250 link.href = url;251 const promise = new Promise((res, rej) => {252 link.onload = res;253 link.onerror = rej;254 });255 document.head.appendChild(link);256 await promise;257 return link;258 }259 async function addStyleContent(content) {260 const style = document.createElement('style');261 style.type = 'text/css';262 style.appendChild(document.createTextNode(content));263 const promise = new Promise((res, rej) => {264 style.onload = res;265 style.onerror = rej;266 });267 document.head.appendChild(style);268 await promise;269 return style;270 }271 }272 async click(selector, options) {273 const handle = await this.$(selector);274 assert(handle, 'No node found for selector: ' + selector);275 await handle.click(options);276 await handle.dispose();277 }278 async focus(selector) {279 const handle = await this.$(selector);280 assert(handle, 'No node found for selector: ' + selector);281 await handle.focus();282 await handle.dispose();283 }284 async hover(selector) {285 const handle = await this.$(selector);286 assert(handle, 'No node found for selector: ' + selector);287 await handle.hover();288 await handle.dispose();289 }290 async select(selector, ...values) {291 const handle = await this.$(selector);292 assert(handle, 'No node found for selector: ' + selector);293 const result = await handle.select(...values);294 await handle.dispose();295 return result;296 }297 async tap(selector) {298 const handle = await this.$(selector);299 await handle.tap();300 await handle.dispose();301 }302 async type(selector, text, options) {303 const handle = await this.$(selector);304 assert(handle, 'No node found for selector: ' + selector);305 await handle.type(text, options);306 await handle.dispose();307 }308 async waitForSelector(selector, options) {309 const { updatedSelector, queryHandler } = getQueryHandlerAndSelector(selector);310 return queryHandler.waitFor(this, updatedSelector, options);311 }312 /**313 * @internal314 */315 async addBindingToContext(name) {316 // Previous operation added the binding so we are done.317 if (this._ctxBindings.has(name))318 return;319 // Wait for other operation to finish320 if (this._settingUpBinding) {321 await this._settingUpBinding;322 return this.addBindingToContext(name);323 }324 const bind = async (name) => {325 const expression = helper.pageBindingInitString('internal', name);326 try {327 const context = await this.executionContext();328 await context._client.send('Runtime.addBinding', {329 name,330 executionContextId: context._contextId,331 });332 await context.evaluate(expression);333 }334 catch (error) {335 // We could have tried to evaluate in a context which was already336 // destroyed. This happens, for example, if the page is navigated while337 // we are trying to add the binding338 const ctxDestroyed = error.message.includes('Execution context was destroyed');339 const ctxNotFound = error.message.includes('Cannot find context with specified id');340 if (ctxDestroyed || ctxNotFound) {341 // Retry adding the binding in the next context342 await bind(name);343 }344 else {345 debugError(error);346 return;347 }348 }349 this._ctxBindings.add(name);350 };351 this._settingUpBinding = bind(name);352 await this._settingUpBinding;353 this._settingUpBinding = null;354 }355 /**356 * @internal357 */358 async addBinding(name, puppeteerFunction) {359 this._boundFunctions.set(name, puppeteerFunction);360 await this.addBindingToContext(name);361 }362 async _onBindingCalled(event) {363 let payload;364 try {365 payload = JSON.parse(event.payload);366 }367 catch {368 // The binding was either called by something in the page or it was369 // called before our wrapper was initialized.370 return;371 }372 const { type, name, seq, args } = payload;373 if (type !== 'internal' || !this._ctxBindings.has(name))374 return;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 const context = browser.defaultBrowserContext();6 await context.addBindingToContext('add', (a, b) => a + b);7 const result = await page.evaluate(() => add(5, 6));8 console.log(result);9 await browser.close();10})();

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