7

I would like to control a headless chrome instance using puppeteer, taking snapshots and clicking on various page elements, while capturing a har file. Is this possible? I have looked at the API but haven't found anything useful.

Atlas1j
  • 2,152
  • 2
  • 25
  • 33
  • 2
    You can use `page.tracing` https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-tracing methods. The data you collect contain all the information what HAR file will have and much more. – Everettss Nov 26 '17 at 15:26

2 Answers2

6

There is no HAR generator helper in Puppeteer. But you can use chrome-har to generate HAR file.

const fs = require('fs');
const { promisify } = require('util');

const puppeteer = require('puppeteer');
const { harFromMessages } = require('chrome-har');

// list of events for converting to HAR
const events = [];

// event types to observe
const observe = [
  'Page.loadEventFired',
  'Page.domContentEventFired',
  'Page.frameStartedLoading',
  'Page.frameAttached',
  'Network.requestWillBeSent',
  'Network.requestServedFromCache',
  'Network.dataReceived',
  'Network.responseReceived',
  'Network.resourceChangedPriority',
  'Network.loadingFinished',
  'Network.loadingFailed',
];

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

  // register events listeners
  const client = await page.target().createCDPSession();
  await client.send('Page.enable');
  await client.send('Network.enable');
  observe.forEach(method => {
    client.on(method, params => {
      events.push({ method, params });
    });
  });

  // perform tests
  await page.goto('https://en.wikipedia.org');
  page.click('#n-help > a');
  await page.waitForNavigation({ waitUntil: 'networkidle2' });
  await browser.close();

  // convert events to HAR file
  const har = harFromMessages(events);
  await promisify(fs.writeFile)('en.wikipedia.org.har', JSON.stringify(har));
})();

Here you can find an article about this solution.

Everettss
  • 13,024
  • 7
  • 63
  • 89
  • FYI, if you needs to also add the `response body` to the har, follow this revised version of the code: https://github.com/sitespeedio/chrome-har/pull/41#issuecomment-456913596 – weefwefwqg3 Mar 01 '19 at 01:39
2

Solution proposed by @Everettss is the only option (so far), but is not as good as HAR saved in browser. Look at this, in both cases I generated HAR for google.com page. At top you have HAR generated by puppeteer-har (which is using chrome-har). Too little requests here, no metrics for main document, strangely different timing.

enter image description here

Puppeteer is not a perfect option for HAR files. Therefore I am suggesting to use https://github.com/cyrus-and/chrome-har-capturer

user1660210
  • 837
  • 10
  • 10