我想通过 Google Chrome 扩展程序在外部使用 Google AppScript 功能编辑我的 Google 文档。
为了实现这一目标,我执行了以下步骤:
- 通过 Google Docs 设置脚本
Tools > Script Editor
- 使用主体实现虚拟函数“myFunction”
var body = DocumentApp.openById(<docId>).getBody()
body.appendParagraph("Another paragraph.")
- 在脚本编辑器中添加 Google Cloud 项目 ID
Resources > Cloud Platform Project
(该 ID 与我在 Chrome 扩展程序中使用的 ID 相同;该项目还具有脚本 API 权限)。
- 通过发布脚本
Publish > Executable API
在脚本中。
- 在Chrome扩展程序的manifest.json中添加oauth2。
- 在 Chrome 扩展程序的后台脚本中使用有效的值初始化 gapi JavascriptBrowser 客户端
apiKey
and discoveryDoc
.
// gapi is available in global scope
gapi.load('client', async () => {
await gapi.client.init({
apiKey: '<apiKey>',
discoveryDocs: ['https://script.googleapis.com/$discovery/rest?version=v1'],
})
chrome.identity.getAuthToken({ interactive: true }, async (token) => {
// set my valid oauth token here
gapi.auth.setToken({
access_token: token,
})
})
})
- calling
scripts.run
:
await gapi.client.script.scripts.run({
scriptId: <scriptId>,
resource: {
function: 'myFunction'
}
})
不幸的是,我在运行脚本时收到以下错误消息:
{
code: 403,
message: "Requests to this API script method google.discovery.Discovery.GetDiscoveryRest are blocked."
status: "PERMISSION_DENIED"
}
为了确保我没有错过任何内容,我尝试通过 Postman 调用 Google Script API。我使用了端点https://script.googleapis.com/v1/scripts/{scriptId}:run
以及 Chrome 扩展程序的有效 oauth2 令牌。这成功了。
此外,我尝试更改初始化函数中的“discoveryDoc”URLhttps://www.googleapis.com/discovery/v1/apis/script/v1/rest?version=v1 https://www.googleapis.com/discovery/v1/apis/script/v1/rest?version=v1- 稍后会出现类似的错误。
{
code: 403,
message: "Requests to this API script method google.apps.script.v1.ScriptExecution.Execute are blocked"
status: "PERMISSION_DENIED"
}
我很茫然。