How to Call Google Apps Script from Web Page

Look into using the GET parameters. https://stackoverflow.com/a/14736926/2048063.

Here’s a previous question on the topic.

You can access the parameters passed by GET in your doGet(e) function using e.parameter. If you call http://script.google......./exec?method=doSomething, then

function doGet(e) {
  Logger.log(e.parameter.method);
}

doSomething will be written to the log, in this case.

Returning data from the script can be done using the ContentService, which allows you to serve JSON (I recommend). JSON is easiest (in my opinion) to make on the GAS end, as well as use on the client end.

The initial “populate list” call would look something like this. I will write it in jQuery because I feel that is very clean.

var SCRIPT_URL = "http://script.google.com/[....PUT YOUR SCRIPT URL HERE....]/exec";
$(document).ready(function() {
    $.getJSON(SCRIPT_URL+"?callback=?",
              {method:"populate_list"},
              function (data) { 
                alert(JSON.stringify(data)); 
              });
});

And the corresponding GAS that produces this.

function doGet(e) {
  if (e.parameter.method=="populate_list") {
    var v = {cat:true,dog:false,meow:[1,2,3,4,5,6,4]}; //could be any value that you want to return
    return ContentService.createTextOutput(e.parameter.callback + "(" + JSON.stringify(v) + ")")
        .setMimeType(ContentService.MimeType.JAVASCRIPT);
  }
}

This method is called JSONP, and it is supported by jQuery. jQuery recognizes it when you put the ?callback=? after your URL. It wraps your output in a callback function, which allows that function to be run on your site with the data as an argument. In this case, the callback function is the one defined in the line that reads function (data) {.

Leave a Comment