Executing Google Apps Script Code directly in javascript – GAS as a CDN

As you know the language of Google Apps Script is javaScript. So you probably have a lot of useful code buried away there, that could be used in web apps. One solution is to copy it to your web site. Another would be to access it directly from Google Apps Script using the Content service with the recently implemented javascript content type.

Before we start, although I do use Google Cache services this is probably going to be slower than just copying the source everywhere, but accessing it directly from GAS at least means the code will be in sync.

Publishing the code

In Publishing with Google Apps Script I showed how to publish prettified versions of your code (not just from GAS but also from web sites, Github and so on) using the GAS html service and the content service. Taking that one step further, here’s how to include scripts directly from GAS in your javaScript apps.

Example

In this example, I’m going to expose all the modules used in Google Apps Script VBA equivalents and in Color Matching in GAS to be able to be used and executed in a javaScript app. 

The code

http://xliberation.com/p/gaspubcontainer.html?source=web&module=xliberation.com/p/testgascdn.html

How does it work?

The GAS scripts in the modules [“vEquivalents”,“hacks”,“usefulColors”from the  mcpher shared library  are returned to the jQuery $.getScript() using the GAS publisher, with a MIME type of javaScript. Then we can simply execute the code that’s in those modules (assuming they are not using any GAS specific classes).

The test compareColors(VBCOLORS.vbBlack, VBCOLORS.vbWhite) uses functions from each of the 3 loaded modules and executes perfectly.

Using a script tag

You’ll notice that I’m loading the modules dynamically. This is not essential (you can use a regular script tag if you want), but like this you can go and do some other things whilst the scripts are loading asynchronously.

Here’s the rather unpleasant script tag for loading the hacks module, for example.

<script src=
“https://script.google.com/macros/s/AKfycbzhzIDmgY9BNeBu87puxMVUlMkJ4UkD_Yvjdt5MhOxR1R6RG88/exec?source=script&type=javascript&module=hacks&library=mcpher”>
</script>

For more stuff like this, see from VBA to Google Apps Script, and for more detail on this post see Serving up javaScript from GAS
http://xliberation.com/b/but.html

(function() { var po = document.createElement(‘script’); po.type = ‘text/javascript’; po.async = true; po.src = ‘https://apis.google.com/js/plusone.js’; var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(po, s); })();

Author: bm082975

Leave a Reply

Your email address will not be published. Required fields are marked *