aatakan aatakan - 7 months ago 33
HTML Question

Running Google Script Function in HTML JavaScript Header section

I have a function that is defined in my Google App Script (code.gs) called myFunction() which accesses information from a Google Sheet. I want to be able to call this function from the script header in the html file where a HTML form is generated. I have tried running google.script.run.myFunction() in the script header of the HTML page however it doesn't return any variable, just undefined. A code snippet for the header of the HTML is below.

<script>
function getArray(){
var equipment = google.script.run.myFunction();
console.log(equipment);
}
</script>


When looking at the console.log the output is undefined. I have tried changing the output of myFunction to many other types of outputs and when I use the Logger.log function in the GS, it outputs the correct variable however it simply doesn't transfer over to the HTML form. Does anyone have any suggestions?

I am doing it in this way as I am using this variable to dynamically created checkboxes in the HTML form and this is the simplest way I can think of doing this.

Thanks!

Answer

The only way to receive a return value is with the:

.withSuccessHandler(myHandlerFunction)

The complete code would be:

<script>
function getArray(){
   google.script.run
     .withSuccessHandler(myHandlerFunction)
     .myFunction();
  }

  function myHandlerFunction(equipment) {
    console.log('equipment: ' + equipment);
  };
</script>

Apps Script Documentation - run methods