我创建了一个Google表格,其中包含沙滩排球杯的大量信息,并且我想调用在此表格中选中复选框时创建的API。
function onEdit(e){
const ui = SpreadsheetApp.getUi();
const spreadsheets = SpreadsheetApp.getActive();
const configSheet = spreadsheets.getSheetByName("Config")
var tourneyId = String(configSheet.getRange(2,4).getValue())
var tourneyTitle = String(configSheet.getRange(2,5).getValue())
var sheet = spreadsheets.getActiveSheet()
if (sheet.getName() == "LiveScore"){
var actRng = sheet.getActiveRange();
var editColumn = actRng.getColumn();
var rowIndex = actRng.getRowIndex();
actRng = actRng.getCell(1, 1);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
if(editColumn == 7 && rowIndex != 1){
onStartBroadcastClicked(actRng, ui, sheet, rowIndex, editColumn, tourneyTitle);
}
}
}
我认为这部分从来没有任何问题。但是当我进入onStartBroadcastClicked函数时:
function onStartBroadcastClicked(actRng, ui, sheet, rowIndex, editColumn, tourneyTitle){
var homeTeam = String(sheet.getRange(rowIndex, 14).getValue());
... // more setting variables
var endTime = new Date(startTime.getTime() + MILLIS_PER_MATCH);
if(actRng.isChecked()){
var response = ui.alert("You are about to start a new broadcast. Are you sure?" +
"\n Title: " + title, ui.ButtonSet.YES_NO);
if (response == ui.Button.YES) {
var httpRequest = "https://someUrl";
var options =
{
'method':'POST',
'contentType': 'application/json',
'payload' : JSON.stringify({
"title" : title,
... // setting all variables
"description" : description
}),
'muteHttpExceptions' : true,
'headers' : {
"Authorization": "Basic " + Utilities.base64Encode(USERNAME + ":" + PASSWORD)
}
};
ui.alert("Waiting.......")
var result = UrlFetchApp.fetch(httpRequest, options);
ui.alert(result.getContentText())
问题是它总是到达行ui.alert("Waiting.......")
,但是当从复选框触发时,它永远不会成功执行http POST请求。如果在编辑器中单击“播放”,它将成功,并且在警报框中得到响应。
是超时还是一些自动保存问题?有谁知道在哪里继续寻找?我已经在这里呆了一段时间了,如果有人能指出我正确的方向,我将非常高兴。
答案 0 :(得分:1)
问题的修改点是使用OnEdit事件的可安装触发器。在简单触发条件下使用授权方法时,会发生错误。这种情况使我们认为脚本似乎不起作用。
为避免此错误,请使用OnEdit事件触发器的可安装触发器。
重要的一点是,在安装触发器之前,请将onEdit()
的函数名称重命名为其他名称。并将重新命名的函数名称安装为OnEdit事件触发器。这样,可以防止onEdit()
的重复运行。如果将onEdit()
函数安装为可安装触发器,则在编辑单元格时,该函数将运行2次。 Ref。
通过以上设置,当单元格被编辑时,UrlFetchApp.fetch()
起作用。