0

I have a dialog I'm displaying via the html service in Google Apps Script. From the dialog, I call a google script function (openFormSidebar) that opens a sidebar with a success handler to close the dialog.

HTML in Dialog

<button
onclick="google.script.run.withSuccessHandler(google.script.host.close()).openFormSidebar()">
Create Form</button>

The problem is that the dialog is closing (the success handler is running) before the sidebar is opened.

gs code

function openFormSidebar () {
  var html = HtmlService.createHtmlOutputFromFile('FormSidebar')
         .setTitle('Form Creation')
         .setWidth(300)
         .setSandboxMode(HtmlService.SandboxMode.IFRAME);
     SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .showSidebar(html);
}

Even if I make the openFormSidebar function a simple logger statement (i.e. Logger.log('test')) it doesn't execute (nothing is logged).

What am I missing? Why is this occuring?

Tovly Deutsch
  • 663
  • 9
  • 30

2 Answers2

2

google.script.run.withSuccessHandler(google.script.host.close()).openFormSidebar() calls google.script.host.close() and then passes its return value into google.script.run.withSuccessHandler, exactly the way foo(bar()); calls bar and then passes its return value in to foo.

You'll want to pass in a function reference instead:

google.script.run.withSuccessHandler(function() { google.script.host.close() }).openFormSidebar()`

or possibly

google.script.run.withSuccessHandler(google.script.host.close.bind(google.script.host)).openFormSidebar()`

Function#bind returns a function that, when called, calls the original with a given this value. So google.script.host.close.bind(google.script.host) creates a function that, when called, will call google.script.host.close with this set to google.script.host.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Actually just removing the () after close should work the way you expect.

Riël
  • 1,251
  • 1
  • 16
  • 31