I have been running a 'check pagespeed daily' script inside a Google Sheet that is based on a script shared by Rick Viscomi @ Google, but it has recently broke and I'm not sure how to fix it.
// Created by Rick Viscomi (@rick_viscomi)
// Adapted from https://ithoughthecamewithyou.com/post/automate-google-pagespeed-insights-with-apps-script by Robert Ellison
var scriptProperties = PropertiesService.getScriptProperties();
var pageSpeedApiKey = scriptProperties.getProperty('API_KEY');
var pageSpeedMonitorUrls = [
ARRAY
OF
URLS
AND
ORIGINS
];
function monitor() {
for (var i = 0; i < pageSpeedMonitorUrls.length; i++) {
var url = pageSpeedMonitorUrls[i];
var desktop = callPageSpeed(url, 'desktop');
var mobile = callPageSpeed(url, 'mobile');
addRow(url, desktop, mobile);
}
}
function callPageSpeed(url, strategy) {
var pageSpeedUrl = 'https://www.googleapis.com/pagespeedonline/v4/runPagespeed?url=' + url + '&fields=loadingExperience&key=' + pageSpeedApiKey + '&strategy=' + strategy;
var response = UrlFetchApp.fetch(pageSpeedUrl);
var json = response.getContentText();
return JSON.parse(JSON.stringify(json));
}
function addRow(url, desktop, mobile) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName('Sheet1');
sheet.appendRow([
Utilities.formatDate(new Date(), 'GMT', 'yyyy-MM-dd'),
url,
getFastFCP(desktop),
getFastFCP(mobile)
]);
}
function getFastFCP(data) {
return data.loadingExperience.metrics.FIRST_CONTENTFUL_PAINT_MS.distributions[0].proportion;
}
Originally I got this error
Exception: Request failed for https://www.googleapis.com returned code 404. Truncated server response: Not Found (use muteHttpExceptions option to examine full response). (line 48, file "Code")
So I added this
var params = {muteHttpExceptions:true};
var response = UrlFetchApp.fetch(pageSpeedUrl, params);
Then I get this error
SyntaxError: Unexpected token N in JSON at position 0 (line 51, file "Code"
So I changed this around
return JSON.parse(JSON.stringify(json));
And now I get this error
TypeError: Cannot read property 'metrics' of undefined (line 66, file "Code")
and I feel like I'm out of my depth (and still none the wiser about why the script, which ran daily for nearly 2 years, has stopped working overnight on the 19th/20th May).