Google Apps Script Success Handler Running before

2019-09-22 03:36发布

问题:

This question already has an answer here:

  • How to hide the Sidebar in a Google Spreadsheet using a script? 2 answers

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?

回答1:

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.



回答2:

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