javascript - Google 表格脚本问题 - 现在调用 Googleapis.com 会引发错误?
问题描述
我一直在基于 Rick Viscomi @ Google 共享的脚本的 Google Sheet 中运行“每天检查 pagespeed”脚本,但它最近坏了,我不知道如何修复它。
// 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;
}
最初我得到了这个错误
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")
所以我添加了这个
var params = {muteHttpExceptions:true};
var response = UrlFetchApp.fetch(pageSpeedUrl, params);
然后我得到这个错误
SyntaxError: Unexpected token N in JSON at position 0 (line 51, file "Code"
所以我改变了这个
return JSON.parse(JSON.stringify(json));
现在我得到这个错误
TypeError: Cannot read property 'metrics' of undefined (line 66, file "Code")
而且我觉得我已经超出了我的深度(而且仍然不知道为什么这个每天运行近 2 年的脚本在 5 月 19 日/20 日一夜之间停止工作)。
解决方案
推荐阅读
- ios - CountdownLabel 检查是否完成
- c# - 如何使用 AmazonS3EncryptionClientV2 客户端加密从 AWS S3 存储桶下载对象?
- scala - 在案例类上定义+操作
- python-3.x - 需要帮助来理解错误。我已经尝试过类似的帖子
- angular - 功能模块中的角度对话框引发错误“mat-dialog-content”不是已知元素
- java - Spring-MVC CRUD项目静态方法错误
- javascript - Mocha - 复选标记 √ 在 Git Bash 上打印为 ΓêÜ
- r - 跟踪多个数据帧中列值的变化
- android - Espresso:通过指定父视图来避免 AmbiguousViewMatcherException
- javascript - 无法访问类范围内的变量