If you are doing anything with HTMLService you have to duplicate a fair amount of stuff, usually by copying them from previous projects. Not only html and css, but also useful code that you’ve built up over time. Quite recently, Clasp was introduced to Apps Script to allow you to better use github and workflow tools to make all this a little less laborious. However, if you want to continue to use the vanilla IDE there’s a way to do that too. In all most of my projects that use HTMLService, I use a certain number of code concepts repeatedly – specifically

  • standard css for spinners and layouts
  • material design (muicss)
  • various DOM related utilities
  • promisified version of google.script.run that works with namespaced methods
  • sharing the same JS code between server and client
  • Property services
  • A JSON editor (I’m using https://github.com/josdejong/jsoneditor)
  • Standardized error reporting and notification
  • A modular “Include” method
  • Passing  arguments from server to client on htmlservice startup

All in all this amounts to a fair amount of setup before you can even get started. However it is possible to build a library of stock code that you can simply include in all your projects. Here’s how. 

The example

 The UI looks like this 

 

This complete app is not public – it uses a library to do the server side part of the work and I won’t be discussing that here. However the container bound part is generic and I’ll use it to illustrate how you can use a stock html library to simplify and standardize your apps script work – everything fits together like this

 

 

Here’s the key, and it’s also on github

1hOH5hCIZSk_PIUKNz_b87HaqsRiH2Im1GeflAf5P814RML1kQjNzkyJ_

 

How does it work?

Both the cStockClient library and the orchestration app contain the Include namespace, which looks like this, so when building your orchestration app, first create a file called Include containing this, and include a library reference to the cStockClient library (or your version of it).

function getLibraryNamespace (library) {
  return this[library];
}
/**
* used to expose memebers of a namespace
* @param {string} namespace name
* @param {method} method name
*/
function exposeRun(namespace, method, argArray) {
  var func = namespace ? this[namespace][method] : this[method];
  if (argArray && argArray.length) {
    return func.apply(this, argArray);
  } else {
    return func();
  }
}
/**
 *used to include code in htmloutput
 *@nameSpace Include
 */
var Include = (function (ns) {
  /**
  * given an array of .gs file names, it will get the source and return them concatenated for insertion into htmlservice
  * like this you can share the same code between client and server side, and use the Apps Script IDE to manage your js code
  * @param {string[]} scripts the names of all the scripts needed
  * @param {string} [library=""] from a shared library (which has include installed) 
  * @return {string} the code inside script tags
  */
  ns.gs =  function (scripts,library) {
    return library ? 
      getLibraryNamespace(library).Include.gs (scripts) :
      'n';
  };
  /**
  * given an array of .html file names, it will get the source and return them concatenated for insertion into htmlservice
  * @param {string[]} scripts the names of all the scripts needed
  * @param {string} [ext] an extension like js if required
  * @return {string} the code inside script tags
  */
  ns.htmlGen = function (scripts, ext,  library) {
    return library ? 
      getLibraryNamespace(library).Include.html (scripts) :
      scripts.map (function (d) {
        return HtmlService.createHtmlOutputFromFile(d+(ext||'')).getContent();
      })
      .join('nn');
  };
  /**
  * given an array of .html file names, it will get the source and return them concatenated for insertion into htmlservice
  * inserts html style
  * @param {string[]} scripts the names of all the scripts needed
  * @return {string} the code inside script tags
  */
  ns.html = function (scripts,library) {
    return ns.htmlGen (scripts , '' , library);
  };
  /**
  * given an array of .html file names, it will get the source and return them concatenated for insertion into htmlservice
  * inserts css style
  * @param {string[]} scripts the names of all the scripts needed
  * @return {string} the code inside script tags
  */
  ns.js = function (scripts,library) {
    return library ? 
      getLibraryNamespace(library).Include.js (scripts) :
      'n';
  };
  /**
  * given an array of .html file names, it will get the source and return them concatenated for insertion into htmlservice
  * like this you can share the same code between client and server side, and use the Apps Script IDE to manage your js code
  * @param {string[]} scripts the names of all the scripts needed
  * @return {string} the code inside script tags
  */
  ns.css = function (scripts,library) {
    return library ? 
      getLibraryNamespace(library).Include.css (scripts) :
      '<style>n' + ns.htmlGen(scripts,'.css') + '</style>n';
  };
  /**
   * append args to be poked into the resolved template
   * @param {object} args
   * @return {string}
   */
  ns.staticArgs = function (args) {
    if (!args.namespace) throw 'Specify a namespace to contain static args';
    return '';
  };
  return ns;
})(Include || {});

The final orchestrating app looks like this, and we’ll go into each file in this article. You can ignore the Code.js file. I keep that around for unit testing.

 


 

index.html

This defines the structure of the Client side App, and uses the Include namespace to pick up code from both the stock library and itself. Here’s what mine looks like. The idea is to keep this as clean as possible, picking up the code, html and css from either the local project or from the library. 

<!DOCTYPE html>
<html>
  <head>
  <base target="_top">
    <?!= Include.html(&#91;'cdn.css'&#93;,'cStockClient'); ?>
    <?!= Include.css(&#91;'spinner','app'&#93;,'cStockClient'); ?>  
  </head>
  <body>
    <?!= Include.html(&#91;'cdn','jseditcdn','jseditcdn.css'&#93;,'cStockClient'); ?>  
    <?!= Include.html(&#91;'appmarkup'&#93;); ?>  
    <?!= Include.html(&#91;'spinner','app'&#93;,'cStockClient'); ?>  
    <?!= Include.js(&#91;'main'&#93;); ?>
    <?!= Include.gs(&#91;'JSEdit','App','DomUtils','Provoke'&#93;,'cStockClient'); ?>
    <?!= Include.gs(&#91; 'Client','Home'&#93;); ?>
  </body>
</html>

Include.html (arrayOfFilenames [,libraryName])

This includes code from each of the html type file names mentioned. If a library name is given it will look there (it uses the copy of the Include namespace in the library to do that). 

Include.css (arrayOfFilenames [,libraryName])

Gets any css definitions included in the html type file names given. There’s not need for them to container <style> tags as this gets inserted automatically. 

Include.gs (arrayOfFilenames [,libraryName])

The idea here is that regular script files can be used client side (and server side too if appropriate). This allows sharing of the same code between client and server. 

Include.js (arrayOfFilenames [,libraryName])

Whereas almost all of my client code is written as regular .gs files, if you want to use syntax unsupported by the Apps Script editor, you’ll need to write them as html type files. This pulls those in. There’s no need for script tags, as they’ll be added automatically. 

Addon.gs

This script file contains the usual stuff for kicking off HtmlService, but also has a pattern for getting variable data into the htmlservice build using Include.staticArgs().

function doCollection() {
  // get the sheet
  var name = SpreadsheetApp.getActiveSheet().getName();
  if (!VimeoCommon.Intro['doCollection' + name]) throw 'Dont know how to get collections on this sheet';
  return showDialog ();
}
/**
* Opens a dialog. 
*/
function showDialog() {
  var sheetName = SpreadsheetApp.getActiveSheet().getName();
  var static = Include.staticArgs ( {
    namespace:'AppsScriptStatic',
    params: {
      sheetName:sheetName,
      execute: {
        namespace:'Server',
        method:'exec',
        args:[sheetName]
      }
    }
  });
  var ui = HtmlService.createTemplateFromFile('index.html')
  .evaluate()
  .append(static)
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setWidth(400)
  .setHeight(580)
  .addMetaTag('viewport', 'width=device-width, initial-scale=1');
  SpreadsheetApp.getUi().showModelessDialog(ui, 'Collection parameters for '+sheetName);
}

Notice that the variable static is filled with some stuff you’d like to build into the htmlservice script. Include.staticArgs() generates some code to create a client side namespace (in this case called ‘AppsScriptStatic’), with various properties that’ll be of some use later. In this case, I’m passing the sheet name, along with the name of a server side namespace and method the client will want to execute later. You can of course put any (stringifable) thing you want here. Just make sure the namespace is specified.  

main.js.html

This is main code to be executed when the client side dom is constructed. This should be as clean as possible, and because it contains reference to window (which doesn’t exist server side), it’s written it as a js.html file , rather than a .gs script.

.

window.onload = function() {
  // set up client app structure
  App.initialize();
  Home.init();
  // get the ui going
  Client.init(AppsScriptStatic);
};

Notice that it references the AppsScriptStatic namespace – which doesn’t exist in any code you’ve written. It got created during the Include.staticArgs() phase. This is how variables from the server ended up getting embedded in the client side script. 

appmarkup.html

This is the html for the app. Most of the markup, (and all of the css comes from the stock library), so this can be pretty minimal too.

<legend>GraphQL collection parameters</legend>
      <input id="textmax" type="text" value="">
      <label>Maximum rows to return</label>
      <label>GraphQL variables</label>
        <button id="start-button">Execute</button>
        <button id="close-button">Cancel</button>

Server.gs

Would typically contain the server side code. In my case, it’s minimal because I’m using another library to do the server side work. The property store stuff is defined in the stock library so all that’s required are some hooks, and to set up this script’s property service.

var Server = (function (ns) {
  ns.initProp = function () {
    // set up propertystore
    return cStockClient.PropertyStores.init (PropertiesService);
  };
  ns.getProp = function (store , key) { 
    return ns.initProp().get(store, key);
  };
  ns.setProp = function (store , key, ob) { 
    return ns.initProp().set(store, key,ob);
  };
  ns.exec  = function (name, params) {
    return VimeoCommon.Intro['doCollection' + name](params);
  };
  return ns;
}) ({});

Home.gs

I generally use this namespace to handle Dom events and validation.  This one is rather lengthy as it also contains the JSONschema definition describing the valid input for the JSON editor dialog. An execute button push starts off the Client dialog, which will in turn initiate the Server side code.

/**
* sets up all listeners
* @constructor Home
*/
var Home = (function (ns) {
  'use strict';
  var el;
  ns.close = function () {
    return google.script.host.close();
  };
  // The initialize function must be run to activate elements
  ns.init = function (reason) {
    el = DomUtils.elem;
    el("close-button")
    .addEventListener ('click', function (e) {
       ns.close();
    });
    // start generating
    el("start-button")
    .addEventListener ('click', function (e) {
      var buttons = ["start-button","close-button"];
      App.spinCursor();
      DomUtils.disable (buttons);
      Client.start ()
      ['finally'] (function () {
        App.resetCursor();
        DomUtils.enable (buttons);
      });
    });
    el("textmax")
    .addEventListener ('change', function (e) {
      App.hideNotification();
      ns.parseTextMax();
    });
    // these are the standard parameters allowed for a collection (minus distinct and countRows which are inappropriate for this use case)
    var schema = {
      "title": "Collection Schema",
      "type": "object",
      "properties": {
        "limit": {
          "type": "integer"
        },
        "offset": {
          "type": "integer"
        },
        "valueKey": {
          "type": "string"
        },
        "value": {
          "anyOf": [
            { "type": "string" }, 
            { "type": "integer" },
            { "type":"array" }
          ]
        },
        "op": {
          "type": "string"
        },
        "sortFields": {
          "type": "string",
        },
        "sortOrder": {
          "type": "string",
          "enum": ["ASC", "DESC"]
        },
        "filters": {
          "type": "array",
          "properties": {
            "valueKey": {
              "type": "string"
            },
            "value": {
              "anyOf": [
                { "type": "string" }, 
                { "type": "integer" },
                { "type":"array" }
              ]
            }
          }
        }
      }
    };
    JSEdit.init(('jsoneditor'), {
      schema:schema,
      mode:"text"
    });
  };
  // Load text from properties into form
  ns.adaptTextArea = function (vars) {
    el("textmax").value = vars && vars.max ? vars.max : "";
    // this fixes the floating label
    if (el("textmax").value) el("textmax").dispatchEvent(new Event('change'));
    JSEdit.set ( (vars && vars.params) || {});
  };
  // get the params from the form and validate them
  ns.getTextArea = function () {
    return ns.parseTextArea();
  };
  // check max is a number
  ns.parseTextMax = function () {
    var max = el("textmax").value ?  parseInt ( el("textmax").value, 10)  : "";
    if (isNaN (max) ) {      
      App.showNotification ("Invalid number", "max needs to be a number");
      return null;
    }
    return max;
  };
  // check the contents of jsoneditor is good
  ns.parseTextVars = function () {
    try {
      var params = JSEdit.get();
      return params;
    }
    catch (err) {
      App.showNotification ("Invalid JSON", "Graphql vars needs to be valid JSON");
      return null;
    }
  };
  // get the max ans json
  ns.parseTextArea = function () {
    var params = ns.parseTextVars();
    if (!params) return null;
    var max = ns.parseTextMax();
    if (max === null ) return null;    
    return {
      params: params, 
      max: max
    };
  };
  return ns;
})(Home || {});

Client.gs

Finally, the main client code.

var Client = (function (ns) {
  /**
   * make sure that we received static parameters
   */
  ns.checkParams = function () {
    const params = ns.static && ns.static.params;
    const exec = params && params.execute;
    if (!params ||  !params.sheetName || !exec || !exec.namespace || !exec.method || !exec.args) {
      App.showNotification ('Static params invalid', JSON.stringify(ns.static || ""));
      return false;
    }
    return true;
  }
  /**
   * store the static parans for later
   */
  ns.init = function (static) {
    ns.static = static;
    if (ns.checkParams()) {
      // set the jsoneditor root name
      // load the default values from last time
      ns.getVars (ns.static.params.sheetName);
      return ns;
    }
    return null;
  };
  /**
   * start up the client
   */
  ns.start = function () {
    if (ns.checkParams()) {
      //store the latest params
      var params = Home.getTextArea ();
      if (params) {
        // set params to property - wait..
        var sv = ns.setVars(ns.static.params.sheetName, params);
        // get ready to run
        var exec = ns.static.params.execute;
        var runArgs = [exec.namespace,exec.method];
        Array.prototype.push.apply (runArgs , exec.args);
        Array.prototype.push.apply (runArgs , [params]);
        // make sure props are save and go
        return Promise.all ( [sv,Provoke.run.apply (this,runArgs)])
          .then (function (results) {
            Home.close();
          })
          ['catch'](function (err) {
            App.showNotification ("Execution failed" , err);
            console.log ('failed provoke', err, JSON.stringify(runArgs));
          });
      }
    }
    else {
      return Promise.reject ("missing args");
    }
  };
  /**
   * make a standard property key
   */
  ns.makeKey = function (key) {
    return 'fidvars_' + key;
  };
  /**
   * get the vars fron the property store
   */
  ns.getVars = function (key) {
    App.spinCursor();
    return Provoke.run ("Server", "getProp" , "script" , ns.makeKey(key))
    .then (function (vars) {
      Home.adaptTextArea (vars);
      App.resetCursor();
    })
    ['catch'](function (err) {
      App.showNotification  ("Error getting property", err); 
      console.log ('error getting var', key);
    })
  };
  /**
   * store the vars in the property store
   */
  ns.setVars = function (key, ob) {
    return Provoke.run ("Server", "setProp" , "script",  ns.makeKey(key), ob)
    .then (function (vars) {
      return vars;
    })
    ['catch'](function (err) {
      App.showNotification  ("Error getting property", err); 
      console.log ('error setting var', key);
    });
  };
  return ns;
}) ({});

The main points of interest here are the use of the Provoke namespace (from the stock library) to run a promisified version of google.script.run and the use of the static variables passed over when the htmlservice was initially created. 

Summary

 Most of the laborious stuff in setting up a client side app using HtmlService can be done once off and re-used. If you find something useful, stick it in your stock library and use Include to use it over and over again. 

For more like this see Google Apps Scripts Snippets
Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.