[英]Customizing the apps script add-ons menu for each editor
I've got an add-on that previously only targeted Google Docs, and I'm trying to expand the feature set to include Google Sheets.我有一个以前只针对 Google 文档的附加组件,我正在尝试扩展该功能集以包含 Google 表格。 In development mode, I can set a conditional to detect which document type is active (docs or sheets) and then show the corresponding menu.
在开发模式下,我可以设置一个条件来检测哪个文档类型处于活动状态(文档或工作表),然后显示相应的菜单。 When I publish the latest version of the add-on, the add-on menu stops working in both Docs and Sheets.
当我发布最新版本的插件时,插件菜单在文档和表格中都停止工作。
I'm guessing it has to do with the permissions around "onOpen()" but i'm not sure how else to handle this.我猜这与“onOpen()”周围的权限有关,但我不知道如何处理这个问题。 The G Suite Marketplace allows you to designate that an add-on supports multiple editors.
G Suite Marketplace 允许您指定一个插件支持多个编辑器。
Here's the code that works in development:这是在开发中工作的代码:
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var doc = DocumentApp.getActiveDocument();
if(ss != null && ss != undefined) {
var sheetsUI = SpreadsheetApp.getUi();
sheetsUI.createAddonMenu()
.addItem('Name', 'function')
.addToUi();
}
if(doc != null && doc != undefined) {
var docsUI = DocumentApp.getUi();
docsUI.createAddonMenu()
.addItem('Name', 'function')
.addToUi();
}
}
If I remove the conditional stuff, and only include editor specific menu (docs for docs, sheets for sheets), the menus appear correctly.如果我删除有条件的东西,并且只包含特定于编辑器的菜单(文档为文档,工作表为工作表),则菜单会正确显示。
You wouldn't want the user to need to approve access to their Sheets, if it's a Docs add-on and vice versa.如果是 Docs 插件,您不希望用户需要批准访问他们的表格,反之亦然。 And if the add-on doesn't have permission to one of them then your code would throw an error, so you need to trap the error with a
try/catch
如果附加组件对其中之一没有权限,那么您的代码将引发错误,因此您需要使用
try/catch
错误
function onOpen(e) {
var docUI,thisIsA_Sheet;
try{
docUI = SpreadsheetApp.getUi();
thisIsA_Sheet = true;
}catch(e){
//Do nothing
}
if (!thisIsA_Sheet) {//This is not a Google Sheet
try{
docUI = DocumentApp.getUi();
}catch(e){
//Do nothing
}
}
docUI.createAddonMenu()
.addItem('Name', 'function')
.addToUi();
}
The comment about trapping errors led me to the solution.关于捕获错误的评论使我找到了解决方案。 I placed each editor's menu code inside try/catch blocks, and now it works.
我将每个编辑器的菜单代码放在 try/catch 块中,现在它可以工作了。
function onOpen(e) {
try{
var docsUI = SpreadsheetApp.getUi();
docsUI.createAddonMenu()
.addItem('Sheets menu item name', 'function')
.addToUi();
} catch(e) {
}
try{
var docsUI = DocumentApp.getUi();
docsUI.createAddonMenu()
.addItem('Docs menu item name', 'function')
.addToUi();
} catch(e) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.