Max*_*Max 2 google-docs google-apps-script
我正在创建一个用于 Google 电子表格的 Google Apps 脚本插件,但它需要能够访问单独的 Google 文档的内容,我正在使用DocumentApp.openById()执行此操作。我已经给脚本提供了这些范围:
"oauthScopes": [
"https://www.googleapis.com/auth/documents.readonly",
"https://www.googleapis.com/auth/script.container.ui",
"https://www.googleapis.com/auth/spreadsheets.currentonly"
]
Run Code Online (Sandbox Code Playgroud)
但显然,这还不够。该脚本告诉我它需要https://www.googleapis.com/auth/documents许可才能正常工作。然而,当它只需要能够查看一个文件的内容时,授予该附加组件编辑所有 Google 文档文件的权限似乎有些过分。我错过了什么吗?有没有办法赋予它对单独的 Google 文档文件的只读访问权限?
这是我用于测试的函数,大部分文档 ID 已被删除:
function getDoc() {
var id = '1NLH----------------------------------------'
var templateFile = DocumentApp.openById(id)
var templateText = templateFile.getBody().getText()
Logger.log(templateText)
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
我相信你的目标如下。
您想要使用以下脚本从 Google 文档检索文本数据。
function getDoc() {
var id = '1NLH----------------------------------------'
var templateFile = DocumentApp.openById(id)
var templateText = templateFile.getBody().getText()
Logger.log(templateText)
}
Run Code Online (Sandbox Code Playgroud)
您希望使用https://www.googleapis.com/auth/documents.readonlyGoogle Apps 脚本的范围来实现此目的。
现阶段DocumentApp.openById使用Document服务,要求使用范围为https://www.googleapis.com/auth/documents. 看来这是当前的规范。因此,在这个答案中,作为一种解决方法,我想建议使用 Google Docs API 而不是文档服务。当使用 Google Docs API 时,您的脚本可以使用https://www.googleapis.com/auth/documents.readonly.
当使用 Google Docs API 修改上面的脚本时,它会变成如下所示。
在使用此脚本之前,请在高级 Google 服务 中启用 Google Docs API。该脚本只能在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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1458 次 |
| 最近记录: |