如何将 drive.file 作用域用于独立的 google 应用程序脚本

How do I use the drive.file scope for a standalone google apps script

我有一个使用表格 API 的独立脚本。只有两个电话:

SpreadsheetApp.openById(spreadsheetID).getSheetByName("Answers")
SpreadsheetApp.openById(otherspreadsheetID).getSheetByName("Questions").getDataRange().getValues()

因此它从一个文件读取并写入另一个文件。该脚本设置为 运行 作为我的网络应用程序,因此在初始 运行 时,默认情况下,这会触发 view/edit/delete 所有工作表的广泛范围。我想限制它。我看到这是我可以手动设置的范围:https://www.googleapis.com/auth/drive.file (docs).

但我不知道如何将我的两个电子表格设置为应用程序“打开或创建”的文件,以便范围对这些文件有效。我尝试创建一个创建两个新工作表的函数(我认为这算作“您使用此应用程序创建的驱动器文件”),但即使是 Spreadsheetapp.create() 函数也会抛出“没有权限”错误。

我可能误解了这个范围的工作原理?

问题和解决方法:

当使用SpreadsheetApp.openById()时,使用https://www.googleapis.com/auth/spreadsheets的范围。好像这是目前的规格。

那么,作为解决方法,使用表格 API 怎么样?使用Sheets API时,可以使用https://www.googleapis.com/auth/drive.file.

的范围

作为重点,https://www.googleapis.com/auth/drive.file范围的官方文档如下

Per-file access to files created or opened by the app. File authorization is granted on a per-user basis and is revoked when the user deauthorizes the app.

所以,当你想使用https://www.googleapis.com/auth/drive.file的范围从Spreadsheet中检索数据时,首先,Spreadsheet需要由范围创建.在这个回答中,我想介绍以下流程。

  1. https://www.googleapis.com/auth/drive.file 的范围设置为 Google Apps 脚本项目。
  2. 创建一个新的跨页sheet。
  3. 从 Spread 中检索值sheet。

用法:

1。设置范围。

请创建一个新的 Google Apps 脚本。根据您的问题,我了解到您使用的是 standalone 类型。为此,请将 https://www.googleapis.com/auth/drive.file 的范围设置为清单文件。 Ref 请将 "oauthScopes": ["https://www.googleapis.com/auth/drive.file"] 添加到 appsscript.json 的文件中。这样,就可以使用特定的scope了。

2。创建一个新的 Spreadsheet.

在您使用此脚本之前,please enable Sheets API at Advanced Google services。当您运行以下脚本时,会创建一个新的 Spreadsheet,您可以在日志中看到 spreadsheet ID。请复制身份证。此 ID 将在下一个脚本中使用。这样,在 https://www.googleapis.com/auth/drive.file.

的范围内创建了一个新的 Spreadsheet
function createNewSpreadsheet() {
  const id = Sheets.Spreadsheets.create({properties: {title: "sample"}}).spreadsheetId;
  console.log(id)
}
  • 当您尝试从不是由此 Google Apps 脚本项目创建的现有 Spreadsheet 中检索值时,会发生 Requested entity was not found. 错误。因此,在本节中,这个 Google Apps 脚本项目创建了一个新的 Spreadsheet。

3。从 Spreadsheet.

获取值

在使用此脚本之前,请打开创建的 Spreadsheet 并检查 sheet 名称。并且,作为样本,请将样本值放入单元格中。当您 运行 以下脚本时,将从 Spreadsheet 检索值,您可以在日志中看到它们。

function getValues() {
  const spreadsheetId = "###"; // Please set the spreadsheet ID.
  const obj = Sheets.Spreadsheets.Values.get(spreadsheetId, "Sheet1");
  const values = obj.values;
  console.log(values)
}

参考文献: