Web App Development with Google Apps Script/Hello world

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Create a new script[edit | edit source]

You can create a new Google Apps Script the same way you'd create a new Google Doc or Google Sheet: Using the "New" button scroll down to "Google Apps Script" under "more". That will open a new script window with a simple test function in it:

function myFunction() {

}

If you write some code in that function you can run the function with the buttons at the top. Typically to see any results you'd have to use Logger.log(some variable here).

If you put javascript code outside of a function it will also execute whenever you run any of the functions. Keep that in mind as we develop web apps. Anything outside of a function will run every time the page is accessed or you run a server function with an ajax call.

Set up doGet()[edit | edit source]

To actually have a web app you have to do two things:

  1. Make sure you have a doGet() function in your script, and
  2. Publish your site

Almost always you're going to want to write your html in a separate file (still housed in the overall script google entity) and then have the doGet() function call it and return it. Assuming you've created an html file called "main.html" you would call it like this:

function doGet(){
   var t=HtmlService.createTemplateFromFile("main"); // note that you don't have to put the ".html"
   return t.evaluate();
   }

You would then access the page by going under to the "Publish->Deploy As Web App..." menu item. Once it's published you can access the url from that same menu item.