google-apps-scriptgoogle-sheetsgoogle-formsgoogle-sites

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.


Solution

  • 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.