This snippet creates a custom menu, when opening the sheet, as expected:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('First item', 'menuItem1')
.addToUi();
}
function menuItem1() {
SpreadsheetApp.getUi().showModelessDialog(userInterface, title)
.alert('You clicked the first menu item!');
}
Adding this this line:
var CALNAME= CalendarApp.getDefaultCalendar();
prevents the custom menu to show, unless I manually run onOpen(). I can fix it using a function:
function CALNAME() {
return CalendarApp.getDefaultCalendar();
}
but I would like to understand why assigning the variable does not work.
when you start a script in GAS (in this case, open event fires onOpen function), GAS loads all code, execute the one in the body (in this case, var CALNAME= CalendarApp.getDefaultCalendar(); ), and after that executes onOpen.
It seems to be an error that quit execution when evaluating CalendarApp.getDefaultCalendar() , so onOpen never gets executed.
The common cause is this: open event executes onOpen in a "privilegesLESS" environment for security reasons, so you are very limited on what onOpen can do. It seems you can't execute CalendarApp.getDefaultCalendar() in that environment.
Try to call CALNAME() from onOpen, you will see it breaks.
The answer is to use an installable trigger, rather than the standard onOpen.
See the 'Managing triggers manually' bit in Installable Triggers Reference. Thanks to Serge insas for the tip in this question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With