【问题标题】:Can I use DocumentApp.openById() with read only permission?我可以使用具有只读权限的 DocumentApp.openById() 吗?
【发布时间】:2021-05-08 03:39:18
【问题描述】:

我正在创建一个用于 Google 电子表格的 Google Apps 脚本插件,但它需要能够访问单独的 Google 文档的内容,我正在使用 DocumentApp.openById() 进行此操作。我已经给脚本这些scopes

"oauthScopes": [
    "https://www.googleapis.com/auth/documents.readonly",
    "https://www.googleapis.com/auth/script.container.ui",
    "https://www.googleapis.com/auth/spreadsheets.currentonly"
  ]

但显然,这还不够。该脚本告诉我它需要https://www.googleapis.com/auth/documents 权限才能正常工作。但是,当它只需要能够查看一个文件的内容时,授予该插件编辑所有 Google Docs 文件的权限似乎有些过分。我错过了什么吗?有没有办法让它只读访问单独的 Google Docs 文件?

这是我用来测试的函数,大部分文档 ID 都被删掉了:

function getDoc() {
  var id = '1NLH----------------------------------------'
  var templateFile = DocumentApp.openById(id)
  var templateText = templateFile.getBody().getText()
  Logger.log(templateText)
}

谢谢!

【问题讨论】:

  • 虽然我不确定我的提议是否与你的目标一致,但我提出了一个答案。你能确认一下吗?如果这不是您期望的方向,我深表歉意。
  • "我可以在只读权限下使用 DocumentApp.openById() 吗?"是的。

标签: google-apps-script google-docs


【解决方案1】:

我相信你的目标如下。

  • 您想使用以下脚本从 Google 文档中检索文本数据。

      function getDoc() {
        var id = '1NLH----------------------------------------'
        var templateFile = DocumentApp.openById(id)
        var templateText = templateFile.getBody().getText()
        Logger.log(templateText)
      }
    
  • 您希望使用 https://www.googleapis.com/auth/documents.readonly 的范围和 Google Apps 脚本来实现此目的。

问题和解决方法:

现阶段使用Document服务的DocumentApp.openById,要求使用https://www.googleapis.com/auth/documents的范围。这似乎是当前的规范。因此,在这个答案中,作为一种解决方法,我想建议使用 Google Docs API 而不是 Document 服务。使用 Google Docs API 时,您的脚本可以使用https://www.googleapis.com/auth/documents.readonly 的范围来实现。

当您使用 Google Docs API 修改上述脚本时,它变为如下。

示例脚本:

在您使用此脚本之前,please enable Google Docs API at Advanced Google services。此脚本只能在https://www.googleapis.com/auth/documents.readonly 的范围内工作。

function myFunction() {
  const documentId = "###"; // Please set the Document ID.

  const obj = Docs.Documents.get(documentId);
  const text = obj.body.content.reduce((s, c) => {
    if (c.paragraph && c.paragraph.elements) {
      s += c.paragraph.elements.map(e => e.textRun.content).join("");
    }
    return s;
  }, "");
  console.log(text)
}

参考:

【讨论】:

  • 这很酷。它返回整个文档。我以前从未使用过该 API。谢谢
  • 你是某种巫师吗?效果很好,非常感谢!现在我只需要学习 API 输出,以便更好地理解它。再次,谢谢! developers.google.com/docs/api/reference/rest/v1/documents
  • @Max 感谢您的回复和测试。我很高兴你的问题得到了解决。也谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多