Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用google.script.run从html调用库函数_Javascript_Html_Google Apps Script - Fatal编程技术网

Javascript 使用google.script.run从html调用库函数

Javascript 使用google.script.run从html调用库函数,javascript,html,google-apps-script,Javascript,Html,Google Apps Script,我使用Google应用程序脚本实现库,使用Google.Script.run从库中调用函数时遇到一些困难 以下是我的库的代码: 代码.gs function ShowSideBar() { var html = HtmlService.createTemplateFromFile('Index_librairie').evaluate() .setTitle('Console de gestion') .setWidth(300); Spreads

我使用Google应用程序脚本实现库,使用Google.Script.run从库中调用函数时遇到一些困难

以下是我的库的代码:

代码.gs

function ShowSideBar() {
    var html = HtmlService.createTemplateFromFile('Index_librairie').evaluate()
        .setTitle('Console de gestion')
        .setWidth(300);
    SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
        .showSidebar(html);
}

function execution_appeler_par_html(){
  Logger.log("execution_appeler_par_html"); 

}
Index_librarie.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
    google.script.run.withSuccessHandler(work_off).execution_appeler_par_html(); 
    function work_off(e){
    alert(e);
    }
    </script>
  </head>
  <body>
    test de ouf
  </body>
</html>
Google.script.run不会重新确认执行\u appeler\u par\u html()函数。
我应该使用libraryname.execution\u appeler\u par\u html(),但这个语法在google.script.run的配置中不起作用似乎google.script.run无法查看对象内部或自动执行的匿名函数。在我的例子中,将任何代码放入对象或IIFE中会导致控制台中抛出“不是函数”类型的错误

您可以通过声明一个函数来解决这个问题,该函数将调用库和对象中的嵌套方法

.GS文件

 function callLibraryFunction(func, args){

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

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

    args = args || [];

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

}
在JavaScript中,每个对象的行为都类似于键值对的关联数组,包括“this”在此场景中指向的全局对象。尽管'libName'和'libFunc'都是字符串类型,但我们仍然可以使用上述语法在全局对象中引用它们。apply()只调用“this”上的函数,使结果在全局范围内可用

以下是如何从客户端调用库函数:

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

我并不声称这个解决方案是我自己的——这是我不久前在Bruce McPherson的网站上看到的。你可以想出其他特别的解决方案,可能更适合你的情况,但我认为这是最普遍的

您是否厌倦了一个伪函数,它依次调用
lbrairietestedouard.execution\u appeler\u par\u html()
。例如:
函数dummy(){lbrairietestedouard.execution\u appeler\u par\u html()}
在html端调用google.script.run.dummy()
 google.script.run.callLibraryFunction("Library.libraryFunction", [5, 3]);