-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathpsi-api-v5.gs
More file actions
55 lines (48 loc) · 1.8 KB
/
Copy pathpsi-api-v5.gs
File metadata and controls
55 lines (48 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
// Example of Google Apps Script code that connects a Sheet with the PSI v5 API.
// Make a copy of this sheet to get started: https://docs.google.com/spreadsheets/d/1mFWe_KbO8_MevyzrDyULbB3SQqXiciKlzWJfmyUBneU/edit?usp=sharing
var scriptProperties = PropertiesService.getScriptProperties();
var pageSpeedApiKey = scriptProperties.getProperty('PSI_API_KEY');
var pageSpeedMonitorUrls = [
'https://www.nytimes.com',
'https://www.washingtonpost.com'
];
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/v5/runPagespeed?url=' + url + '&fields=originLoadingExperience&key=' + pageSpeedApiKey + '&strategy=' + strategy;
var response = UrlFetchApp.fetch(pageSpeedUrl);
var json = response.getContentText();
return JSON.parse(json);
}
function addRow(url, desktop, mobile) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var date = Utilities.formatDate(new Date(), 'GMT', 'yyyy-MM-dd');
var sheet = spreadsheet.getSheetByName('Desktop');
sheet.appendRow([
date,
url,
getFastFCP(desktop),
getFastINP(desktop)
]);
sheet = spreadsheet.getSheetByName('Mobile');
sheet.appendRow([
date,
url,
getFastFCP(mobile),
getFastINP(mobile)
]);
}
function getFastFCP(data) {
return data.originLoadingExperience.metrics.FIRST_CONTENTFUL_PAINT_MS.distributions[0].proportion;
}
function getFastINP(data) {
return data.originLoadingExperience.metrics.INTERACTION_TO_NEXT_PAINT_MS.distributions[0].proportion;
}