Creating a custom menu

You might be wondering whether you can execute the greeting function without the help of the button. The answer is yes. In the script editor, there is a Run menu. If you click on Run | greeting, then the greeting function will be executed and the message box will open.

Creating a button for every function may not be feasible. Although you cannot alter or add items to the application's standard menu (except the Add-ons menu) such as File, Edit, View, and so on, you can add custom menus and menu items.

For this task, create a new Google Docs document or open an existing document. Open the script editor and type these two functions:

function createMenu() {
  DocumentApp.getUi()
   .createMenu("PACKT")
   .addItem("Greeting","greeting")
   .addToUi();
}

function greeting() {
  var ui = DocumentApp.getUi();
  ui.alert("Greeting", "Hello World!", ui.ButtonSet.OK);
}

In the first function, you are using the DocumentApp class, invoking the getUi method, and consecutively invoking the createMenu, addItem, and addToUi methods by method chaining. The second function should be familiar to you, as you created it in the previous task, but this time with the DocumentApp class and associated methods.

Tip

Do not copy-paste these functions or codes; create/edit them yourself line by line. This will help you become familiar with the script editor's code hinting and completion features.

Now run the createMenu function and flip to the document window/tab. You will see a new menu item called PACKT added next to the Help menu. You can see the custom menu PACKT with an item Greeting as shown in the following screenshot. The item label Greeting is associated with the function greeting.

Creating a custom menu

The menu item Greeting works the same way as the button created in the previous task. The drawback with this method of inserting the custom menu is that to get the custom menu to show up, you need to run createMenu every time within the script editor. Consider how your user would be able to use this greeting function if they didn't know about GAS and the script editor. Think about how your user may not be a programmer like you. To enable your users to execute selected GAS functions, you should create a custom menu and make it visible as soon as the document opens. To do so, rename the createMenu function onOpen, and that's all.

Tip

The onOpen function is a special function name. Whenever a user opens a document, the GAS interpreter executes this function first. Other similar function names are onEdit, onInstall, doGet, and doPost. The first two are spreadsheet event-related functions and the next two are published script service's get and post callback functions. You should not use these function names other than for the intended purposes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.64.229