首页 > 解决方案 > 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 日一夜之间停止工作)。

标签: javascriptjson

解决方案


推荐阅读