According to the documentation, calling a Google Apps Script function from a client HTML script should be as simple as google.script.run.myFunction()
. However it doesn't seem to work for me:
My Code
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'My Dialog');
}
function doSomething() {
var sheet = SpreadsheetApp.getActive().getActiveSheet();
sheet.getRange(sheet.getLastRow()+1, 1).setValue("Hello :)");
}
Note that calling doSomething()
from the IDE runs smoothly. However not from the HTML script:
My HTML
<script>
google.script.run.doSomething();
</script>
That appears to be all about timing -
google.script.run
may be getting called before the client-server connection is ready*. The usual intent of displaying a user interface is to interact with a user - and because people are much slower than machines, you'd not encounter this problem.Even a short delay to display a
toast
is enough to make it work.Free bonus! Thinking ahead to the next problem you'll run into, note the
return
statement. A server function must have some kind ofreturn
to cause a callback to thegoogle.script.run.onSuccess()
handler.*Edit - Something isn't quite right with this explanation, since the
toast
call is on the server. Would be nice if a Googler would speak up to offer a better explanation.