A Newer Way to make Dialogs in Apps Script

In a previous post I discussed the creation of user dialogs in Apps Script, using the Browser object. While this code still works, Google has gone away from this sort of interface, instead concentrating on the UI service. In thios article I show you how to use the newer syntax to generate user dialogs.

In place of Browser.msgBox, Google now recommends using the ui alert() method. Here’s an example:

var ui = SpreadsheetApp.getUi();
var userChoice = ui.alert(
   'Please confirm',
   'Are you sure you want to continue?',
   ui.ButtonSet.YES_NO);

An alert is a modal dialog box that opens inside a Google Docs, Sheets, or Forms document. It displays a user message along with an “OK” button. Alerts suspend the server-side script from being executed while the dialog is open, allowing it to resume after the the dialog is closed.

A dialog title, and alternative buttons to the default OK are optionally configurable too. The method is similar to the JavaScript window.alert() method available in client-side JavaScript code. To override the default OK button with alternative buttons, pass a value from the set of buttons arguments listed in the previous post. In some of these cases, we need to evaluate the user’s response by capturing the return value, for example in the following example function showChoice():

function showChoice() {
   var ui = SpreadsheetApp.getUi();
   var userChoice = ui.alert(
      'Please confirm',
      'Are you sure you want to continue?',
      ui.ButtonSet.YES_NO);
   if (userChoice == ui.Button.YES) {
      ui.alert('Operation Confirmed.');
   } else {
      ui.alert('Operation Halted.');
   }
}

Here’s the example code shown in the code editor, here driven by an onOpen() trigger:

Click image to enlarge

Click image to enlarge

The code generates the following dialog:

Click image to enlarge

Click image to enlarge

Here’s the confirmation dialog shown after clicking ‘Yes’:

Click image to enlarge

Click image to enlarge

The alert() method can also be used to build dialogs that require the user to type input, similar to calling window.prompt() in client-side JavaScript, as shown in the following code example:

function showChoice() {
   var ui = SpreadsheetApp.getUi();
   var userChoice = ui.prompt(
      'Name Required',
      'Please enter your name:',
      ui.ButtonSet.OK_CANCEL);
   var button = userChoice.getSelectedButton();
   var text = userChoice.getResponseText();
   if (button == ui.Button.OK) {
      ui.alert('OK, thanks ' + text);
   } else {
      ui.alert('Stay mysterious, then.');
   }
}

Here we collect the user-entered text and access it via the line:

var text = userChoice.getResponseText();

Here’s how such a prompt dialog looks: 

Click image to enlarge

Click image to enlarge

There are further options for the generation of custom dialogs displaying either HTML service or UI service user interfaces, such as in this post.