It’s quite irritating that you can only access functions that are global from the client side when running Html service. Except there is a way round it using regular JavaScript.

Let’s say you have a namespace like this and you want to call some of its methods.

var Abc = {
    doSomething:function (arg1,arg2) {
       return something;
    } ,
    doSomethingElse:function (arg) {
       return something;
    } 
};

If you wanted to call Abc.doSomething(a,b)  from google.script.run, you’d have to first create a global version of the function. You can’t even do this

// this doesn't even work
var doSomething = Abc.doSomething

google.script.run doesn’t recognize doSomething as a function, so this only works if doSomething is defined as a global function like this.

function doSomething (arg1,arg2) {
    return Abc.doSomething (arg1,arg2);
}

to allow you to be able to call it like this.

google.script.run.doSomething(a,b);

Can we get round it?

Yes we can!

function exposeAbc(method) {
  return Abc[method].apply(this,Array.prototype.slice.call(arguments,1));
}

Then you can address any method from google.script.run like this. You can address functions in libraries the same way.

google.script.run.exposeAbc('doSomething', a , b );

You still need to create one global function of course, but you can centralize access to all methods to that one function. You could even pass the namespace or library name to a more general one like this.

function expose (namespace , method) {
   return this[namespace][method]
  .apply(this,Array.prototype.slice.call(arguments,2));
}

Then you can address any method from google.script.run like this. You can address functions in libraries the same way.

google.script.run.expose('Abc','doSomething', a , b );
For more like this, see Google Apps Scripts Snippets

Why not join our community , follow the blog or twitter .