[GAS Beginner Series #25] Display Popup Messages: Create Yes/No Confirmation Dialogs with Ui.alert()

As you get more comfortable building automation scripts and workflow tools with Google Apps Script (GAS), have you ever found yourself thinking, “I want a clear on-screen notification when the script finishes!” or “I really need an ‘Are you sure you want to proceed?’ confirmation dialog before bulk-deleting important data!”?

Until now, you’ve probably used Logger.log()—which we covered in Part 1—to inspect messages behind the scenes in the Apps Script execution log. However, if you want to notify colleagues using the spreadsheet directly via an on-screen popup or ask for their confirmation with clickable buttons, you need to show those messages right on the Google Sheets screen rather than in a hidden console log.

That brings us to the must-have method we’ll master today: Ui.alert(), which lets you display interactive dialogs (popup windows) directly on the user’s screen!

In this tutorial, we will break down everything from the basic syntax of Ui.alert() to branching conditional logic using “Yes / No” buttons and preventing accidental data loss with real-world confirmation dialogs—explained in the friendliest, most beginner-friendly way possible!

1. What Is Ui.alert()? Key Differences from Logger.log()

Ui.alert() is a Google Apps Script method that displays an interactive popup dialog (modal window) with custom messages and action buttons directly on top of the currently active Google Sheet.

First, let’s clarify the key differences between Logger.log() and Ui.alert().

AspectLogger.log()Ui.alert()
Display LocationScript Editor “Execution Log” areaCenter of the Google Sheets screen (Modal Dialog)
Target AudienceDeveloper / Script authorEnd-users interacting with the sheet (teammates or yourself)
Primary PurposeDebugging variables and checking errorsCompletion alerts, confirmation before data deletion
User InteractionNone (simply outputs text)Execution pauses until a button is clicked

Think of It as a “Concierge” Handing You a “Message Card”!

To show a popup on the Google Sheets screen, you first need to ask GAS to summon the “Concierge” (the UI object) in charge of managing the user interface.

  1. SpreadsheetApp.getUi() ➡ Call the UI “Concierge” responsible for screen operations.
  2. ui.alert("Message") ➡ Ask the concierge to present a “Message Card (Dialog)” right on the screen.

Following these two straightforward steps allows you to present a polished popup interface to anyone using your spreadsheet!

2. Basic Syntax of Ui.alert() and 3 Essential Patterns

Ui.alert() provides three core patterns depending on what you want to achieve. Each pattern is widely used in production scripts, so let’s master the essentials!

Pattern 1: Simple Notification (Message Only)

var ui = SpreadsheetApp.getUi();
ui.alert("Shopping list updated successfully!");
  • Characteristics: The simplest implementation. It presents a dialog with just a single [ OK ] button. Ideal for simple “Task Complete” notifications.

Pattern 2: Separate Title and Body Text

var ui = SpreadsheetApp.getUi();
ui.alert("Process Complete", "Shopping list updated successfully!", ui.ButtonSet.OK);
  • Characteristics: Specify the title in the first argument, the body in the second, and the button configuration in the third. Adding a prominent header makes your dialogs look much more professional and readable.

Pattern 3: Action Buttons with Conditional Branching (Super Important!)

var ui = SpreadsheetApp.getUi();
// 1. Show the confirmation dialog and capture the clicked button in the variable 'response'
var response = ui.alert("Confirm Action", "Are you sure you want to delete this data?", ui.ButtonSet.YES_NO);

// 2. Branch execution depending on which button was clicked (if statement)
if (response == ui.Button.YES) {
  // Code to execute when [Yes] is clicked
} else {
  // Code to execute when [No] is clicked
}
  • Characteristics: By adding ui.ButtonSet.YES_NO, your script can detect which button the user clicked. This is an indispensable technique before executing critical operations where you want to prevent accidental user mistakes!

3. STEP 1: Preparation! Create the Sapporo Office Snack Request Sheet

Now, let’s get hands-on and run this code inside an actual Google Spreadsheet!

For this tutorial, let’s model a realistic scenario from our Sapporo office: an order sheet for a quick convenience store lunch run to Seicomart (our beloved local chain!).

Setup Steps

  1. Create a new Google Spreadsheet and title it Sapporo Office Operations.
  2. Rename the active sheet tab at the bottom to Seicomart Run.
  3. Populate the sheet with the following sample data:
ABCD
1RequesterItem NameQuantityStatus
2SatoHot Chef Katsudon1Completed
3SuzukiFried Chicken2Completed
4TakahashiJapanese Sweets (Walnut Daifuku)3Completed
  1. Once typed in, keep the “Seicomart Run” sheet open on your screen.

4. STEP 2: Hands-On Tutorial: Build an “Are You Sure?” Confirmation Dialog

With our data ready, let’s open the Apps Script editor and write some code.

In this exercise, we will create a script that prompts users with an “Are you sure you want to delete this data?” warning dialog before clearing out the completed shopping list—clearing cells only if the user confirms by clicking [ Yes ].

To clear the data safely, we will utilize the Range.clearContent() method introduced back in Part 8, which wipes cell contents while preserving formatting and borders!

1. Enter the Code

In the spreadsheet menu, navigate to Extensions > Apps Script. Clear any template code in the editor window and paste the following snippet:

function clearShoppingListWithConfirm() {
  // 1. Get the active spreadsheet and the UI concierge
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var ui = SpreadsheetApp.getUi();
  
  // 2. Display the confirmation alert dialog and record the clicked button
  var response = ui.alert(
    "Confirm Bulk Deletion", 
    "All items in the shopping list will be deleted.\nAre you sure you want to proceed?", 
    ui.ButtonSet.YES_NO
  );
  
  // 3. Branch script execution based on user response
  if (response == ui.Button.YES) {
    // If [Yes] is clicked: clear data range (A2:D4) using clearContent()
    sheet.getRange("A2:D4").clearContent();
    
    // Display completion confirmation dialog
    ui.alert("Process Complete", "The list has been successfully cleared.", ui.ButtonSet.OK);
    
  } else {
    // If [No] or [Close (X)] is clicked: cancel safely without touching the data
    ui.alert("Cancelled", "Deletion was cancelled.", ui.ButtonSet.OK);
  }
}

2. Line-by-Line Code Breakdown

  • var ui = SpreadsheetApp.getUi();
    • Retrieves the UI object (our UI concierge) that handles interactive dialogs and prompts inside Google Sheets.
  • ui.ButtonSet.YES_NO
    • Instructs the dialog to display two choices: a [ Yes ] button and a [ No ] button.
  • "\n" (Line Break)
    • Inserting \n inside a string creates a line break, formatting long messages into clean, readable multi-line dialogs.
  • if (response == ui.Button.YES)
    • Evaluates whether the value stored in response matches the constant for the [ Yes ] button: ui.Button.YES.
  • sheet.getRange("A2:D4").clearContent();
    • Our trusty command from Part 8! It removes values from cells A2 through D4 while leaving header styling intact.

3. Save and Run the Script

  1. Click the Save icon (floppy disk) at the top of the script editor.
  2. Make sure the selected function is set to clearShoppingListWithConfirm, then click Run.
  3. Switch back to your Google Sheets browser tab!

Look at that! In the center of your spreadsheet, a dialog titled “Confirm Bulk Deletion” has appeared!

  • If you click [ No ] ➡ A message stating “Deletion was cancelled” appears, and the data in your sheet remains completely untouched.
  • If you click [ Yes ] ➡ Cells A2:D4 are wiped clean in an instant, followed by a “The list has been successfully cleared” confirmation popup!

By including this brief confirmation step, you can completely eliminate the nightmare of accidental data wipes!

5. STEP 3: Level Up! 3 Practical Ways to Use Ui.alert() at Work

Beyond standard confirmation popups, here are three practical techniques frequently used in day-to-day workflow development.

Pattern A: Available Button Sets (ButtonSet Reference)

Here is a quick reference table showing the button combinations you can define in ui.alert() and their corresponding return values.

Specified ButtonSetDisplayed ButtonsComparison Constant (ui.Button)
ui.ButtonSet.OK[ OK ]ui.Button.OK
ui.ButtonSet.OK_CANCEL[ OK ] [ Cancel ]ui.Button.OK, ui.Button.CANCEL
ui.ButtonSet.YES_NO[ Yes ] [ No ]ui.Button.YES, ui.Button.NO
ui.ButtonSet.YES_NO_CANCEL[ Yes ] [ No ] [ Cancel ]ui.Button.YES, ui.Button.NO, ui.Button.CANCEL

Pattern B: Embed Dynamic Variables and Calculated Values

Instead of hardcoded text, embedding calculated numbers or dynamic variables makes your tools significantly more useful for team members.

function notifyTaskCount() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var ui = SpreadsheetApp.getUi();
  
  // Find the last row containing data (refer to Part 11)
  var lastRow = sheet.getLastRow();
  var count = lastRow - 1; // Exclude header row
  
  // Inject dynamic count right into the popup message!
  ui.alert("Current Order Status", "There are currently " + count + " Seicomart lunch requests submitted!", ui.ButtonSet.OK);
}

Pattern C: Show a Welcome Notice When the Sheet Opens

By combining Ui.alert() with simple triggers like onOpen(e) (which we will dive into in Part 21), you can automatically display an announcement the exact second a team member opens the spreadsheet!

function onOpen(e) {
  var ui = SpreadsheetApp.getUi();
  ui.alert(
    "[Sapporo Office Notice]", 
    "We are heading to Seicomart at 3:00 PM today.\nPlease submit any additional snack requests by 2:30 PM!", 
    ui.ButtonSet.OK
  );
}

6. 5 Common Pitfalls Beginners Face and How to Avoid Them

When working with Ui.alert(), beginners often encounter a few common stumbling blocks. Here are five classic traps and how to solve them.

Trap 1: Calling Ui.alert() Directly Without getUi()

A very frequent mistake is attempting to call Ui.alert() like this:

// INCORRECT: Will throw an error (getUi was not called)
Ui.alert("Process completed!");
// Error message: ReferenceError: Ui is not defined

The Ui object does not exist in the global scope on its own. Remember the rule: always summon your UI concierge with var ui = SpreadsheetApp.getUi(); first, then call ui.alert(...)!

Trap 2: Using Ui.alert() Inside Time-Driven (Clock) Triggers

[Important!] Ui.alert() can only function when an active user has the spreadsheet open on their computer screen.

If you try calling Ui.alert() inside an automated script triggered by a time-driven clock trigger (like an overnight background job), the script will fail with this error:

Exception: Cannot call SpreadsheetApp.getUi() from this context.

For scheduled background jobs running without a user present, bypass modal dialogs and use Gmail notifications or Slack/LINE webhooks instead!

Trap 3: Casing Mistakes with ui.Button.YES

JavaScript is strictly case-sensitive:

  • ✕ ui.button.yes (all lowercase)
  • ✕ ui.Button.Yes (only capital Y)
  • ◯ ui.Button.YES (capitalized Button, uppercase YES)

If the casing doesn’t match, your if condition will fail silently even when the user clicks [ Yes ], leading to baffling bugs.

Trap 4: Forgetting that Alerts Pause Script Execution

While a ui.alert() dialog is active on screen, GAS execution halts and waits patiently until a button is clicked.

If you accidentally place ui.alert() inside a for loop, you’ll create a user nightmare where a popup appears for every single row of data, requiring hundreds of manual button clicks.

As a best practice, reserve alert dialogs for the very start (confirmation) or the very end (completion report) of your scripts.

Trap 5: Typing the Wrong Slash for Line Breaks

When trying to insert line breaks, typing forward slashes like /n instead of backslashes \n is a classic typo.

  • ✕ "Line 1/nLine 2" ➡ Literally displays “Line 1/nLine 2”
  • ◯ "Line 1\nLine 2" ➡ Correctly breaks into two lines

Make sure you are using the backslash character followed by a lowercase n (\n).

7. Summary & What’s Next

In this guide, we explored how to use Ui.alert() to bring interactive notifications and confirmation dialogs right into Google Sheets.

Key Takeaways for Today

  1. Call the UI concierge first using SpreadsheetApp.getUi()
  2. Show quick modal alerts using ui.alert("message")
  3. Use ui.ButtonSet.YES_NO to create confirmation prompts
  4. Evaluate the clicked button (ui.Button.YES) with if statements to branch logic safely
  5. Remember that Ui.alert() cannot run inside automated time-driven triggers

With dialogs under your belt, your tools are no longer just one-way scripts—they are friendly, interactive applications that work collaboratively with your team!

Now that you can prompt users with confirmation buttons, the natural next step is: “How do I let users type in custom text or numbers directly through a popup and process that input in GAS?”

In Part 26, we will dive into Ui.prompt(), the input prompt method that lets you collect user text on the fly!

Imagine asking for an assignee name or a target date range right from a popup to drive dynamic spreadsheet workflows. Stay tuned—it’s going to be lots of fun!