-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagespeed_v2.gs
263 lines (249 loc) · 7.58 KB
/
pagespeed_v2.gs
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/* PageSpeed automation for multiple domains
- Create 3 sheets as
- Settings
- Put domain identifier for smart notifications starting from B5
- Put Google Api Key for domain
- Put Slack webhook URL for domian
- Log
- URL Pool
- Put URLs from A2 and below
*/
const SHEET = SpreadsheetApp.getActiveSpreadsheet();
const API_URL = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed";
const TODAY = new Date()
const onOpen = () => {
var ui = SpreadsheetApp.getUi();
ui.createMenu('PageSpeed Menu')
.addItem('🚀 - Start Testing', 'wrapper')
.addToUi();
}
const wrapper = async () => {
var activeSheet = SHEET.getSheetByName('Settings');
var resultRows = activeSheet.getLastRow();
for (var i = 5; i <= resultRows; i++) {
var target = activeSheet.getRange(`B${i}:D${i}`).getValues();
var data = {
"domain": target[0][0], // URL
"api_key": target[0][1], // Google API Key
"slack_hook": target[0][2] // slack hook
}
await testRunner(data)
}
}
const testRunner = async (data) => {
['mobile', 'desktop'].forEach(async (strategy) => {
await getURLsFromSheet(strategy, data);
});
}
const getURLsFromSheet = async (strategy, keyData) => {
var activeSheet = SHEET.getSheetByName('URL Pool');
var rows = activeSheet.getLastRow();
for (var i = 2; i <= rows; i++) {
var url = activeSheet.getRange(i, 2).getValue();
if (url.match(keyData.domain)) {
//console.log(keyData.domain, strategy, url)
await getLighthouseResults(url, strategy, keyData)
}
}
}
const getLighthouseResults = async (url, strategy, keyData) => {
const serviceUrl = `${API_URL}?url=${url}&key=${keyData.api_key}&strategy=${strategy}&category=ACCESSIBILITY&category=BEST_PRACTICES&category=PERFORMANCE&category=PWA&category=SEO`
var res = UrlFetchApp.fetch(serviceUrl);
Logger.log(res)
var data = JSON.parse(res.getContentText());
Logger.log(data)
var header = JSON.parse(res.getResponseCode());
if (header != 404 || 500) {
Logger.log(`Result retrieved for ${serviceUrl} with ${strategy} strategy.`);
lt = data.lighthouseResult;
const ltMetrics = {
'strategy': strategy,
'url': url,
'performance': lt.categories.performance.score * 100,
'accessibility': lt.categories.accessibility.score * 100,
'bestPractices': lt.categories["best-practices"].score * 100,
'seo': lt.categories.seo.score * 100,
'firstContentfulPaint': lt.audits['first-contentful-paint'].displayValue.slice(0, -2),
'speedIndex': lt.audits['speed-index'].displayValue.slice(0, -2),
'totalBlockingTime': lt.audits['total-blocking-time'].displayValue.slice(0, -3),
'firstMeaningfulPaint': lt.audits['first-meaningful-paint'].displayValue.slice(0, -2),
'cumulativeLayoutShift': lt.audits['cumulative-layout-shift'].displayValue,
'largestContentfulPaint': lt.audits['largest-contentful-paint'].displayValue.slice(0, -2),
'interactive': lt.audits['interactive'].displayValue.slice(0, -2),
'domain': keyData.domain.toUpperCase(),
'identifier': await pageIdentifierHelper(url),
'today': `${TODAY.getFullYear()}/${TODAY.getMonth() + 1}/${TODAY.getDate()}`
}
// Append all Metrics to the Log sheet.
SpreadsheetApp.getActive().getSheetByName('Log').appendRow(
[
ltMetrics.strategy,
ltMetrics.url,
ltMetrics.performance,
ltMetrics.accessibility,
ltMetrics.bestPractices,
ltMetrics.seo,
ltMetrics.firstContentfulPaint,
ltMetrics.speedIndex,
ltMetrics.totalBlockingTime,
ltMetrics.firstMeaningfulPaint,
ltMetrics.cumulativeLayoutShift,
ltMetrics.largestContentfulPaint,
ltMetrics.interactive,
ltMetrics.domain,
ltMetrics.identifier,
ltMetrics.today
],
);
Logger.log(`Slack notification sent for ${ltMetrics.url}`);
await slackNotifier(ltMetrics, keyData);
} else {
Logger.log('Something went wrong!');
}
}
const slackNotifier = async (metrics, keyData) => {
var payload = {
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": `:mega: ${metrics.domain} - ${metrics.identifier} - Performance results for ${metrics.strategy.toUpperCase()}`
}
},
{
"type": "context",
"elements": [
{
"text": `*${TODAY}*`,
"type": "mrkdwn"
}
]
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `*URL:* ${metrics.url}`
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `${await iconHelper(metrics.performance)} Performance: *${metrics.performance}*`
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `${await iconHelper(metrics.accessibility)} Accessibility: *${metrics.accessibility} *`
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `${await iconHelper(metrics.bestPractices)} Best Practices: *${metrics.bestPractices}*`
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `${await iconHelper(metrics.seo)} SEO: *${metrics.seo}*`
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Lighthouse Results*"
}
},
{
"type": "section",
"fields": [
{
"type": "plain_text",
"text": `First Contentful Paint: ${metrics.firstContentfulPaint} s`,
"emoji": true
},
{
"type": "plain_text",
"text": `First Meaningful Paint: ${metrics.firstMeaningfulPaint} s`,
"emoji": true
},
{
"type": "plain_text",
"text": `Time to Interactive: ${metrics.interactive} s`,
"emoji": true
},
{
"type": "plain_text",
"text": `Speed Index: ${metrics.speedIndex} s`,
"emoji": true
},
{
"type": "plain_text",
"text": `Total Blocking Time: ${metrics.totalBlockingTime} ms`,
"emoji": true
},
{
"type": "plain_text",
"text": `Largest Contentful Paint: ${metrics.largestContentfulPaint} s`,
"emoji": true
},
{
"type": "plain_text",
"text": `Cumulative Layout Shift: ${metrics.cumulativeLayoutShift}`,
"emoji": true
}
]
},
{
"type": "divider"
}
]
};
var options = {
"method": "post",
"headers": {
"Content-type": "application/json",
},
"payload": JSON.stringify(payload)
};
UrlFetchApp.fetch(keyData.slack_hook, options);
}
const iconHelper = async (value) => {
let icon;
if (value > 84) {
icon = ':large_green_circle:'
} else if (value > 64 && value < 85) {
icon = ':large_orange_circle:'
} else {
icon = ':red_circle:'
}
return icon;
}
const pageIdentifierHelper = async (url) => {
let state;
switch (true) {
case /products\//.test(url): // set up to your URL pattern
state = 'PDP'
break;
case /products/.test(url): // set up to your URL pattern
state = 'PLP'
break;
default:
state = 'LP'
}
return state;
}