In a Google Apps Script, I have the following script:
function doGet() {
return HtmlService.createHtmlOutputFromFile('mypage');
}
function writeSomething() {
return "<h1>hi people</h1>";
}
and the following html file:
<html>
<a id="caller" href="#">update</a>
<br>
<div id="div">waiting...</div>
<script>
function go() {
var a=google.script.run.writeSomething();
document.getElementById("div").innerHTML=a;
}
document.getElementById('caller').onclick = go;
</script>
</html>
When I click on the "update" link, the div content changes from "waiting..." to "undefined". I suppose that google.script.run cannot be called as a function. So, how can I solve this trouble? (obviously, this is a toy example; I need a way to update the div content from the script and not from the html file)
Run scripts from the Apps Script editor First, select the function you want to run from the dropdown menu and then click the Run button to run it.
Equality (==): a == b results in true if the value a is equal to value b. Strict equality (===): a === b results in true if the value a is equal to value b and their types are also the same. Inequality (! =): a !=
The onEdit(e) trigger runs automatically when a user changes the value of any cell in a spreadsheet.
The function writeSomething() is run asynchronously so it happens but doesn't return the response as a local function would. (This is standard for JavaScript talking to a server). Instead, you need to specify a "callback" function which gets invoked when writeSomething() is finished.
Here's the corrected version of your HTML:
<html>
<a id="caller" href="#">update</a>
<br>
<div id="div">waiting...</div>
<script>
function callback(whatToWrite) {
document.getElementById("div").innerHTML=whatToWrite;
}
function go() {
google.script.run.withSuccessHandler(callback).writeSomething();
}
document.getElementById('caller').onclick = go;
</script>
</html>
Or equivalently, you can specify the callback function inline:
...
<script>
function go() {
google.script.run.withSuccessHandler(function(whatToWrite) {
document.getElementById("div").innerHTML=whatToWrite;
}).writeSomething();
}
...
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