1

In my index.html file (before closing body tag), I want a function to self-invoke itself when the page is loaded. However, I am having issues when the function (here, setUp) is defined in an external file.

If I copy-paste the setUp function in Index.html then everything works as expected.

I am new to JS: am I incorrectly linking script file? Thanks!

Index.html

    <script src="Code.gs">
        window.onload=setUp;
    </script>

Code.gs

        function setUp() {
            dateHelper_();
        }

Student
  • 41
  • 7
  • Please read https://developers.google.com/apps-script/guides/html – Rubén May 26 '19 at 03:18
  • I think that [the issue of your new question](https://stackoverflow.com/q/56311127/7108653) is related to this question. And this question is a simpler script than new one. So I think that when you understand this question and answer, it will help you understand the issue of your new question. I can support for these situations. When my answer is not useful for your situation, please tell me. I would like to modify it. – Tanaike May 26 '19 at 06:26

1 Answers1

1
  • You want to run Google Apps Script when HTML is loaded.

If my understanding is correct, how about this modification? The flow of this modified script is as follows.

  1. When the HTML is opened, google.script.run is run and setUp() of Google Apps Script is run.
  2. When setUp() is finished, "ok" from setUp() is returned and the returned value is shown using console.log() at withSuccessHandler().
    • In this modified script, you can see Done: ok at the console of browser.

Modified script:

Please modify HTML and Google Apps Script on your script editor as follows.

HTML & Javascript: Index.html
<script>
  window.onload = google.script.run.withSuccessHandler((e) => {console.log("Done: " + e)}).setUp();
</script>
Google Apps Script: Code.gs
function setUp() {
//    dateHelper_();
  return "ok"; // In this modification, as a sample, "ok" is returned.
}

Note:

  • Although I'm not sure about your whole situation, HTML can be opened by a dialog, sidebar and Web Apps.

Reference:

If I misunderstood your question and this was not the result you want, I apologize.

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • Thanks! That was helpful. Is it true that we can't modify the document in Code.gs? It seems like I was getting an error because of that. I had to move that function to a script tag in Index.html file. – Student May 26 '19 at 19:33
  • @Student Thank you for replying. I'm glad your issue was resolved. – Tanaike May 26 '19 at 22:12