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>
I use it normally, and it works fine.
But I never tried it before the page load. Since Google has a lot of security barriers, such as replacing the html body with its own custom body, I think it's worth trying to call it in a handler for the page load.
Try putting alerts in the handlers (see below) to see if it is really being run. Any little mistake in other parts of the html code often makes the entire script simply not run.
Things to be aware of: if you have global variables in your server side script, these will not persist!!! They will reset everytime you use google.script.run. So, make sure doSomething() has everything it needs on its own.
And if you expect to see a result after doSomething(), consider adding the handlers to google.script.run. You server side script will not be able to change the user interface nor open a new one if it's modal. (Never tried non modal...)
google.script.run
.withSuccessHandler(function(data,element){window.alert("executed");})
.withFailureHandler(function(msg,element){window.alert("failed"); })
.doSomething();
If none of the messages appear, the problem is not here, but elsewhere. Some other thing is preventing your script from even starting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With