Skip to content Skip to sidebar Skip to footer

Call Library Function From Html With Google.script.run

I implement library with Google App Script and I have some difficulties to call a function from library using google.script.run. Here is the code of my Library : Code.gs function

Solution 1:

It seems that google.script.run can't look inside Objects or self-executing anonymous functions. In my case, putting any code inside an object or IIFE resulted in "is not a function" type of error being thrown in the console.

You can work around this by declaring a single function that will call nested methods inside libraries and objects.

.GS file

 function callLibraryFunction(func, args){

    var arr = func.split(".");

    var libName = arr[0];
    var libFunc = arr[1];

    args = args || [];

   returnthis[libName][libFunc].apply(this, args);

}

In JavaScript, every object behaves like an associative array of key-value pairs, including the global object that 'this' would be pointing to in this scenario. Although both 'libName' and 'libFunc' are of String type, we can still reference them inside the global object by using the above syntax. apply() simply calls the function on 'this', making the result available in global scope.

Here's how you call the library function from the client:

 google.script.run.callLibraryFunction("Library.libraryFunction", [5, 3]);

I don't claim this solution as my own - this is something I saw at Bruce McPherson's website a while back. You could come up with other ad-hoc solutions that may be more appropriate for your case, but I think this one is the most universal.

Solution 2:

After quite long time working on this, I found out that any function that you call from the library using google.script.run must exist in both the main script and the library script. The function must at least be declared in the main script while the implementation as well as the parameters are not important. The implementation will be in your library. If the main script does not include the name of the function, the error <your function> is not a function will appear.

Now that there is no meaning of having a library if every single function needs to exist in the main function, the solution provided by @Anton Dementiev would be used as a workaround. Suppose you have a function named testFunc in your library, you can call it using the following method:

google.script.run.callLibraryFunction("testFunc", [5, 3]);

where the library has this function:

function callLibraryFunction(func, args) {
  args = args || [];
  returnthis[func].apply(this, args);
}

and the main script has this declaration:

function callLibraryFunctdion() {

}

Google must fix this stupid behaviour

Post a Comment for "Call Library Function From Html With Google.script.run"