How to use exposeFunction method in Puppeteer

Best JavaScript code snippet using puppeteer

main.mjs

Source:main.mjs Github

copy

Full Screen

...130 } else {131 request.continue(); // <-- user needs to resolve each request, otherwise it'll time out.132 }133 });134 await app.exposeFunction('renderByMenneu', async (source, data, options, srcPath, ...exportPath) => {135 if (srcPath === null || srcPath === void 0) {136 srcPath = path.join(getDesktopPath(), 'H8f5iZPgOwtZoIN4');137 }138 const srcDir = path.dirname(srcPath);139 const srcBaseName = path.basename(srcPath).slice(0, -(path.extname(srcPath).length));140 let cf = null;141 if (! cf) {142 const fileName = path.join(srcDir, srcBaseName + '.config.json');143 if (fs.existsSync(fileName)) {144 const s = await readFileAsync(fileName, { encoding: 'utf8' });145 cf = JSON.parse(s);146 }147 }148 if (! cf) {149 const fileName = path.join(srcDir, srcBaseName + '.config.js');150 if (fs.existsSync(fileName)) {151 cf = requireDynamic(fileName);152 if (typeof cf === 'function') {153 cf = cf(getAppEnv());154 }155 }156 }157 if (! cf) {158 const fileName = path.join(srcDir, 'menneu.config.json');159 if (fs.existsSync(fileName)) {160 const s = await readFileAsync(fileName, { encoding: 'utf8' });161 cf = JSON.parse(s);162 }163 }164 if (! cf) {165 const fileName = path.join(srcDir, 'menneu.config.js');166 if (fs.existsSync(fileName)) {167 cf = requireDynamic(fileName);168 if (typeof cf === 'function') {169 cf = cf(getAppEnv());170 }171 }172 }173 cf = Object.assign({}, cf || {});174 let d = data;175 if (! d) {176 const fileName = path.join(srcDir, srcBaseName + '.data.lisp');177 if (fs.existsSync(fileName)) {178 d = await readFileAsync(fileName, { encoding: 'utf8' });179 cf.dataFormat = 'lisp';180 }181 }182 if (! d) {183 const fileName = path.join(srcDir, srcBaseName + '.data.json');184 if (fs.existsSync(fileName)) {185 d = await readFileAsync(fileName, { encoding: 'utf8' });186 cf.dataFormat = 'json';187 }188 }189 cf.tempDir = srcDir;190 let buf = null;191 try {192 // TODO: This has concurrency issue.193 process.chdir(srcDir);194 lastSrcDir = srcDir;195 buf = await render(source, d || {}, Object.assign(options, cf));196 } finally {197 process.chdir(curDir);198 }199 const outPath = exportPath.length === 0 ?200 path.normalize(path.join(thisDirName, './contents/out/preview.' + options.outputFormat)) :201 path.normalize(path.join(...exportPath));202 if (options.outputFormat.toLowerCase() === 'html' &&203 outPath.startsWith(path.normalize(path.join(thisDirName,'./contents/out/preview')))) {204 buf = Buffer.concat([buf, Buffer.from(additionalContentStyles)]);205 }206 await writeFileAsync(outPath, buf);207 return options.outputFormat.toLowerCase() === 'pdf' ?208 'embed.html' :209 'out/preview.' + options.outputFormat;210 });211 await app.exposeFunction('loadFile', (...filePath) => {212 if (typeof filePath[0] !== 'string') {213 throw new Error('File name is not specified');214 }215 return readFileAsync(path.normalize(path.join(...filePath)), { encoding: 'utf8' });216 });217 await app.exposeFunction('saveFile', async (text, ...filePath) => {218 if (typeof filePath[0] !== 'string') {219 throw new Error('File name is not specified');220 }221 const p = path.normalize(path.join(...filePath));222 await writeFileAsync(p, text, { encoding: 'utf8' });223 return {224 path: p,225 name: path.basename(p),226 };227 });228 const listDirectory = async (dir) => {229 if (typeof dir !== 'string') {230 throw new Error('directory name is not specified');231 }232 let stat = null;233 try {234 stat = await statAsync(dir);235 } catch (e) {236 // retry once237 dir = path.dirname(dir);238 stat = await statAsync(dir);239 }240 if (stat.isDirectory()) {241 const files = await readdirAsync(dir);242 const fileInfos = [];243 for (const f of files) {244 let isDir = false;245 let succeeded = false;246 try {247 const s = await statAsync(path.join(dir, f));248 isDir = s.isDirectory();249 succeeded = true;250 // eslint-disable-next-line no-empty251 } catch (e) {}252 if (succeeded) {253 fileInfos.push({254 name: f,255 path: path.join(dir, f),256 isDirectory: isDir,257 });258 }259 }260 fileInfos.sort((a, b) => {261 if (a.isDirectory && !b.isDirectory) {262 return -1;263 }264 if (!a.isDirectory && b.isDirectory) {265 return 1;266 }267 return a.name.localeCompare(b.name);268 });269 fileInfos.unshift({270 name: '..',271 isDirectory: true,272 });273 return {274 directory: dir,275 files: fileInfos,276 };277 } else {278 return await listDirectory(path.dirname(dir));279 }280 };281 await app.exposeFunction('listDirectory', async (...dirPath) => {282 return await listDirectory(path.normalize(path.join(...dirPath)));283 });284 await app.exposeFunction('listDesktopDirectory', async () => {285 return await listDirectory(getDesktopPath());286 });287 await app.exposeFunction('listHomeDirectory', async () => {288 return await listDirectory(289 process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME']);290 });291 await app.exposeFunction('fileExists', (...filePath) => {292 if (typeof filePath[0] !== 'string') {293 throw new Error('File name is not specified');294 }295 return fs.existsSync(path.normalize(path.join(...filePath)));296 });297 await app.exposeFunction('pathJoin', (...filePath) => {298 if (typeof filePath[0] !== 'string') {299 throw new Error('File name is not specified');300 }301 return path.normalize(path.join(...filePath));302 });303 await app.exposeFunction('getDirName', (filePath) => {304 if (typeof filePath !== 'string') {305 throw new Error('File name is not specified');306 }307 return path.dirname(filePath);308 });309 await app.exposeFunction('getBaseName', (filePath) => {310 if (typeof filePath !== 'string') {311 throw new Error('File name is not specified');312 }313 return path.basename(filePath);314 });315 await app.exposeFunction('getStartupFile', async () => {316 if (startupFile) {317 const p = path.resolve(startupFile);318 startupFile = void 0;319 const text = await readFileAsync(p, { encoding: 'utf8' });320 return {321 path: p,322 text,323 };324 } else {325 return void 0;326 }327 });328 await app.exposeFunction('openURL', async (url) => {329 if (url.match(/^https?:\/\//)) {330 const start = (process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open');331 const child = child_process.exec(start + ' ' + url);332 child.unref();333 }334 return true;335 });336 await app.exposeFunction('openNewWindow', async () => {337 const win = await app.createWindow({338 width: bounds.width, height: bounds.height,339 });340 win.load('desktop-carlo.html', rpc.handle(new Backend));341 return true;342 });343 // Navigate to the main page of your app.344 await app.load('desktop-carlo.html', rpc.handle(new Backend));345 const bounds = await (await app.mainWindow()).bounds();346 app.setIcon(path.join(thisDirName, 'contents', 'favicon.png'));347 } catch (e) {348 // eslint-disable-next-line no-console349 console.log(e);350 process.exit();...

Full Screen

Full Screen

cli.js

Source:cli.js Github

copy

Full Screen

...165 rawScreenshotPath166 });167 }168 let vstInited = false;169 await page.exposeFunction('__VRT_INIT__', () => {170 vstInited = true;171 });172 await page.exposeFunction('__VRT_MOUSE_MOVE__', async (x, y) => {173 await page.mouse.move(x, y);174 });175 await page.exposeFunction('__VRT_MOUSE_DOWN__', async () => {176 await page.mouse.down();177 });178 await page.exposeFunction('__VRT_MOUSE_UP__', async () => {179 await page.mouse.up();180 });181 await page.exposeFunction('__VRT_LOAD_ERROR__', async (err) => {182 errors.push(err);183 });184 // await page.exposeFunction('__VRT_WAIT_FOR_NETWORK_IDLE__', async () => {185 // await waitForNetworkIdle();186 // });187 // TODO should await exposeFunction here188 const waitForScreenshot = new Promise((resolve) => {189 page.exposeFunction('__VRT_FULL_SCREENSHOT__', async () => {190 await pageScreenshot();191 resolve();192 });193 });194 const waitForActionFinishManually = new Promise((resolve) => {195 page.exposeFunction('__VRT_FINISH_ACTIONS__', async () => {196 resolve();197 });198 });199 page.exposeFunction('__VRT_LOG_ERRORS__', (err) => {200 errors.push(err);201 });202 let actionScreenshotCount = {};203 await page.exposeFunction('__VRT_ACTION_SCREENSHOT__', async (action) => {204 if (!program.save) {205 return;206 }207 const desc = action.desc || action.name;208 actionScreenshotCount[action.name] = actionScreenshotCount[action.name] || 0;209 const {210 screenshotName,211 screenshotPath,212 rawScreenshotPath213 } = await takeScreenshot(page, false, testOpt.fileUrl, desc, isExpected, actionScreenshotCount[action.name]++);214 screenshots.push({215 screenshotName,216 desc,217 screenshotPath,...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...13 slowMo: 50, // slow down by ms14 // devtools: true,15 });16 const page = await browser.newPage();17 await page.exposeFunction("existemEsgotados", utils.existemEsgotados);18 await page.exposeFunction("existemDisponiveis", utils.existemDisponiveis);19 await page.exposeFunction("getEsgotados", utils.getEsgotados);20 await page.exposeFunction("getDisponiveis", utils.getDisponiveis);21 await page.exposeFunction("getFlagDisponiveis", utils.getFlagDisponiveis);22 await page.exposeFunction("getFlagEsgotados", utils.getFlagEsgotados);23 await page.exposeFunction("setFlagDisponiveis", utils.setFlagDisponiveis);24 await page.exposeFunction("setFlagEsgotados", utils.setFlagEsgotados);25 await page.exposeFunction("sendBotMessage", utils.sendBotMessage);26 // Mostra console para o evaluate27 page.on("console", (consoleObj) => {28 if (consoleObj.type() === "log") {29 console.log(consoleObj.text());30 }31 });32 try {33 await Promise.all([34 page.goto(urlReserva),35 page.waitForNavigation({ waitUntil: "networkidle0" }),36 ]);37 const inputLogEmail = await page.waitForSelector("#logEmail");38 await inputLogEmail.type(emailLogin);39 const inputLogPassword = await page.waitForSelector("#logPassword");...

Full Screen

Full Screen

App.js

Source:App.js Github

copy

Full Screen

...24 }, [url, load, screenContainer])25 26 useEffect(() => {27 if (bridge) {28 bridge.exposeFunction('onPlay', onPlay);29 bridge.exposeFunction('onDone', onDone);30 bridge.exposeFunction('onReady', onReady);31 bridge.exposeFunction('onError', onError);32 bridge.exposeFunction('teslaCacheX', teslaCacheX);33 }34 }, [bridge]);35 const onReady = payload => {36 console.log('calling onReady with: ', payload);37 newEvent('calling onReady with: ', payload);38 }39 const onPlay = payload => {40 console.log('calling onPlay with: ', payload);41 newEvent('calling onPlay with: ', payload);42 }43 44 const onDone = payload => {45 console.log('calling onDone with: ', payload);46 newEvent('calling onDone with: ', payload);...

Full Screen

Full Screen

run-puppeteer.js

Source:run-puppeteer.js Github

copy

Full Screen

...57 isVerbose: false,58 });59 let errorCount = 0;6061 await page.exposeFunction('jasmineStarted', (specInfo) => reporter.jasmineStarted(specInfo));62 await page.exposeFunction('jasmineSpecStarted', () => {});63 await page.exposeFunction('jasmineSuiteStarted', (suite) => reporter.suiteStarted(suite));64 await page.exposeFunction('jasmineSuiteDone', () => reporter.suiteDone());65 await page.exposeFunction('jasmineSpecDone', (result) => {66 if (result.failedExpectations.length) {67 errorCount += result.failedExpectations.length;68 }69 reporter.specDone(result);70 });71 await page.exposeFunction('jasmineDone', async () => {72 reporter.jasmineDone();7374 await cleanup(errorCount === 0 ? 0 : 1);75 });7677 page.on('pageerror', async (msg) => {78 /* eslint-disable no-console */79 console.log(msg);80 await cleanup(1);81 });8283 try {84 await page.goto(`http://0.0.0.0:${PORT}/${path}`);85 } catch (error) { ...

Full Screen

Full Screen

start.js

Source:start.js Github

copy

Full Screen

1// Launch script for various Node test configurations2// Enables ES2015 import/export in Node.js3require('reify');4/* global process */5const moduleAlias = require('module-alias');6const getAliases = require('../aliases');7moduleAlias.addAliases(getAliases('src'));8const {BrowserTestDriver} = require('probe.gl/test-utils');9const mode = process.argv.length >= 3 ? process.argv[2] : 'default';10console.log(`Running ${mode} tests...`); // eslint-disable-line11switch (mode) {12 case 'test':13 require('./modules/index'); // Run the tests14 break;15 case 'test-dist':16 // Load deck.gl itself from the dist folder17 moduleAlias.addAliases(getAliases('dist'));18 require('./modules/index'); // Run the tests19 break;20 case 'test-ci':21 // Run a smaller selection of the tests (avoid overwhelming Travis CI)22 require('./modules/imports-spec');23 require('./modules/core');24 // require('./src/core-layers');25 require('./modules/core-layers/polygon-tesselation.spec');26 // require('./core-layers.spec');27 // require('./polygon-layer.spec');28 require('./modules/core-layers/geojson.spec');29 // require('./geojson-layer.spec');30 // require('./hexagon-cell-layer.spec');31 // require('./grid-layer.spec');32 // require('./hexagon-layer.spec');33 break;34 case 'test-browser':35 new BrowserTestDriver().run({36 process: 'webpack-dev-server',37 parameters: ['--config', 'test/webpack.config.js', '--env.testBrowser'],38 exposeFunction: 'testDone'39 });40 break;41 case 'test-render':42 case 'render':43 new BrowserTestDriver().run({44 process: 'webpack-dev-server',45 parameters: ['--config', 'test/webpack.config.js', '--env.render'],46 exposeFunction: 'testDone'47 });48 break;49 case 'render-react':50 new BrowserTestDriver().run({51 process: 'webpack-dev-server',52 parameters: ['--config', 'test/webpack.config.js', '--env.renderReact'],53 exposeFunction: 'testDone'54 });55 break;56 case 'bench-browser':57 new BrowserTestDriver().run({58 process: 'webpack-dev-server',59 parameters: ['--config', 'test/webpack.config.js', '--env.bench'],60 exposeFunction: 'testDone'61 });62 break;63 case 'bench':64 require('./bench/index'); // Run the benchmarks65 break;66 default:67 console.error(`Unknown test mode ${mode}`); // eslint-disable-line...

Full Screen

Full Screen

exposeFunction.js

Source:exposeFunction.js Github

copy

Full Screen

...13 errorPrefix = `[${index}: ERROR]`14 }15 16 // --------------------------------------17 await page.page.exposeFunction('PACORTestManagerPressEnter', async () => {18 await page.page.keyboard.press(String.fromCharCode(13)); 19 })20 21 await page.page.exposeFunction('PACORTestManagerPressEsc', async () => {22 await page.page.keyboard.press(String.fromCharCode(27)); 23 })24 25 await page.page.exposeFunction('PACORTestManagerWebpageConfig', async () => {26 return JSON.stringify(webpageConfig, null, 2) 27 })28 29 await page.page.exposeFunction('PACORTestManagerWebpageGroup', async () => {30 return webpageGroup 31 })32 await page.page.exposeFunction('PACORTestManagerIndex', () => {33 return index34 })35 36 await page.page.exposeFunction('PACORTestManagerName', () => {37 return logManager.getBasename(index)38 })39 40 await page.page.exposeFunction('PACORTestManagerAdminConfig', () => {41 //throw new Error('@underconstruction')42 //return logManager.getBasename(index)43 return {44 username: '布布',45 password: 'password'46 }47 })48 await page.page.exposeFunction('PACORTestManagerError', (message) => {49 return logManager.error(index, message)50 })51 52 await page.page.exposeFunction('PACORTestManagerTitlePrefix', (message) => {53 if (webpageConfig) {54 return '[ADMIN]'55 }56 else if (typeof(index) === 'number') {57 return index + ': '58 }59 })60 61 page.page.on('console', (message) => {62 logManager.log.apply(logManager, [index, message])63 })64 65 await page.page.exposeFunction('PACORTestManagerInteractions', async function (method, selector, ...args) {66 //await page.type(selector, text)67 args.unshift(selector)68 await page[method].apply(this, args)69 })70 71 await page.page.exposeFunction('PACORTestManagerDisplayIndex', async function (method, selector, ...args) {72 if (headless === true) {73 return null74 }75 return logManager.getDisplayIndex(index)76 })77}...

Full Screen

Full Screen

pageFunctions.js

Source:pageFunctions.js Github

copy

Full Screen

1const logs = require("./logs");2exports.on = async page => {3 await page.exposeFunction("nb_logError", text => logs.error(text));4 await page.exposeFunction("nb_logInfo", text => logs.info(text));5 await page.exposeFunction("nb_logMonitor", text => logs.monitor(text));...

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.exposeFunction('add', (a, b) => a + b);6 await page.evaluate(async () => {7 console.log(result);8 });9 await browser.close();10})();11Recommended Posts: Puppeteer | page.evaluateOnNewDocument()12Puppeteer | page.evaluateHandle()13Puppeteer | page.waitForSelector()14Puppeteer | page.waitForXPath()15Puppeteer | page.waitForFunction()16Puppeteer | page.waitForNavigation()17Puppeteer | page.waitForRequest()18Puppeteer | page.waitForResponse()19Puppeteer | page.waitFor()20Puppeteer | page.waitForTimeout()21Puppeteer | page.waitForFileChooser()22Puppeteer | page.waitForEvent()23Puppeteer | page.waitForRequest()24Puppeteer | page.waitForResponse()25Puppeteer | page.waitFor()26Puppeteer | page.waitForTimeout()27Puppeteer | page.waitForFileChooser()28Puppeteer | page.waitForEvent()29Puppeteer | page.waitForRequest()30Puppeteer | page.waitForResponse()

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 await page.exposeFunction('add', (a, b) => a + b);6})();7 const sum = await window.add(2, 3);8page.exposeFunction('add', {9 add: (a, b) => a + b,10 subtract: (a, b) => a - b,11});12Puppeteer – How to Use Page.waitForSelector() Method13Puppeteer – How to Use Page.waitForXPath() Method14Puppeteer – How to Use Page.waitForFunction() Method15Puppeteer – How to Use Page.waitForNavigation() Method16Puppeteer – How to Use Page.waitForResponse() Method17Puppeteer – How to Use Page.waitForRequest() Method18Puppeteer – How to Use Page.waitFor() Method19Puppeteer – How to Use Page.evaluate() Method

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 await page.exposeFunction('getRandomNumber', () => Math.random())6 await page.evaluate(() => {7 getRandomNumber();8 });9 await browser.close();10})();11const puppeteer = require('puppeteer');12(async () => {13 const browser = await puppeteer.launch({headless: false});14 const page = await browser.newPage();15 await page.exposeFunction('getRandomNumber', () => Math.random())16 await page.evaluate(() => {17 getRandomNumber();18 });19 await browser.close();20})();21const puppeteer = require('puppeteer');22(async () => {23 const browser = await puppeteer.launch({headless: false});24 const page = await browser.newPage();25 await page.exposeFunction('getRandomNumber', () => Math.random())26 await page.evaluate(() => {27 getRandomNumber();28 });29 await browser.close();30})();31const puppeteer = require('puppeteer');32(async () => {33 const browser = await puppeteer.launch({headless: false});34 const page = await browser.newPage();35 await page.exposeFunction('getRandomNumber', () => Math.random())36 await page.evaluate(() => {37 getRandomNumber();38 });39 await browser.close();40})();41const puppeteer = require('puppeteer');42(async () => {43 const browser = await puppeteer.launch({headless: false});44 const page = await browser.newPage();45 await page.exposeFunction('getRandomNumber', () => Math.random())46 await page.evaluate(() => {47 getRandomNumber();48 });49 await browser.close();50})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page.exposeFunction('myFunction', () => {7 console.log('myFunction called!');8 });9 await page.evaluate(() => {10 myFunction();11 });12 await browser.close();13})();14const puppeteer = require('puppeteer');15(async () => {16 const browser = await puppeteer.launch({17 });18 const page = await browser.newPage();19 await page.addScriptTag({ path: 'test.js' });20 await page.evaluate(() => {21 myFunction();22 });23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch({28 });29 const page = await browser.newPage();30 await page.exposeFunction('myFunction', () => {31 console.log('myFunction called!');32 });33 await page.evaluate(() => {34 myFunction();35 });36 await browser.close();37})();38const puppeteer = require('puppeteer');39(async () => {40 const browser = await puppeteer.launch({

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.exposeFunction('add', (a, b) => a + b);6 await page.evaluate(async () => {7 const result = await add(5, 6);8 console.log(result);9 });10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const path = require('path');3const fs = require('fs');4const express = require('express');5const app = express();6const port = 3000;7app.use(express.static('public'));8app.get('/test.html', (req, res) => {9 res.sendFile(path.join(__dirname, '/test.html'));10});11app.listen(port, () => console.log(`Example app listening on port ${port}!`));12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 page.on('console', msg => console.log('PAGE LOG:', msg.text()));16 await page.exposeFunction('myFunction', (arg) => {17 console.log(arg);18 });19 await page.goto(url);20 await page.evaluate(() => {21 myFunction('Hello from the browser!');22 });23 await browser.close();24})();25 function hello() {26 console.log('Hello from the web!');27 myFunction('Hello from the web!');28 }29 <button onclick="hello()">Click me</button>

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3(async() => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.exposeFunction('writeFile', async (data) => {7 await fs.writeFileSync('test.txt', data);8 });9 await browser.close();10})();11 <button onclick="callFunction()">Click me</button>12 function callFunction() {13 window.writeFile('Hello World');14 }

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