Google Apps Script – a new day – a new feature

GAS just keeps getting better. I was thinking the other day about how I might be able to embed sample Google Apps Script code in Google Sites, or other web sites in the way that you can embed Gist samples from github.

I searched around and couldn’t find anything suitable, so I posted a question on stackoverflow. Corey Goldfeder posted the answer, referring to a new (I think undocumented) method of the ScriptApp Class which can get the source code of your script file.

Along with the content service then, you can now get a jSon encoded version of the script of any module. Here’s an example from my mcpher utility library.

function doGet(e) {
       return ContentService
            .createTextOutput(JSON.stringify(mcpher.getMySource ( e )))
            .setMimeType(ContentService.MimeType.JSON); ;    
}

The code in the mcpher library that reacts to this is

/**
 * Returns a modules source code
 * @param {parameters} e the argument to doGet(e). should have module parameter specified
 * @param {scriptappinstance} sap an instance of scriptapp
 * @return {object} The result.
 */
function getMySource(e) {
  var results = {error : "missing module parameter"};
  if (e.hasOwnProperty("parameter")) {
    if (e.parameter.module) {
      try {
        var results =
        { code :
          { module : e.parameter.module, code : ScriptApp.getResource(e.parameter.module).getDataAsString() }
        };
      }
      catch (err) {
        var results = { error : "could not open module " + e.parameter.module} ;
      }
    }
  }
  return results;
}

function testGetSource() {
  Logger.log( getMySource (  {parameter: { module: "cRest" }}));
}

The Url to the public code (shown here asking for the code of module getMySource) is

https://script.google.com/a/macros/mcpher.com/s/AKfycbx4gQTsHjYRSXNDZulP-OhUq8b1NzBtgIRT35ZMBJBURMjf-B8/exec?module=getMySource

Try it and see. So now you can get the source of any module, by creating a doGet() as above, and copying in the getMySource code.

I’ll implement this for google sites and elsewhere, and post here later with the results. No more maintaining source code as a Gist as well as Apps Script!

About brucemcp 225 Articles
I am a Google Developer Expert and decided to investigate Google Apps Script in my spare time. The more I investigated the more content I created so this site is extremely rich. Now, in 2019, a lot of things have disappeared or don’t work anymore due to Google having retired some stuff. I am however leaving things as is and where I came across some deprecated stuff, I have indicated it. I decided to write a book about it and to also create videos to teach developers who want to learn Google Apps Script. If you find the material contained in this site useful, you can support me by buying my books and or videos.