How to know which menu item was clicked?

2020-03-07 05:16发布

问题:

I'm creating a dynamic custom menu from REST call in google spreadsheet. With every call I receive different sports that I want to use as menu items

  // sample sports array
  var menuItemsArr = ['Footbal', 'Tennis', 'Swimming'];

  var menu = SpreadsheetApp.getUi().createMenu("Sports");
  for (i in menuItemsArr){
      menu.addItem(menuItemsArr[i],'createSheet')
       .addSeparator()
  }
  menu.addToUi();

When the user clicks on menu item I want to create a new sheet with title - the sport that was clicked. So if the user choose Tennis I want to create a sheet with name Tennis.

Is it possible to know which menu item was clicked (to take the name of the item (Tennis) somehow, or at least the index of the menu item that was clicked?

Any help will be appreciated! Thanks.

回答1:

Google Apps Script .createMenu and .createAddonMenu are able to call functions by their name as string and only looks for functions with that name on the Apps Script project global scope.

The alternative is to create your user interface by using a dialog or sidebar with the HTML Service.