App Script 如何检测 onOpen 方法是否是使用 Doc、Sheet 或其他类型的文档调用的?

Vin*_*eib 6 google-apps-script

在 onOpen 方法中,如何确定文档类型?

Quickstart: Add-on for Google Docs建议以下代码:

function onOpen(e) {
  DocumentApp.getUi().createAddonMenu()
      .addItem('Start', 'showSidebar')
      .addToUi(); 
}
Run Code Online (Sandbox Code Playgroud)

但是,当打开 Google Sheet 时,脚本会抛出异常:

Exception: Cannot call DocumentApp.getUi() from this context. at onOpen(Code:9:15)
Run Code Online (Sandbox Code Playgroud)

应该有一个测试,首先,检测正在打开的文档类型上下文,允许脚本选择是否以及如何添加菜单项。怎么做?onOpen的引用表明 e.source 将是不同的类型,但type of e.source只是object.

欲望是这样的:

function onOpen(e) {
  if (/* answer to this question: test if onOpen called for Doc only */) {
    DocumentApp.getUi().createAddonMenu()
        .addItem('Start', 'showSidebar')
        .addToUi(); 
  }
}
Run Code Online (Sandbox Code Playgroud)

Tan*_*ike 5

  • 您想在打开 Google Docs 时检测 Google Docs 的 mimeType。然后,您要检索 doc 的对象。
  • 您想使用 Google Apps 脚本来实现这一点。

如果我的理解是正确的,这个答案怎么样?请将此视为几个答案之一。

解决方案:

在此示例脚本中,它会在打开 Google Docs 时检索容器绑定脚本的活动文档。作为示例情况,当此脚本用于Spreadsheet 的容器绑定脚本时,DocumentApp.getActiveDocument(),SlidesApp.getActivePresentation()FormApp.getActiveForm()return null。并且只SpreadsheetApp.getActiveSpreadsheet()返回对象。本方法使用这种情况。

示例脚本:

示例脚本如下。

function onOpen() {
  var docObject = DocumentApp.getActiveDocument() ? DocumentApp :
      SpreadsheetApp.getActiveSpreadsheet() ? SpreadsheetApp :
      SlidesApp.getActivePresentation() ? SlidesApp :
      FormApp.getActiveForm() ? FormApp : null;

  // When this is used for your script, it becomes as follows.
  docObject.getUi().createAddonMenu()
        .addItem('Start', 'showSidebar')
        .addToUi();
}
Run Code Online (Sandbox Code Playgroud)
  • 例如,当上面的脚本被放入谷歌文档时,docObject成为DocumentApp. 并docObject.getUi().createAddonMenu().addItem('Start', 'showSidebar').addToUi()适用于 Google 文档。

笔记:

  • 在此脚本中,使用了以下 4 个范围。
    • https://www.googleapis.com/auth/documents
    • https://www.googleapis.com/auth/forms
    • https://www.googleapis.com/auth/presentations
    • https://www.googleapis.com/auth/spreadsheets
  • 例如,如果您不需要检查 Google 表单,请删除FormApp.getActiveForm() ? FormApp :.
  • 上面的脚本通过简单的触发器工作。但如果添加其他方法,则可能需要使用可安装的触发器。请注意这一点。

参考:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

编辑:

首先,我很抱歉我误解了你的目标。从您更新的问题中,我可以理解如下。

  • 当容器绑定脚本的父级仅为 Google 文档时,您希望运行该脚本。

如果我的理解是正确的,当使用我回答的方法时,下面的修改如何?

从:

if (/* answer to this question: test if onOpen called for Doc only */) {
Run Code Online (Sandbox Code Playgroud)

到:

if (DocumentApp.getActiveDocument()) {
Run Code Online (Sandbox Code Playgroud)
  • 在这种情况下,当它用于除 Google 文档之外的 Google 文档时,DocumentApp.getActiveDocument()返回null. 这样,除了 Google 文档之外,不会为 Google Docs 运行 if 语句中的脚本。