Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use google.script.run as if it was a function

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)

like image 445
tic Avatar asked Jul 14 '12 20:07

tic


People also ask

How do I run a function in Google Apps Script?

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.

What is === in Google script?

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 !=

How do you trigger an onEdit in Google Sheets?

The onEdit(e) trigger runs automatically when a user changes the value of any cell in a spreadsheet.


1 Answers

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();
}
...
like image 57
Corey G Avatar answered Nov 06 '22 05:11

Corey G