Message Dialogs in Apps Script

If you’ve ever written any JavaScript (or even visited web pages where it’s used) you’ll probably be familiar with the alert and prompt boxes that the language offers:

Click image to enlarge

Click image to enlarge

Google Apps Script shares most of its style and grammar with JavaScript. While the latter usually runs in the browser, though, Google Apps Scripts are run on the server. Google has thoughtfully provided server-side methods with similar abilities to these useful gadgets. The Apps Script methods are called MsgBox and InputBox, and belong to the Browser object:

inputBox(prompt) Pops up a dialog box with a text input box in the user’s browser.
inputBox(prompt, buttons) Pops up a dialog box with a text input box in the user’s browser.
inputBox(title, prompt, buttons) Pops up a dialog box with a text input box in the user’s browser.
msgBox(prompt) Pops up a dialog box with the given message and an OK button in the user’s browser.
msgBox(prompt, buttons) Pops up a dialog box with the given message and specified buttons in the user’s browser.
msgBox(title, prompt, buttons) Pops up a dialog box with the given title, message and specified buttons in the user’s browser.

Where the parameter buttons is specified, use one of the following:

OK A single “OK” button, providing a text message that can only be dismissed.
OK_CANCEL An “OK” button and a “Cancel” button, allowing the user to either go ahead with or cancel an operation.
YES_NO A “Yes” button and a “No” button, allowing the user to answer yes/no to a question.
YES_NO_CANCEL A “Yes” button, a “No” button, and a “Cancel” button, allowing the user to either answer yes/no to a question, or cancel an operation.

Here’s an example of a simple message box triggered (in this case) by opening a spreadsheet:

function onOpen() {
   Browser.msgBox('Welcome to my spreadsheet!', Browser.Buttons.OK);
}

And here’s how it appears:

Click image to enlarge

Click image to enlarge

(Extra tip: triggering a MsgBox using the onOpen() trigger like this is a handy way to give instructions or warnings to users about how your sheet should be used).

The InputBox() method, like its JavaScript equivalent prompt(), serves to collect a value from the user:

var searchstring = Browser.inputBox('Enter a search term');

which displays like this:

Click image to enlarge

Click image to enlarge

(The new version of Google Sheets offers an additional way of generating these dialogs, which I’ll cover in a future post. The code described in this post still works just fine.)