尝试发送请求时出错

时间:2018-03-06 10:47:29

标签: javascript api google-apps-script google-sheets

我想测试是否可以使用Google电子表格中的UrlFetchApp.fetch发送请求。这是我的代码:

function createSpreadsheetOpenTrigger() {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('myOnEdit')
      .forSpreadsheet(ss)
      .onEdit()
      .create();
}

function myOnEdit(){
   var response = UrlFetchApp.fetch('http://www.google.com/');
    Logger.log(response.getContentText());
}

当我测试功能createSpreadsheetOpenTrigger时,它会显示一个提示框authorization required,当我点击审核权限按钮并登录时会显示This app isn't verified。我也不确定如何使用可安装的触发器,以便我的自定义onEdit工作。

我很感激任何有用的例子,因为我已经花了很长时间才开始工作。感谢。

1 个答案:

答案 0 :(得分:0)

有两种类型的脚本:

绑定脚本可以调用一些独立脚本不能的方法:

  • getActiveSpreadsheet(),getActiveDocument()和getActiveForm()允许绑定脚本引用其父文件,而不引用文件的ID。
  • getUi允许绑定脚本访问其父文件的用户界面,以添加自定义菜单,对话框和侧边栏。
  • 在Google表格中,getActiveSheet(),getActiveRange()和getActiveCell()让脚本确定用户的当前工作表,所选的单元格范围或选定的单个单元格。 setActiveSheet(sheet)和setActiveRange(range)让脚本更改这些选择。

您还可以手动在绑定脚本中创建可安装的触发器: The official documentation

要通过脚本编辑器中的对话框手动创建可安装触发器,请执行以下步骤:

  • 从脚本编辑器中,选择编辑>当前项目的触发器。
  • 点击以下链接:未设置触发器。点击此处立即添加一个。
  • 在“运行”下,选择要触发的功能名称。
  • 在“活动”下,选择时间驱动或脚本绑定的Google App(例如,从电子表格中)。
  • 选择并配置您要创建的触发器类型(例如,每小时运行的小时计时器或打开的触发器)。
  • (可选)单击通知以配置触发功能失败时如何以及何时通过电子邮件联系。
  • 点击保存。

以编程方式制作可安装的触发器:

https://developers.google.com/apps-script/reference/script/trigger-builder#forSpreadsheet(String)

ScriptApp.newTrigger('myFunction')
.forSpreadsheet('1234567890abcdefghijklmnopqrstuvwxyz')
.onEdit()
.create();

摘要:要从独立脚本创建此触发器,只需通过调用SpreadsheetApp.getActive()替换SpreadsheetApp.openById(id)即可。 ID是电子表格的关键:例如,网址https://docs.google.com/spreadsheets/d/abc1234567/edit#gid=0中的电子表格ID为“abc1234567”。

代码:

function createSpreadsheetOpenTrigger() {

  ScriptApp.newTrigger('myOnEdit')
      .forSpreadsheet('ID')
      .onEdit()
      .create();
}

function myOnEdit(){
   var response = UrlFetchApp.fetch('http://www.google.com/');
    Logger.log(response.getContentText());
}