Hello,
The issue you're experiencing where clicking outside a dialog box like InputBox, Prompt, or MsgBox causes it to close and results in a "Error resuming script execution" is due to how Google Apps Script handles these UI elements. Typically, this error arises from the script execution environment's handling of asynchronous interruptions or unexpected exits from dialog boxes.
When a user clicks outside of a dialog box in a Google Sheets UI created with Apps Script, it's considered an "interruption" of the dialog, and Google Apps Script doesn't always handle these interruptions gracefully. The script is paused awaiting user input, and when the input method is prematurely closed, it fails to resume correctly, thus leading to the error.
Solutions to Handle or Prevent the Error
1. Using Try-Catch to Handle the Error
One way to manage these issues in your script is by using `try-catch` blocks. This won't prevent the dialog from closing but will handle the error more gracefully.
function showPrompt() {
try {
var ui = SpreadsheetApp.getUi(); // Or DocumentApp or FormApp.
var response = ui.prompt('Step 1 of 2', 'Please enter something:', ui.ButtonSet.OK_CANCEL);
// Process the user's response.
if (response.getSelectedButton() == ui.Button.OK) {
Logger.log('The user\'s name is %s.', response.getResponseText());
} else if (response.getSelectedButton() == ui.Button.CANCEL) {
Logger.log('The user didn\'t want to provide their name.');
} else {
Logger.log('The user clicked the close button in the dialog\'s title bar.');
}
} catch(e) {
Logger.log("The prompt was closed unexpectedly: " + e.toString());
ui.alert("Please do not click outside the dialog box.");
}
}
2. Custom HTML Dialogs
For more robust handling, consider using HTML service to create custom dialogs. These can be designed to handle outside clicks better and provide more control over user interactions.
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setWidth(400)
.setHeight(300);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Title of the dialog');
}
// Include this in a file named "Page.html" in your Apps Script project
// <html>
// <head>
// <base target="_top">
// </head>
// <body>
// <p>Please enter your name:</p>
// <input type="text" id="name">
// <button onclick="google.script.host.close()">Close</button>
// </body>
// </html>
In the HTML dialog approach, you have more control over the behavior when the user clicks outside the modal dialog if you set it up to not close on such interactions, depending on how you configure the dialog in your HTML and CSS.
While there's no direct way to prevent the default behavior of these UI dialogs from being closed by clicking outside, implementing one of the above solutions should help manage or circumvent the issue. The custom HTML dialog approach offers the most flexibility and robustness if you're comfortable with HTML and JavaScript.