Auto close modal dialog - After server code is done, close dialog in Google Spreadsheet

Nick Burke picture Nick Burke · Sep 11, 2015 · Viewed 9.1k times · Source

I have a Google Sheet that runs some Apps Script server code to connect to an SQL server. I want to show the message "loading..." in the modal dialog while data is being refreshed. I can get the modal to pop up, but I want to auto-close the dialog as soon as the code is finished.

An example I have set up is:

function testpop () {
  var htmlOutput = HtmlService
    .createHtmlOutput('<p> This box will close when the data has finished loading.</p>')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME)
    .setWidth(250)
    .setHeight(200);
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Loading...');
  sleep(1000);
//close the dialog
}

I know this can be called on a client side but need it to be handled in the GS so it fires when the code is done.

Answer

Alan Wells picture Alan Wells · Sep 11, 2015

The flow of events could be:

  • User does something
  • Triggers modal dialog
  • onLoad event of modal dialog triggers client side code
  • Client side google.script.run triggers a server side .gs function to run
  • Server function in .gs script file runs.
  • database updated from server.
  • server code sends a return value back to dialog
  • "withSuccessHandler()" in dialog detects the return from the server
  • "withSuccessHandler()" runs and closes the dialog using google.script.host.close();

You'll need a <script> tag in your modal dialog.

<script>
  window.onload = function() {    
    //console.log('window.onload ran!');

    google.script.run
      .withSuccessHandler(closeDialog)
      .theFunctionNameToUpdateDatabase()
  };

  window.closeDialog = function() {
    google.script.host.close();
  };
</script>

Right now you are using:

HtmlService.createHtmlOutput(the HTML here)

You could create the HTML from a file instead:

HtmlService.createHtmlOutputFromFile(filename)