Best JavaScript code snippet using puppeteer
BenchmarkLib.js
Source: BenchmarkLib.js
...14function formatDate(date) {15 date = date || new Date();16 return date.getFullYear() + pad(date.getMonth() + 1, 2) + pad(date.getDate(), 2) + "_" + pad(date.getHours(), 2) + pad(date.getMinutes(), 2);17}18function parseOrientation(orientation, defaultValue) {19 if ((orientation.x !== undefined) || (orientation.y !== undefined) || (orientation.z !== undefined) || (orientation.w !== undefined)) {20 return orientation21 } else if ((orientation.yaw !== undefined) || (orientation.pitch !== undefined) || (orientation.roll !== undefined)) {22 var y = 0.023 var p = 0.024 var r = 0.025 if (orientation.pitch !== undefined) {26 p = orientation.pitch27 }28 if (orientation.yaw !== undefined) {29 y = orientation.yaw30 }31 if (orientation.roll !== undefined) {32 r = orientation.roll33 }34 return Quat.fromPitchYawRollDegrees(p, y, r)35 }36 return defaultValue37}38TestScript = function (properties) {39 properties = properties || {};40 this.dateString = formatDate();41 this.tests = [];42 return this;43};44// url - URL to load domain from45// waitIdle46// position - initial position47// orientation - initial orientation48// delay_secs - time to wait before starting benchmark (gives domain time to load)49TestScript.locationLoader = function (url, waitIdle, position, orientation, delay_secs) {50 return function () {51 print("QQQ going to URL " + url);52 Window.location = url;53 54 if (delay_secs !== null) {55 Test.wait(delay_secs * 1000);56 } else {57 Test.wait(3 * 1000);58 }59 60 if (!Test.waitForConnection()) {61 return false;62 }63 if (position) {64 MyAvatar.position = position;65 }66 if (orientation) {67 MyAvatar.orientation = orientation;68 }69 if (waitIdle) {70 print("QQQ waiting for idle");71 Test.waitIdle();72 }73 return true;74 };75};76TestScript.locationSteps = function(steps) {77 return function () {78 print("TEST locationSteps : " + JSON.stringify(steps))79 var len = steps.length;80 for (var i = 0; i < len; i++) {81 var step = steps[i];82 if (step.dt !== undefined) {83 var dt = step.dt;84 var nextPos = MyAvatar.position;85 if (step.pos !== undefined) {86 nextPos = step.pos;87 }88 var nextOri = MyAvatar.orientation;89 if (step.ori !== undefined) {90 nextOri = parseOrientation(step.ori, MyAvatar.orientation);91 }92 Test.wait(dt * 1000.0)93 MyAvatar.position = nextPos;94 MyAvatar.orientation = nextOri;95 }96 }97 }98}99var MOUSE_POS;100Controller.mouseMoveEvent.connect(function(event) {101 MOUSE_POS = { x: event.x, y: event.y }102});103TestScript.measureTimingSteps = function(steps) {104 return function () {105 print("TEST measureTimingSteps : " + JSON.stringify(steps))106 var output = [ [ "Game (fps)", "Render (fps)", "Present (fps)", "Engine (ms)", "GPU (ms)", "Batch (ms)" ] ];107 var len = steps.length;108 for (var i = 0; i < len; i++) {109 var step = steps[i];110 if (step.time !== undefined && step.step !== undefined) {111 var TOTAL_TIME = step.time;112 var TIME_STEP = step.step;113 var KEEP_ACTIVE = step.keepActive;114 var nextPos = MyAvatar.position;115 if (step.pos !== undefined) {116 nextPos = step.pos;117 }118 var nextOri = MyAvatar.orientation;119 if (step.ori !== undefined) {120 nextOri = parseOrientation(step.ori, MyAvatar.orientation);121 }122 MyAvatar.position = nextPos;123 MyAvatar.orientation = nextOri;124 var t = 0;125 var totalSamples = TOTAL_TIME / TIME_STEP;126 MOUSE_POS = Reticle.position;127 var measuredTimes = [ 0, 0, 0, 0, 0, 0 ];128 var numSamples = 0;129 while (t < TOTAL_TIME) {130 measuredTimes[0] += Rates.simulation;131 measuredTimes[1] += Rates.render;132 measuredTimes[2] += Rates.present;133 measuredTimes[3] += LODManager.engineRunTime;134 measuredTimes[4] += LODManager.gpuTime;...
fetch_devices.js
Source: fetch_devices.js
...145 /**146 * @param {*} json147 * @return {!{width: number, height: number}}148 */149 function parseOrientation(json) {150 const result = {};151 const minDeviceSize = 50;152 const maxDeviceSize = 9999;153 result.width = parseIntValue(json, 'width');154 if (result.width < 0 || result.width > maxDeviceSize ||155 result.width < minDeviceSize)156 throw new Error('Emulated device has wrong width: ' + result.width);157 result.height = parseIntValue(json, 'height');158 if (result.height < 0 || result.height > maxDeviceSize ||159 result.height < minDeviceSize)160 throw new Error('Emulated device has wrong height: ' + result.height);161 return /** @type {!{width: number, height: number}} */ (result);162 }163 const result = {};164 result.type = /** @type {string} */ (parseValue(json, 'type', 'string'));165 result.userAgent = /** @type {string} */ (parseValue(json, 'user-agent', 'string'));166 const capabilities = parseValue(json, 'capabilities', 'object', []);167 if (!Array.isArray(capabilities))168 throw new Error('Emulated device capabilities must be an array');169 result.capabilities = [];170 for (let i = 0; i < capabilities.length; ++i) {171 if (typeof capabilities[i] !== 'string')172 throw new Error('Emulated device capability must be a string');173 result.capabilities.push(capabilities[i]);174 }175 result.deviceScaleFactor = /** @type {number} */ (parseValue(json['screen'], 'device-pixel-ratio', 'number'));176 if (result.deviceScaleFactor < 0 || result.deviceScaleFactor > 100)177 throw new Error('Emulated device has wrong deviceScaleFactor: ' + result.deviceScaleFactor);178 result.vertical = parseOrientation(parseValue(json['screen'], 'vertical', 'object'));179 result.horizontal = parseOrientation(parseValue(json['screen'], 'horizontal', 'object'));180 return result;181}182/**183 * @param {url}184 * @return {!Promise}185 */186function httpGET(url) {187 let fulfill, reject;188 const promise = new Promise((res, rej) => {189 fulfill = res;190 reject = rej;191 });192 const driver = url.startsWith('https://') ? require('https') : require('http');193 const request = driver.get(url, response => {...
app.js
Source: app.js
...69 robot: robot,70 lost: lost71 };72}73function parseOrientation(orientation) {74 switch (orientation) {75 case 0:76 return 'E';77 case 90:78 return 'N';79 case 180:80 return 'W';81 case 270:82 return 'S';83 }84}85const init = function (size) {86 MAX_X = parseInt(size.split(' ')[0]);87 MAX_Y = parseInt(size.split(' ')[1]);88 robot = {};89 instructions = [];90 scents = [];91 output = '';92 lostRobots = 0;93 for (let i = 0; i <= MAX_X; i++){94 scents.push(new Array(MAX_Y));95 for (let j = 0; j <= MAX_Y; j++){96 scents[i][j] = false;97 }98 }99}100const saveStats = function(){101 fs.writeFileSync('output.txt', 'Martian Robots\n' +102 '-------------------------------\n' +103 'Size of Mars: ' + MAX_X + ' ' + MAX_Y + '\n' +104 'Initial coordinates and orientation: ' + robot.x + ' ' + robot.y + ' ' + parseOrientation(robot.orientation) + '\n' +105 'Instructions: ' + instructions + '\n' +106 '\nOutput: ' + output + '\n' +107 'Number of lost robots: ' + lostRobots, function (error) {108 if (error){109 console.error(error);110 }111 });112}113const run = function(coordinates, instruction){114 if (coordinates === ''){115 rl.close();116 console.log(output);117 saveStats();118 process.exit(0);119 }120 robot.x = parseInt(coordinates.split(' ')[0]);121 robot.y = parseInt(coordinates.split(' ')[1]);122 switch (coordinates.split(' ')[2]) {123 case 'N':124 robot.orientation = 90;125 break;126 case 'S':127 robot.orientation = 270;128 break;129 case 'W':130 robot.orientation = 180;131 break;132 case 'E':133 robot.orientation = 0;134 break;135 }136 instructions = [];137 for (let i = 0; i < instruction.length; i++){138 instructions.push(instruction.charAt(i));139 }140 let result;141 for (let i = 0; i < instructions.length; i++){142 result = moveRobot(instructions[i], robot, MAX_X, MAX_Y);143 robot = result.robot;144 if (result.lost){145 break;146 }147 }148 if (result.lost){149 output = output.concat(result.robot.x + ' ' + result.robot.y + ' ' + parseOrientation(result.robot.orientation) + ' LOST\n');150 lostRobots++;151 } else {152 output = output.concat(result.robot.x + ' ' + result.robot.y + ' ' + parseOrientation(result.robot.orientation) + '\n');153 }154 return output;155}...
cli.js
Source: cli.js
...9const options = {};10const map = (loc, parser = (v => v)) => (v) => v && _set(options, loc, parser(v));11const mapUnit = (loc) => map(loc, parseUnit);12const mapNumber = (loc) => map(loc, parseNumber);13const mapLandscape = map('landscape', v => parseOrientation(v) === 'landscape');14const mapBoolean = (loc, flagName) => () => {15 _set(options, loc, !process.argv.includes('--no-' + flagName));16};17program18 .version(pkg.version)19 .arguments('[input] [output]')20 .option('-B, --margin-bottom <unitreal>', 'Set the page bottom margin', mapUnit('margin.bottom'))21 .option('-L, --margin-left <unitreal>', 'Set the page left margin (default 10mm)', mapUnit('margin.left'))22 .option('-R, --margin-right <unitreal>', 'Set the page right margin (default 10mm)', mapUnit('margin.right'))23 .option('-T, --margin-top <unitreal>', 'Set the page top margin', mapUnit('margin.top'))24 .option('-O, --orientation <orientation>', 'Set orientation to Landscape or Portrait (default Portrait)', mapLandscape)25 .option('-s, --page-size <Size>', 'Set paper size to: A4, Letter, etc. (default A4)', map('format'))26 .option('--page-height <unitreal>', 'Page height', mapUnit('height'))27 .option('--page-width <unitreal>', 'Page width', mapUnit('width'))...
Info.plist.js
Source: Info.plist.js
1const plistEditor = require('./editor/plist');2function parseOrientation(o) {3 if (o === 'landscape') {4 return ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];5 } else if (o === 'portrait') {6 return ['UIInterfaceOrientationPortrait'];7 }8 return [9 'UIInterfaceOrientationLandscapeLeft',10 'UIInterfaceOrientationLandscapeRight',11 'UIInterfaceOrientationPortrait',12 ];13}14module.exports = function infoPlist(file) {15 const editor = plistEditor(file);16 editor.addMethod('orientation', (g, orientation) => {17 g.set({18 UISupportedInterfaceOrientations: parseOrientation(orientation),19 });20 });21 editor.addMethod('fullScreen', (g, fullScreen) => {22 g.set({23 UIStatusBarHidden: fullScreen,24 UIRequiresFullScreen: fullScreen,25 });26 });27 editor.addMethod('link', (g, name, scheme) => {28 const schemes = [scheme === undefined ? name : scheme];29 const n = g.find('CFBundleURLTypes', b => b.CFBundleURLName === name);30 if (n) {31 n.CFBundleURLSchemes = schemes;32 } else {...
cli-validation.js
Source: cli-validation.js
2 if (/\d+(em|vh|px|cm|mm)/.test(value))3 return value;4 return undefined;5}6function parseOrientation(value) {7 value = value.trim().toLowerCase();8 if (value == 'landscape')9 return value;10 return 'portrait';11}12function parsePaperSize(value) {13 if (['A4', 'Letter'].includes(value))14 return value;15}16function parseNumber(value) {17 return parseFloat(value);18}19module.exports = {20 parseUnits,...
Using AI Code Generation
1const puppeteer = require('puppeteer');2const devices = require('puppeteer/DeviceDescriptors');3const iPhone = devices['iPhone 6'];4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 await page.emulate(iPhone);8 await page.screenshot({path: 'example.png'});9 await browser.close();10})();11const puppeteer = require('puppeteer');12const devices = require('puppeteer/DeviceDescriptors');13const iPhone = devices['iPhone 6'];14(async () => {15 const browser = await puppeteer.launch();16 const page = await browser.newPage();17 await page.emulate(iPhone);18 await page.screenshot({path: 'example.png'});19 await browser.close();20})();21const puppeteer = require('puppeteer');22const devices = require('puppeteer/DeviceDescriptors');23const iPhone = devices['iPhone 6'];24(async () => {25 const browser = await puppeteer.launch();26 const page = await browser.newPage();27 await page.emulate(iPhone);28 await page.screenshot({path: 'example.png'});29 await browser.close();30})();31const puppeteer = require('puppeteer');32const devices = require('puppeteer/DeviceDescriptors');33const iPhone = devices['iPhone 6'];34(async () => {35 const browser = await puppeteer.launch();36 const page = await browser.newPage();37 await page.emulate(iPhone);38 await page.screenshot({path: 'example.png'});39 await browser.close();40})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 const pdf = await page.pdf({ path: 'google.pdf', format: 'A4' });7 await browser.close();8})();9const puppeteer = require('puppeteer');10const fs = require('fs');11(async () => {12 const browser = await puppeteer.launch();13 const page = await browser.newPage();14 const pdf = await page.pdf({ path: 'google.pdf', format: 'A4' });15 await browser.close();16})();17const puppeteer = require('puppeteer');18const fs = require('fs');19(async () => {20 const browser = await puppeteer.launch();21 const page = await browser.newPage();22 const pdf = await page.pdf({ path: 'google.pdf', format: 'A4' });23 await browser.close();24})();25const puppeteer = require('puppeteer');26const fs = require('fs');27(async () => {28 const browser = await puppeteer.launch();29 const page = await browser.newPage();30 const pdf = await page.pdf({ path: 'google.pdf', format: 'A4' });31 await browser.close();32})();33const puppeteer = require('puppeteer');34const fs = require('fs');35(async () => {36 const browser = await puppeteer.launch();37 const page = await browser.newPage();38 const pdf = await page.pdf({ path: 'google.pdf', format: 'A4' });39 await browser.close();40})();41const puppeteer = require('puppeteer');42const fs = require('fs');43(async () => {
Using AI Code Generation
1const puppeteer = require('puppeteer');2const devices = require('puppeteer/DeviceDescriptors');3const iPhone = devices['iPhone 6'];4async function run() {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 await page.emulate(iPhone);8 await page.screenshot({path: 'google.png'});9 await browser.close();10}11run();12const puppeteer = require('puppeteer');13const devices = require('puppeteer/DeviceDescriptors');14const iPhone = devices['iPhone 6'];15async function run() {16 const browser = await puppeteer.launch();17 const page = await browser.newPage();18 await page.emulate(iPhone);19 await page.screenshot({path: 'google.png'});20 await browser.close();21}22run();23const puppeteer = require('puppeteer');24const devices = require('puppeteer/DeviceDescriptors');25const iPhone = devices['iPhone 6'];26async function run() {27 const browser = await puppeteer.launch();28 const page = await browser.newPage();29 await page.emulate(iPhone);30 await page.screenshot({path: 'google.png'});31 await browser.close();32}33run();34const puppeteer = require('puppeteer');35const devices = require('puppeteer/DeviceDescriptors');36const iPhone = devices['iPhone 6'];37async function run() {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page.emulate(iPhone);41 await page.screenshot({path: 'google.png'});42 await browser.close();43}44run();45const puppeteer = require('puppeteer');46const devices = require('puppeteer/DeviceDescriptors');47const iPhone = devices['iPhone 6'];48async function run() {49 const browser = await puppeteer.launch();50 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch({headless: true});5 const page = await browser.newPage();6 const pdfBuffer = await page.pdf({7 });8 await browser.close();9 fs.writeFile('google.pdf', pdfBuffer, (err) => {10 if (err) throw err;11 console.log('The file has been saved!');12 });13})();
Collect elements by class name and then click each one - Puppeteer
Excluding elements with certain classes in Puppeteer
Is it possible to simulate pressing 'Down' arrow?
What is the difference between jsHandle and elementHandle in Puppeteer?
Puppeteer - Async function in evaluate method throws error
Puppeteer / Node.js to click a button as long as it exists -- and when it no longer exists, commence action
how to ignore a region or element within the body tag when using jest-image-snapshot to compare image shots?
Opening local HTML file using Puppeteer
Puppeteer Hangs In Headless Mode
Error: EPERM: operation not permitted while running puppeteer JavaScript node
for
loop vs. Array.map()/Array.forEach()
As all puppeteer methods are asynchronous it doesn't matter how we iterate over them. I've made a comparison and a rating of the most commonly recommended and used options.
For this purpose, I have created a React.Js example page with a lot of React buttons here (I just call it Lot Of React Buttons). Here (1) we are able set how many buttons to be rendered on the page; (2) we can activate the black buttons to turn green by clicking on them. I consider it an identical use case as the OP's, and it is also a general case of browser automation (we expect something to happen if we do something on the page). Let's say our use case is:
Scenario outline: click all the buttons with the same selector
Given I have <no.> black buttons on the page
When I click on all of them
Then I should have <no.> green buttons on the page
There is a conservative and a rather extreme scenario. To click no. = 132
buttons is not a huge CPU task, no. = 1320
can take a bit of time.
In general, if we only want to perform async methods like elementHandle.click
in iteration, but we don't want to return a new array: it is a bad practice to use Array.map
. Map method execution is going to finish before all the iteratees are executed completely because Array iteration methods execute the iteratees synchronously, but the puppeteer methods, the iteratees are: asynchronous.
const elHandleArray = await page.$$('button')
elHandleArray.map(async el => {
await el.click()
})
await page.screenshot({ path: 'clicks_map.png' })
await browser.close()
Duration: 891 ms
By watching the browser in headful mode it looks like it works, but if we check when the page.screenshot
happened: we can see the clicks were still in progress. It is due to the fact the Array.map
cannot be awaited by default. It is only luck that the script had enough time to resolve all clicks on all elements until the browser was not closed.
Duration: 6868 ms
If we increase the number of elements of the same selector we will run into the following error:
UnhandledPromiseRejectionWarning: Error: Node is either not visible or not an HTMLElement
, because we already reached await page.screenshot()
and await browser.close()
: the async clicks are still in progress while the browser is already closed.
All the iteratees will be executed, but forEach is going to return before all of them finish execution, which is not the desirable behavior in many cases with async functions. In terms of puppeteer it is a very similar case to Array.map
, except: for Array.forEach
does not return a new array.
const elHandleArray = await page.$$('button')
elHandleArray.forEach(async el => {
await el.click()
})
await page.screenshot({ path: 'clicks_foreach.png' })
await browser.close()
Duration: 1058 ms
By watching the browser in headful mode it looks like it works, but if we check when the page.screenshot
happened: we can see the clicks were still in progress.
Duration: 5111 ms
If we increase the number of elements with the same selector we will run into the following error:
UnhandledPromiseRejectionWarning: Error: Node is either not visible or not an HTMLElement
, because we already reached await page.screenshot()
and await browser.close()
: the async clicks are still in progress while the browser is already closed.
The best performing solution is a slightly modified version of bside's answer. The page.$$eval (page.$$eval(selector, pageFunction[, ...args])
) runs Array.from(document.querySelectorAll(selector))
within the page and passes it as the first argument to pageFunction
. It functions as a wrapper over forEach hence it can be awaited perfectly.
await page.$$eval('button', elHandles => elHandles.forEach(el => el.click()))
await page.screenshot({ path: 'clicks_eval_foreach.png' })
await browser.close()
Duration: 711 ms
By watching the browser in headful mode we see the effect is immediate, also the screenshot is taken only after every element has been clicked, every promise has been resolved.
Duration: 3445 ms
Works just like in case of 132 buttons, extremely fast.
The simplest option, not that fast and executed in sequence. The script won't go to page.screenshot
until the loop is not finished.
const elHandleArray = await page.$$('button')
for (const el of elHandleArray) {
await el.click()
}
await page.screenshot({ path: 'clicks_for_of.png' })
await browser.close()
Duration: 2957 ms
By watching the browser in headful mode we can see the page clicks are happening in strict order, also the screenshot is taken only after every element has been clicked.
Duration: 25 396 ms
Works just like in case of 132 buttons (but it takes more time).
Array.map
if you only want to perform async events and you aren't using the returned array, use forEach or for-of instead. ❌Array.forEach
is an option, but you need to wrap it so the next async method only starts after all promises are resolved inside the forEach. ❌Array.forEach
with $$eval
for best performance if the order of async events doesn't matter inside the iteration. ✅for
/for...of
loop if speed is not vital and if the order of the async events does matter inside the iteration. ✅Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium JavaScript Tutorial.
Websites and web apps are growing in number day by day, and so are the expectations of people for a pleasant web experience. Even though the World Wide Web (WWW) was invented only in 1989 (32 years back), this technology has revolutionized the world we know back then. The best part is that it has made life easier for us. You no longer have to stand in long queues to pay your bills. You can get that done within a few minutes by visiting their website, web app, or mobile app.
As technology keeps evolving, organizations need to realign their business strategies. It is always good to improve the overall efficiency and end-user experience to stay ahead of the competition. Automated tasks and creating customized workflows add tremendous value. This is the primary goal of the ServiceNow platform.
The speed at which tests are executed and the “dearth of smartness” in testing are the two major problems developers and testers encounter.
The year 2021 can be encapsulated as one major transition. In 2022, the current breakthroughs in the elusive fight to eliminate the COVID-19 pandemic are top of mind for enterprises globally. At the same time, we are witnessing recent strides in technological advancements as the world gets digitized. As a result, the year 2022 will see the resumption of massive changes in technology and digital transformation, driving firms to adapt and transform themselves perpetually.
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!