Skip to content

Instantly share code, notes, and snippets.

@arijitMondal
Last active April 22, 2022 15:03
Show Gist options
  • Save arijitMondal/a49ab3f72a382459c465f170952af0fa to your computer and use it in GitHub Desktop.
Save arijitMondal/a49ab3f72a382459c465f170952af0fa to your computer and use it in GitHub Desktop.
Google Apps Script code to fetch pagespeed data and save to google sheet
var pageSpeedApiKey = 'PAGESPEED_API_KEY'; // use your api key here
var urlToMonitor = 'YOUR_WEBSITE'; //replace with website you want to monitor
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName('results');
function createHeaders() {
//Freezes the first row
sheet.setFrozenRows(1);
// Set the values we want for headers
var values = [["Timestamp", "Device","Performance Score","LAB FCP", "LAB LCP", "LAB CLS", "LAB Interactive", "LAB Total Blocking Time", "LAB Speed Index"]];
// Set the range of cells
var range = sheet.getRange(1, 1, 1, 9);
//Call the setValues method on range and pass in our values
range.setValues(values);
}
function monitor() {
var desktopInfo = getPageSpeedInfo('desktop');
var mobileInfo = getPageSpeedInfo('mobile');
instertDataToSheet(desktopInfo, 'desktop');
instertDataToSheet(mobileInfo, 'mobile');
}
function getPageSpeedInfo(strategy) {
var pageSpeedUrl = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=' + urlToMonitor + '&key=' + pageSpeedApiKey + '&strategy=' + strategy;
var response = UrlFetchApp.fetch(pageSpeedUrl);
var json = response.getContentText();
return JSON.parse(json);
}
function instertDataToSheet(deviceInfo, deviceType){
sheet.appendRow([
// GMT+8:00 is for singapore
Utilities.formatDate(new Date(), "GMT+8:00", "yyyy-MM-dd'T'HH:mm:ss"),
deviceType,
deviceInfo.lighthouseResult.categories.performance.score * 100,
deviceInfo.lighthouseResult.audits['first-contentful-paint'].numericValue,
deviceInfo.lighthouseResult.audits['largest-contentful-paint'].numericValue,
deviceInfo.lighthouseResult.audits['cumulative-layout-shift'].numericValue,
deviceInfo.lighthouseResult.audits['interactive'].numericValue,
deviceInfo.lighthouseResult.audits['total-blocking-time'].numericValue,
deviceInfo.lighthouseResult.audits['speed-index'].numericValue,
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment