如何从Google工作表绑定脚本调用Web应用程序以修改工作表

时间:2019-09-05 15:29:46

标签: google-apps-script google-sheets web-applications http-status-code-401 google-apps-script-web-application

我正在尝试制作一个可由Google工作表的绑定脚本触发的网络应用,以在我的授权下修改工作表。我尝试使用可安装的触发器,但是我需要的功能比它们提供的功能还要多。

我从以下位置复制并粘贴代码 Google Apps Script: Temporarily run script as another user 并尝试使其正常运行,但不断出现相同的错误Exception: Request failed for https://script.google.com returned code 401. Truncated server response:,然后出现页面的HTML。我甚至连这个工作的基本版本都很难,上面的链接是我找到的最/唯一相关的指南。

以下是我尝试获得基本功能的尝试(它返回上述相同的错误)。如果我在浏览器中打开Web应用程序,它将成功向第一个单元格添加1,但是我无法弄清楚如何从工作表的绑定脚本正确调用Web应用程序。

通过电子表格的绑定脚本:

function myFunction() {
  UrlFetchApp.fetch('web app url');
}

通过网络应用程序:

function doGet() {
  var ss = SpreadsheetApp.openById('spreadsheet id');
  var sheet = ss.getSheetByName('Sheet1');
  var cell = sheet.getRange(1, 1);
  cell.setValue(cell.getValue() + 1);
}

我所需要的只是一个有效的例子。之后,我可以从那里拿走。

1 个答案:

答案 0 :(得分:1)

尝试一下:

这就像我一样运行,只有我可以访问它。因此,您可能希望对其进行修改。

function myFunction() {
  Logger.log(ScriptApp.getService().getUrl());
  var url=ScriptApp.getService().getUrl();
  var params = {
    method: "get",
    headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
  };
  UrlFetchApp.fetch(url,params);
}

function doGet() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet1');
  sh.getRange("A1").setValue(sh.getRange("A1").getValue() + 1);
  var html=Utilities.formatString('Process Complete: Current Value: %s',sh.getRange("A1").getValue());
  return HtmlService.createHtmlOutput(html);
}

这些是我添加的范围:

"oauthScopes": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/spreadsheets"]