How to capture performance metrics in Puppeteer?

To capture performance metrics in Puppeteer, you can use the Performance API. Here is a step-by-step guide on how to capture performance metrics in Puppeteer:

  1. Launch a new Puppeteer browser instance:
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); })();
  1. Enable the performance feature on the page:
await page.setBypassCSP(true); await page.evaluateOnNewDocument(() => { // Enable performance feature window.performance = window.performance || {}; });
  1. Start capturing performance metrics by using the Performance API:
await page.tracing.start({ path: 'profile.json' });
  1. Perform actions on the page that you want to capture performance metrics for.

  2. Stop capturing performance metrics and save the data to a file:

const trace = await page.tracing.stop(); await require('fs').writeFileSync('profile.json', JSON.stringify(trace));
  1. Analyze the performance metrics data saved in the profile.json file to get insights into the page load times, network requests, scripts execution, etc.

By following these steps, you can capture performance metrics in Puppeteer and analyze them to optimize the performance of your web application.