简体   繁体   中英

from google script to html

I have a function in a .gs file:

function testReturn(){
 return "Finaly it works!";
}

and an other in an html file:

<script>
  window.addEventListener('load', function() {
    google.script.run.withSuccessHandler(createPost).testReturn();
  });

  /**/

  document.getElementById("go_button").addEventListener("click",functionGo);

  function functionGo(){

    var textToDisplay = google.script.run.testReturn();

    document.getElementById("input1_id").value = textToDisplay;   
  }

</script>

The return is always "undifined". How can I interact between gs and html script? (Of course I don't only want to return an integer, the project is to get a long text wrote with many functions, I'm just looking for a way to get the result and to dispaly it on a html).

Thanks you

You are not implementing the createPost function which is the callback function (because you set it in withSuccessHandler function [1]) that will receive the value returned in your testReturn function from code.gs.

For your html, the code below will update the input value as soon the page is loaded. It should work for you if you have an input element with id set to 'input1_id':

<script>
  window.addEventListener('load', function() {
    google.script.run.withSuccessHandler(createPost).testReturn();
  });

  function createPost(returnedValue){
    document.getElementById("input1_id").value = returnedValue;   
  }
</script>

If what you want is to update the input value after a button is clicked, you can use this instead (assuming you have a button with 'go_button' as id):

<script>
  document.getElementById("go_button").addEventListener("click",functionGo);

  function functionGo(){
    google.script.run.withSuccessHandler(createPost).testReturn();
  }

  function createPost(returnedValue){
    document.getElementById("input1_id").value = returnedValue;   
  }

</script>

Basically, calling an Apps Script function (code.gs) from the html with google.script.run [2] won't directly return you the value, but rather you have to manage the response with a callback function set in one or more of the handler functions [1] (like withSuccessHandler in this example).

[1] https://developers.google.com/apps-script/guides/html/communication#success_handlers

[2] https://developers.google.com/apps-script/guides/html/reference/run

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM