Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom menu onOpen does not show

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.

like image 629
antonio Avatar asked Oct 24 '25 04:10

antonio


2 Answers

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.

like image 68
Alejandro Silvestri Avatar answered Oct 26 '25 17:10

Alejandro Silvestri


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

like image 29
FrinkTheBrave Avatar answered Oct 26 '25 19:10

FrinkTheBrave