Tutorials

How To Use A Custom Menu To Execute Google Apps Scripts

Custom menus execute a custom functions or Google Apps Scripts.  And they are the simplest method to do so.  The custom menu has options for submenus and dividers to group menu items nicely.  Inserting your menu is done easily using Google’s reserved trigger function called “onOpen”.  And because of this, building and including your custom menu into the UI is simple and effective.

 

Objective




Add a menu and execute a Google Apps Script upon opening a Google Docs Document.

Steps

Create and open a bound Google Apps Script

  • Open a Google Doc
  • Select Tools, then Script Editor from the top level menu. This will open a blank Google Apps Script project

Create The Custom Menu

  • Change the function name from “myFunction” to “onOpen” with no arguments
  • Add code so your editor looks like the following:

function onOpen() {

var menu = DocumentApp.getUi().createMenu(‘Custom Menu’);

menu.addItem(‘Custom Alert’, ‘customAlert’).addToUi();

};

  • Save the project
  • Make sure the drop down menu in the toolbar says “onOpen” and select Run
  • Go back to the Google Doc to see the custom menu added as a top-level menu item

Create A Custom Function

  • In the Google Apps Script, add a new line by pressing enter on the keyboard.
  • Add the following code into the editor:

function customAlert() {

var msg = ‘Congrats! You just executed your first function with from a custom menu!’;

DocumentApp.getUi().alert(msg);

};

  • Save the project

Run The Custom Function

  • Go back to the Google Doc, open the menu and select the “Custom Alert” menu item

Use Cases




Google gifted us by allowing access to the top-level user interface in some Drive Apps. Also, it makes for a more seamless feel when adding menus and submenus into the UI. Whether you execute a script or open a sidebar from the menu, it’s a simple and effective method to integrating your own Google Apps Script projects into some Google Drive Apps.

Related Articles

 

What did you think???