Addressing namespace and library methods from google.script.run

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 );


You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.





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





Comments