AppsScriptPulse

How to get Google Lighthouse reports using PageSpeedInsights API and Google Apps Script

Lighhouse

Image: CC-BY Google

Lighthouse is an open-source, automated tool for improving the quality of web pages. You can run it against any web page, public or requiring authentication. It has audits for performance, accessibility, progressive web apps, SEO and more.

On StackOverflow there is a nice question/answer from Mert Dökümcü on How to send Google Lighthouse reports to Slack using PageSpeedInsights API and Google Apps Script. You can read the full solution there and below is an excerpt from Mert’s post (copied here CC-BY-SA Mert Dökümcü) of the bit that really interested me, getting results from PageSpeedInsights.

First and foremost, get…

Once you have these, go to https://script.google.com/home and create a new script. The following code should do the trick:

var mobileData = fetchDataFromPSI('mobile');
var desktopData = fetchDataFromPSI('desktop');

function pageSpeedApiEndpointUrl(strategy) {
  const apiBaseUrl = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed';
  const websiteHomepageUrl = ''; // Your website
  const apikey = ''; // Your API key
  
  const apiEndpointUrl = apiBaseUrl + '?url=' + websiteHomepageUrl + '&key=' + apikey + '&strategy=' + strategy;
  return apiEndpointUrl;
}
function fetchDataFromPSI(strategy) {
  const pageSpeedEndpointUrl = pageSpeedApiEndpointUrl(strategy);
  const response = UrlFetchApp.fetch(pageSpeedEndpointUrl);
  const json = response.getContentText();
  const parsedJson = JSON.parse(json);
  
  const lighthouse = parsedJson['lighthouseResult']
  const originLoadingExperience = parsedJson['originLoadingExperience']

  const result = {
    'overall_performance': originLoadingExperience['overall_category'],
    'score': lighthouse['categories']['performance']['score']*100,
    'firstContentfulPaint': lighthouse['audits']['first-contentful-paint']['displayValue'],
    'speedIndex': lighthouse['audits']['speed-index']['displayValue'],
    'timeToInteractive': lighthouse['audits']['interactive']['displayValue'],
    'firstMeaningfulPaint': lighthouse['audits']['first-meaningful-paint']['displayValue'],
  }
  return result; 
}

2 comments for “How to get Google Lighthouse reports using PageSpeedInsights API and Google Apps Script

  1. 20 November, 2021 at 12:0526

    Hi,

    When you do exactly as instructions, you get this error:

    TypeError: Cannot read property ‘overall_category’ of undefined
    fetchDataFromPSI @ Código.gs:24
    (anónimo) @ Código.gs:3

    The function pageSpeedApiEndpointUrl(strategy) needs this “strategy”, what to put here?

    Thanks!

    • 21 November, 2021 at 09:4626

      Hi Albert,Looking at the code the strategy is a string to fetch either the mobile or desktop result.

Leave a Reply

Your email address will not be published. Required fields are marked *