Google Apps脚本/如何设置整个段落的背景颜色? 更新1-Google文档API的UrlFetchApp为403 原始问题

问题描述

我正在寻找一个.gs函数,以通过Google Docs扩展名更改Google脚本中整个段落的背景。

虽然我一直在尝试使用外部API调用this answer中的代码段;并尝试使其正常工作,理想情况下,它会很简单:

...
var paragraph = <some way of getting the paragraph>;
paragraph.setBackgroundColor('#112233');
...

更新1-Google文档API的UrlFetchApp为403

突出显示最后一行完全停止工作-现在我遇到了异常。

尝试使用已发布的答案here中的代码时,我从下面获得了403 Unauthorized

  var baseUrl = "https://docs.googleapis.com/v1/documents/";
  var headers = {"Authorization": "Bearer " + ScriptApp.getoAuthToken()};
  // Logged the headers and it contains a bearer token,so it's not empty or null.
  var params = {headers: headers};
  // 403 from UrlFetchApp querying for docs.googleapis.com
  var res = UrlFetchApp.fetch(baseUrl + id + "?fields=*",params);

这就是我的作用域:

https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/script.container.ui
https://www.googleapis.com/auth/script.external_request

这是appsscript.json的摘录:

  "timeZone": "REDACTED","dependencies": {
    "enabledAdvancedServices": [{
      "userSymbol": "Docs","serviceId": "docs","version": "v1"
    }]
  },"exceptionLogging": "STACKDRIVER","runtimeVersion": "V8"
}

我已经通过Resources->Advanced Google Services打开了Docs API访问,并且看起来通过菜单处于活动状态:

enter image description here

原始问题

好像我们有这个答案:https://webapps.stackexchange.com/questions/126354/how-can-i-set-a-background-color-for-an-entire-paragraph

但是在尝试时,它只是改变了段落最后一行的背景,而不是像gif显示那样设置整个背景。它也使用了额外的呼叫。所以我想知道也许会有一个更新的API直接设置段落背景(不是文档指出这一点)。

解决方法

我已将答案发布为here才能正常工作。 我必须在appsscript.json中显式设置docs服务-由于某种原因检测到它还不够。

我的appsscript.json看起来像这样:

{
  "timeZone": "...","dependencies": {
      "enabledAdvancedServices": [{
        "userSymbol": "Docs","serviceId": "docs","version": "v1"
      }]
  },"oauthScopes": [
    "https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/script.container.ui","https://www.googleapis.com/auth/script.external_request"
  ],"exceptionLogging": "STACKDRIVER","runtimeVersion": "V8"
}

完成后,所描述的解决方案便对我有用。