What is the Puppeteer equivalent of window.performance?
Benjamin C
benjamin c profile pic

The Puppeteer equivalent ofwindow.performance ispage.evaluate() orpage.evaluateHandle(). Here's a detailed explanation: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

   (async () => {
     const browser = await puppeteer.launch();
     const page = await browser.newPage();

     // Perform actions with the page here

     // Close the browser
     await browser.close();
   })();
   

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Accessing performance-related information usingpage.evaluate() orpage.evaluateHandle(): To access performance-related information in Puppeteer, you can use eitherpage.evaluate() orpage.evaluateHandle(). - Usingpage.evaluate():

1
2
3
4
5

     const performanceMetrics = await page.evaluate(() => JSON.stringify(window.performance));

     console.log('Performance Metrics:', performanceMetrics);
     

This code usespage.evaluate() to execute JavaScript code within the page's context. It retrieves thewindow.performance object, serializes it as a JSON string, and returns it to the Node.js environment. The performance-related information can then be logged or further processed as needed. - Usingpage.evaluateHandle():

1
2
3
4
5
6

     const performanceHandle = await page.evaluateHandle(() => window.performance);
     const performanceMetrics = await performanceHandle.jsonValue();

     console.log('Performance Metrics:', performanceMetrics);
     

This code usespage.evaluateHandle() to evaluate the JavaScript code within the page's context and return a handle to thewindow.performance object. ThejsonValue() method is called on the handle to extract the performance-related information as a JSON object. Finally, the performance metrics are logged or processed accordingly. By utilizing eitherpage.evaluate() orpage.evaluateHandle(), you can access the performance-related information in Puppeteer. This includes various metrics such as navigation timing, resource timing, user timing, and more. You can analyze and process this information to measure the page's performance, identify bottlenecks, and optimize your web applications or automated tasks.