Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Google apps script automatically upon loading a Google Site?

I wrote an Apps Script that takes a spreadsheet and converts it into a Google form. I want to display the form on my google site; however, I want the form to automatically refresh every time the site is opened, so that if the spreadsheet has changed, the form will also be updated when it displays. Essentially, I want the script to run automatically upon open of the Google site – any idea how to do this?

Also, as a side note (not as important), is there any way to incorporate a script into a google site without displaying it as a gadget? I don't want to display the script, I just want it to run in the background.

like image 960
Kooshul Avatar asked Jul 03 '26 13:07

Kooshul


1 Answers

You can run an Apps Script function indirectly when the site loads by creating a stand alone Web App with HTML Service, publishing it, and putting window.onload into a script tag:

<script>
  window.onload = function() {
    console.log('Onload ran. ');//Open the browser console log to see debug messages

  };
</script>

Then use google.script.run to run a server function:

<script>
  window.onload = function() {
    console.log('hah! it ran. ');
    google.script.run
      .withSuccessHandler(run_This_On_Success)
      .gsServerFunction();
  };

 window.run_This_On_Success = function(the_Return) {
   console.log('was successful!: ' + the_Return);
 };

Code.gs

function gsServerFunction() {
  return true;
};

index.html

<!DOCTYPE html>
<html>
  <body>
    This is the body


    <script>
      window.onload = function() {
        console.log('hah! it ran. ');
        google.script.run
          .withSuccessHandler(wuzSugzezvul)
          .gsServerFunction();
       };

       window.wuzSugzezvul = function() {
         console.log('was successful!');
       };
    </script>
  </body>
</html>

Remove the border and the title of the apps script gadget, make it very small, and don't put in any text to display in the HTML.

like image 131
Alan Wells Avatar answered Jul 07 '26 05:07

Alan Wells



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!