Best JavaScript code snippet using puppeteer
withDevice.js
Source:withDevice.js
...54};55(async () => {56 const browser = await puppeteer.launch();57 const page = await browser.newPage();58 const client = await page.target().createCDPSession();59 await client.send('Network.enable');60 await client.send('Network.emulateNetworkConditions', NETWORK_PRESETS['Regular2G']);61 await page.goto(WEB);62 const performanceTiming = JSON.parse(63 await page.evaluate(() => JSON.stringify(window.performance.timing))64 );65 const loadWithDOM = performanceTiming.domComplete - performanceTiming.navigationStart;66 const all = performanceTiming.loadEventEnd - performanceTiming.navigationStart;67 console.log('User can see content for Regular2G ~', loadWithDOM / 1000, 'sec');68 console.log('All Load for Regular2G --', all / 1000, 'sec');69 await browser.close();70})();71(async () => {72 const browser = await puppeteer.launch();73 const page = await browser.newPage();74 const client = await page.target().createCDPSession();75 await client.send('Network.enable');76 await client.send('Network.emulateNetworkConditions', NETWORK_PRESETS['WiFi']);77 await page.goto(WEB);78 const performanceTimingFast = JSON.parse(79 await page.evaluate(() => JSON.stringify(window.performance.timing))80 );81 const loadWithDOMFast = performanceTimingFast.domComplete - performanceTimingFast.navigationStart;82 const allFast = performanceTimingFast.loadEventEnd - performanceTimingFast.navigationStart;83 console.log('User can see content with WiFi ~', loadWithDOMFast / 1000, 'sec');84 console.log('All Load with WiFi --', allFast / 1000, 'sec');85 await browser.close();86})();87(async () => {88 const browser = await puppeteer.launch();89 const page = await browser.newPage();90 await page.emulate(iPhonex);91 const client = await page.target().createCDPSession();92 await client.send('Network.enable');93 await client.send('Network.emulateNetworkConditions', NETWORK_PRESETS['WiFi']);94 await page.goto(WEB);95 const performanceTimingFast = JSON.parse(96 await page.evaluate(() => JSON.stringify(window.performance.timing))97 );98 const loadWithDOMFast = performanceTimingFast.domComplete - performanceTimingFast.navigationStart;99 const allFast = performanceTimingFast.loadEventEnd - performanceTimingFast.navigationStart;100 console.log('[iPhone X] User can see content with WiFi ~', loadWithDOMFast / 1000, 'sec');101 console.log('[iPhone X] All Load with WiFi --', allFast / 1000, 'sec');102 await browser.close();...
CDPSession.spec.js
Source:CDPSession.spec.js
...24 setupTestBrowserHooks();25 setupTestPageAndContextHooks();26 it('should work', async () => {27 const { page } = getTestState();28 const client = await page.target().createCDPSession();29 await Promise.all([30 client.send('Runtime.enable'),31 client.send('Runtime.evaluate', { expression: 'window.foo = "bar"' }),32 ]);33 const foo = await page.evaluate(() => window.foo);34 expect(foo).toBe('bar');35 });36 it('should send events', async () => {37 const { page, server } = getTestState();38 const client = await page.target().createCDPSession();39 await client.send('Network.enable');40 const events = [];41 client.on('Network.requestWillBeSent', (event) => events.push(event));42 await page.goto(server.EMPTY_PAGE);43 expect(events.length).toBe(1);44 });45 it('should enable and disable domains independently', async () => {46 const { page } = getTestState();47 const client = await page.target().createCDPSession();48 await client.send('Runtime.enable');49 await client.send('Debugger.enable');50 // JS coverage enables and then disables Debugger domain.51 await page.coverage.startJSCoverage();52 await page.coverage.stopJSCoverage();53 // generate a script in page and wait for the event.54 const [event] = await Promise.all([55 waitEvent(client, 'Debugger.scriptParsed'),56 page.evaluate('//# sourceURL=foo.js'),57 ]);58 // expect events to be dispatched.59 expect(event.url).toBe('foo.js');60 });61 it('should be able to detach session', async () => {62 const { page } = getTestState();63 const client = await page.target().createCDPSession();64 await client.send('Runtime.enable');65 const evalResponse = await client.send('Runtime.evaluate', {66 expression: '1 + 2',67 returnByValue: true,68 });69 expect(evalResponse.result.value).toBe(3);70 await client.detach();71 let error = null;72 try {73 await client.send('Runtime.evaluate', {74 expression: '3 + 1',75 returnByValue: true,76 });77 } catch (error_) {78 error = error_;79 }80 expect(error.message).toContain('Session closed.');81 });82 it('should throw nice errors', async () => {83 const { page } = getTestState();84 const client = await page.target().createCDPSession();85 const error = await theSourceOfTheProblems().catch((error) => error);86 expect(error.stack).toContain('theSourceOfTheProblems');87 expect(error.message).toContain('ThisCommand.DoesNotExist');88 async function theSourceOfTheProblems() {89 await client.send('ThisCommand.DoesNotExist');90 }91 });...
CDPSession.js
Source:CDPSession.js
...17 await helper.end()18})19test.serial('Target.createCDPSession should work', async t => {20 const { page, server } = t.context21 const client = await page.target().createCDPSession()22 await Promise.all([23 client.send('Runtime.enable'),24 client.send('Runtime.evaluate', { expression: 'window.foo = "bar"' })25 ])26 const foo = await page.evaluate(() => window.foo)27 t.is(foo, 'bar')28})29test.serial('Target.createCDPSession should send events', async t => {30 const { page, server } = t.context31 const client = await page.target().createCDPSession()32 await client.send('Network.enable')33 const events = []34 client.on('Network.requestWillBeSent', event => events.push(event))35 await page.goto(server.EMPTY_PAGE)36 t.is(events.length, 1)37})38test.serial(39 'Target.createCDPSession should enable and disable domains independently',40 async t => {41 const { page, server } = t.context42 const client = await page.target().createCDPSession()43 await client.send('Runtime.enable')44 await client.send('Debugger.enable')45 // JS coverage enables and then disables Debugger domain.46 await page.coverage.startJSCoverage()47 await page.coverage.stopJSCoverage()48 // generate a script in page and wait for the event.49 const script = '() => it'50 const [event] = await Promise.all([51 waitEvent(client, 'Debugger.scriptParsed'),52 page.evaluate(script)53 ])54 // expect events to be dispatched.55 t.truthy(event)56 }57)58test.serial(59 'Target.createCDPSession should be able to detach session',60 async t => {61 const { page, server } = t.context62 const client = await page.target().createCDPSession()63 await client.send('Runtime.enable')64 const evalResponse = await client.send('Runtime.evaluate', {65 expression: '1 + 2',66 returnByValue: true67 })68 t.is(evalResponse.result.value, 3)69 await client.detach()70 let error = null71 try {72 await client.send('Runtime.evaluate', {73 expression: '3 + 1',74 returnByValue: true75 })76 } catch (e) {77 error = e78 }79 t.true(error.message.includes('Session closed.'))80 }81)82test.serial('Target.createCDPSession should throw nice errors', async t => {83 const { page } = t.context84 const client = await page.target().createCDPSession()85 const error = await theSourceOfTheProblems().catch(error => error)86 t.true(error.stack.includes('theSourceOfTheProblems'))87 t.true(error.message.includes('ThisCommand.DoesNotExist'))88 async function theSourceOfTheProblems () {89 await client.send('ThisCommand.DoesNotExist')90 }...
index.js
Source:index.js
...23 let res = [];24 // ------- first browser run ---------25 let browser = await puppeteer.launch();26 let page = await browser.newPage();27 let client = await page.target().createCDPSession();28 await emulateConditions(client);29 // first enter test30 res = [31 ...res,32 ...convertResultsToArr(await testPage(page, client), 'firstEnter'),33 ];34 bar.tick();35 await page.close();36 page = await browser.newPage();37 client = await page.target().createCDPSession();38 await emulateConditions(client);39 // second enter test with ServiceWorker and cache40 res = [41 ...res,42 ...convertResultsToArr(await testPage(page, client), 'swAndCache'),43 ];44 bar.tick();45 await browser.close();46 // ------- second browser run ---------47 browser = await puppeteer.launch();48 page = await browser.newPage();49 client = await page.target().createCDPSession();50 // first enter only for hydration ServiceWorker and cache51 await testPage(page, client);52 bar.tick();53 await page.close();54 page = await browser.newPage();55 client = await page.target().createCDPSession();56 await emulateConditions(client);57 await client.send('ServiceWorker.enable');58 await client.send('ServiceWorker.unregister', {59 scopeURL: 'http://localhost:8080/',60 });61 // second enter test with cache62 res = [63 ...res,64 ...convertResultsToArr(await testPage(page, client), 'cache'),65 ];66 bar.tick();67 await browser.close();68 // ------- third browser run ---------69 browser = await puppeteer.launch();70 page = await browser.newPage();71 client = await page.target().createCDPSession();72 // first enter only for hydration ServiceWorker and cache73 await testPage(page, client);74 bar.tick();75 await page.close();76 page = await browser.newPage();77 client = await page.target().createCDPSession();78 await emulateConditions(client);79 await client.send('Network.clearBrowserCache');80 // second enter test with ServiceWorker81 res = [...res, ...convertResultsToArr(await testPage(page, client), 'sw')];82 bar.tick();83 await browser.close();84 const file = JSON.parse(await promisify(fs.readFile)(filePath));85 await promisify(fs.writeFile)(filePath, JSON.stringify([...file, ...res]));86 }87};...
connect_to_browser.js
Source:connect_to_browser.js
...11 12 browser.on('targetchanged', async (target) => {13 if (target.type() === 'page') {14 console.log('\n[targetchanged event]\n');15 let cdp = await target.createCDPSession();16 var page = await target.page();17 18 serve_history_page(cdp);19 runPageOperations(page, cdp);20 }21 })22 //Get tagets for tabs opened in the background23 // ex: tabs that are opened by middle click24 browser.on('targetcreated', async (target) => {25 if (target.type() === 'page') {26 console.log('\nnew tab opened\n');27 let cdp = await target.createCDPSession();28 var page = await target.page();29 30 serve_history_page(cdp);31 runPageOperations(page, cdp);32 }33 });34 //TODO make sure to on the run these functions ^ single35 //Make a test to see if the page target is already being handled 36 37 const pages = (await browser.pages());38 console.log('open pages:');39 console.log(pages.length);40 var cdp = await pages[0].target().createCDPSession();41 var targets = await cdp.send('Target.getTargets');42 console.log('targets:');43 console.log(targets['targetInfos'].length);44 var attached_targets = 0;45 targets['targetInfos'].forEach(async (target) => {46 if (target['attached'] == true)47 {48 attached_targets++;49 }50 })51 console.log('attached targets:');52 console.log(attached_targets);53 // Handle when the page gets closed suddenly54 process.on('unhandledRejection', (reason) => {...
clearData.js
Source:clearData.js
...6 await waitFor(7 async () => {8 let closeCdpSession = false;9 if (!cdpSession) {10 cdpSession = await this.target().createCDPSession();11 closeCdpSession = true;12 }13 await Promise.all([14 cdpSession.send('Network.clearBrowserCookies'),15 this.evaluate(() => localStorage.clear()).catch(err => {16 logger.warn('fail to clear localStorage', err);17 }),18 this.evaluate(() => sessionStorage.clear()).catch(err => {19 logger.warn('fail to clear sessionStorage', err);20 }),21 ]);22 if (closeCdpSession) await cdpSession.detach();23 },24 { timeout: 20000, message: 'unable to clear user data' },25 );26 } catch (err) {27 err.message = `failed to clear user data.\n${err.message}`;28 logger.error(err);29 throw err;30 }31}32async function clearCache(cdpSession = null) {33 try {34 if (!cdpSession) cdpSession = await this.target().createCDPSession();35 // Wipe entire disk cache36 await cdpSession.send('Network.clearBrowserCache');37 // Toggle 'Disable Cache' to evict the memory cache38 await cdpSession.send('Network.setCacheDisabled', { cacheDisabled: true });39 await cdpSession.send('Network.setCacheDisabled', { cacheDisabled: false });40 } catch (err) {41 err.message = `failed to clear user cache.\n${err.message}`;42 logger.error(err);43 throw err;44 }45}46async function clearAllData() {47 const cdpSession = await this.target().createCDPSession();48 await Promise.all([49 this.clearCache(cdpSession),50 this.clearUserData(cdpSession),51 cdpSession.send('Storage.clearDataForOrigin', {52 origin: new URL(url).origin,53 storageTypes: 'all',54 }),55 ]);56 await cdpSession.detach();57}58module.exports = {59 clearUserData,60 clearCache,61 clearAllData,...
test.js
Source:test.js
1const EventEmitter = require('events');2const test = require('tape');3const {stub} = require('sinon');4test('PuppeteerNetworkStats', async (t) => {5 t.plan(6);6 const PuppeteerNetworkStats = require('./index');7 const mockClient = new EventEmitter();8 mockClient.send = stub();9 mockClient.detach = stub();10 const createCDPSession = stub().returns(mockClient);11 const mockPage = {target: () => ({createCDPSession})};12 const networkStats = new PuppeteerNetworkStats({13 requestWillBeSent: ({request: {url}}) => ({url}),14 responseReceived: ({response: {status}}) => ({status})15 });16 await networkStats.attach(mockPage);17 t.ok(18 createCDPSession.calledOnce,19 'attach creates client'20 );21 t.ok(22 mockClient.send.calledWith('Network.enable'),23 'attach enables Network'24 );25 const id = 1;26 const url = 'https://www.example.com';27 mockClient.emit(28 'Network.requestWillBeSent',29 {requestId: id, request: {url}}30 );31 t.equal(32 networkStats.getRequests()[id].url, url,33 'configured parameters are captured from an event'34 );35 const status = 200;36 mockClient.emit(37 'Network.responseReceived',38 {requestId: id, response: {status}}39 );40 t.deepEqual(41 networkStats.getRequests()[id], {status, url},42 'event with same request id has its captured parameters merged'43 );44 await networkStats.detach(mockPage);45 t.ok(mockClient.detach.calledOnce, 'detach calls client.detach');46 networkStats.clearRequests();47 t.deepEqual(48 networkStats.getRequests(), {},49 'clearRequests clears captured requests'50 );...
util.js
Source:util.js
1async function minimize(page) {2 const session = await page.target().createCDPSession();3 const goods = await session.send("Browser.getWindowForTarget");4 const { windowId } = goods;5 await session.send("Browser.setWindowBounds", {6 windowId,7 bounds: { windowState: "minimized" },8 });9 10 return;11 }12 13async function maximize(page) {14 const session = await page.target().createCDPSession();15 const goods = await session.send("Browser.getWindowForTarget");16 const { windowId } = goods;17 await session.send("Browser.setWindowBounds", {18 windowId,19 bounds: { windowState: "normal" },20 });21 }22module.exports = {23 minimize,24 maximize...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const client = await page.target().createCDPSession();6 await client.send('Network.enable');7 await page.screenshot({path: 'example.png'});8 await browser.close();9})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const client = await page.target().createCDPSession();6 await client.send('Network.enable');7 await client.send('Network.setExtraHTTPHeaders', {headers: { 'X-My-Custom-Header': 'MyCustomHeaderValue' }});8 await browser.close();9})();10const puppeteer = require('puppeteer');11(async () => {12 const browser = await puppeteer.launch();13 const page = await browser.newPage();14 await page.setExtraHTTPHeaders({15 });16 await browser.close();17})();18const puppeteer = require('puppeteer');19(async () => {20 const browser = await puppeteer.launch();21 const page = await browser.newPage();22 await page.setExtraHTTPHeaders({23 });24 await browser.close();25})();26const puppeteer = require('puppeteer');27(async () => {28 const browser = await puppeteer.launch();29 const page = await browser.newPage();30 await page.setExtraHTTPHeaders({31 });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.setExtraHTTPHeaders({39 });40 await browser.close();41})();42const puppeteer = require('puppeteer');
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const client = await page.target().createCDPSession();6 await client.send('Network.enable');7 client.on('Network.requestWillBeSent', (params) => {8 console.log(params.request.url);9 });10 await browser.close();11})();12const puppeteer = require('puppeteer');13(async () => {14 const browser = await puppeteer.launch({headless: false});15 const page = await browser.newPage();16 await page.goto(url);17 await page.waitForSelector('input[name="q"]');18 await page.$eval('input[name="q"]', (el, value) => el.value = value, 'puppeteer');19 await page.click('input[name="btnK"]');20 await page.waitForNavigation();21 await browser.close();22})();23const cookies = await page.cookies();24console.log(cookies);25const cookies = await page._client.send('Network.getAllCookies');26console.log(cookies);27const puppeteer = require('puppeteer');28(async () => {
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const client = await page.target().createCDPSession();6 await client.send('Page.enable');7 await client.send('Page.captureScreenshot', { format: 'png', fromSurface: true })8 .then((image) => {9 console.log(image);10 });11 await browser.close(
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 const client = await page.target().createCDPSession();6 const response = await client.send('Network.enable');7 console.log(response);8 await browser.close();9})();10{ id: 1, result: {} }
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 client = await page.target().createCDPSession();7 await client.send('Page.enable');8 await client.send('Page.captureScreenshot', {format: 'jpeg', fromSurface: true})9 .then(result => {10 fs.writeFile('screenshot.jpeg', result.data, 'base64', function (err) {11 if (err) {12 console.log(err);13 }14 console.log('File created');15 });16 });17 await browser.close();18})();19const puppeteer = require('puppeteer');20const fs = require('fs');21(async () => {22 const browser = await puppeteer.launch();23 const page = await browser.newPage();24 await page.screenshot({path: 'screenshot.jpeg'});25 await browser.close();26})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const client = await page.target().createCDPSession();6 await client.send('Network.enable');7 await client.send('Network.setCacheDisabled', { cacheDisabled: true });8 await page.screenshot({path: 'google.png'});9 await browser.close();10})();11const puppeteer = require('puppeteer');12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 const client = await page.target().createCDPSession();16 await client.send('Network.enable');17 await client.send('Network.setCacheDisabled', { cacheDisabled: true });18 await page.screenshot({path: 'google.png'});19 await browser.close();20})();21const puppeteer = require('puppeteer');22(async () => {23 const browser = await puppeteer.launch();24 const page = await browser.newPage();25 const client = await page.target().createCDPSession();26 await client.send('Network.enable');27 await client.send('Network.setCacheDisabled', { cacheDisabled: true });28 await page.screenshot({path: 'google.png'});29 await browser.close();30})();31const puppeteer = require('puppeteer');32(async () => {33 const browser = await puppeteer.launch();34 const page = await browser.newPage();35 const client = await page.target().createCDPSession();36 await client.send('Network.enable');37 await client.send('Network.setCacheDisabled', { cacheDisabled: true });38 await page.screenshot({path: 'google.png'});39 await browser.close();40})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 const client = await page.target().createCDPSession();6 await client.send('Page.enable');7 await client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: '/home/username/Downloads'});8 await page.screenshot({path: 'google.png'});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 const client = await page.target().createCDPSession();16 await client.send('Page.enable');17 await client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: '/home/username/Downloads'});18 await page.screenshot({path: 'google.png'});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 const client = await page.target().createCDPSession();26 await client.send('Page.enable');27 await client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: '/home/username/Downloads'});28 await page.screenshot({path: 'google.png'});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();
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!!