我是否可以使用具有只读权限的DocumentApp.OpenByID()? [英] Can I use DocumentApp.openById() with read only permission?
问题描述
我正在创建一个Google Apps脚本插件,用于Google电子表格,但它需要能够访问单独的Google Doc的内容,这是我使用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)
}
谢谢!
推荐答案
我相信您的目标如下。
您要使用以下脚本从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脚本来实现此目的。
问题和解决方法:
在当前阶段,使用文档服务的DocumentApp.openById
,需要使用https://www.googleapis.com/auth/documents
的作用域。看来这就是目前的规格。因此,在这个答案中,作为一种变通办法,我建议使用Google Docs API来代替文档服务。当使用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)
}
参考:
这篇关于我是否可以使用具有只读权限的DocumentApp.OpenByID()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!