javascript lighthouse

Generating screenshots with Lighthouse

Lighthouse captures the rendering timeline of a page in 10 images. Do you need to store them? If yes, keep reading in order to learn how to store these images.

Lighthouse screenshots

The filmstrip above reveals how a page is rendered in a browser and gives us an opportunity to understand what is slow. For example, blank screenshots in the beginning is a sign that the First Contentful Paint is too slow.

In this post you will learn where these images are stored and how to store them in a file system. Here is the script (from my lighthouse-examples GitHub repository):

 1const { writeFileSync } = require('fs');
 2const lighthouse = require('lighthouse');
 3const chromeLauncher = require('chrome-launcher');
 5(async () => {
 6  const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
 7  const options = {port: chrome.port};
 8  const { lhr: { audits } } = await lighthouse('', options);
10  audits['screenshot-thumbnails'].details.items
11    .forEach(({ timing, data }) => {
12      debugger;
13      const screenshot = data.split(';base64,').pop();
14      const screenshotFile = `screenshot-${timing}ms.jpg`;
15      writeFileSync(screenshotFile, screenshot, { encoding: 'base64' });
16    });
18  const finalScreenshotFile = `screenshot-final.jpg`;
19  const finalScreenshot = audits['final-screenshot']';base64,').pop();
20  writeFileSync(finalScreenshotFile, finalScreenshot, { encoding: 'base64' });
22  await chrome.kill();

Let’s dig into the magic. Starting in line 10, we loop in the screenshot-thumbnails audit the images captured by Lighthouse. Notice that images are encoded in the Base64 format, and along with their content, Lighthouse also stores when they happen.

The script will create 11 image files as shown below.

Screenshots created by Lighthouse

Desktop dimensions

By default, the device emulated in Lighthouse is a Moto G4, with a 5.5 inches screen (1920 x 1080). We can tweak that and emulate a Desktop by setting the emulatedFormFactor to desktop. The options variable will look like this:

const options = {port: chrome.port, emulatedFormFactor: 'desktop'};

Why do we need this?

This script is useful in order to closely follow what is being rendered on a page or web app. In my particular case, I am storing only the final screenshot for future reference (ex. is this the right page?).

Can you think of different uses? Let me know in the comments!

Avatar photo If you like my content, follow me on Twitter and GitHub TwitterTweet




comments powered by Disqus