Custom Dialogs in Google Apps Script

In previous posts I’ve shown how to open dialogs such as alert() and prompt() to help you communicate messages to users and/or have them enter information. In addition to these pre-written dialogs, Apps Script lets you build custom modal dialogs to your own design.

A custom dialog can display a UI Service user interface inside a Google Docs document, a Sheets spreadsheet, or a Forms editor. Unlike alert() and prompt(), these custom dialogs do not pause the server-side script while the dialog is open; it carries on running.

Docs, Forms, and (the new version of) Sheets all use the following method to open the dialog:

Ui.showModalDialog()

First, we need to create the dialog in HTML. The following code goes into a new HTML file opened via the Script Editor:

<style>
   h2 { color:red; font: 20px bold verdana, helvetica, sans-serif; }
   p { font: 14px normal verdana, helvetica, sans-serif; }
   #btn { float:right; border-radius: 15px; }
</style>

<div>
<h2>Warning</h2>
<p>The action you are performing may be way too cool for some users.</p>
<p>Try to dial back the awesomeness a little now and then.</p>
<input id="btn" type="button" value="X" onclick="google.script.host.close()" />
</div>

Here’s the code in the editor:

Click image to enlarge

Click image to enlarge

Here I’ve used a simple message that I could have done equally well with alert(), but it serves for a demonstration. I’ve also used some CSS to change the look a little, rounding off the button corners and changing a few fonts.

Next, the server-side code. The onOpen() trigger code will probably be familiar from previous posts on the subject (if not, see this post)

function onOpen() {
 SpreadsheetApp.getUi()
 .createMenu('Custom Dialog')
 .addItem('Show dialog', 'showDialog')
 .addToUi();
}

function showDialog() {
 var html = HtmlService.createHtmlOutputFromFile('Dialog1')
 .setWidth(300)
 .setHeight(200);
 SpreadsheetApp.getUi().showModalDialog(html, 'A message from the boss');
}

The function showDialog() is where the html code is generated from the file Dialog1.html and passed to showModalDialog(). Here’s the result when the newly-created menu item is clicked:

Click image to enlarge

Click image to enlarge

In a real application, you might want more interaction from your custom dialogs; the chance for users to enter information, perhaps, or choose between various options. See this post for information on using google.script.run in your dialogs to achieve that.