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)
如果我的理解是正确的,这个答案怎么样?请将此视为几个答案之一。
在此示例脚本中,它会在打开 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 文档。https://www.googleapis.com/auth/documentshttps://www.googleapis.com/auth/formshttps://www.googleapis.com/auth/presentationshttps://www.googleapis.com/auth/spreadsheetsFormApp.getActiveForm() ? FormApp :.如果我误解了您的问题并且这不是您想要的方向,我深表歉意。
首先,我很抱歉我误解了你的目标。从您更新的问题中,我可以理解如下。
如果我的理解是正确的,当使用我回答的方法时,下面的修改如何?
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)
DocumentApp.getActiveDocument()返回null. 这样,除了 Google 文档之外,不会为 Google Docs 运行 if 语句中的脚本。| 归档时间: |
|
| 查看次数: |
496 次 |
| 最近记录: |