【问题标题】:Call Library function from html with google.script.run使用 google.script.run 从 html 调用库函数
【发布时间】:2018-02-22 13:42:05
【问题描述】:

我使用 Google App Script 实现库,但在使用 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_librairie.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>

这是我使用图书馆的电子表格: 代码.gs

function onopen() {
  lbrairietestedouard.ShowSideBar();
}

Google.script.run 不重新编译 execution_appeler_par_html() 函数。 我应该使用 libraryname.execution_appeler_par_html() 但这种语法在 google.script.run 的配置中不起作用

【问题讨论】:

  • 你是否厌倦了一个虚拟函数,它又调用lbrairietestedouard.execution_appeler_par_html()。例如:function dummy(){ lbrairietestedouard.execution_appeler_par_html() } 在您的 HTML 端只是 call google.script.run.dummy()

标签: javascript html google-apps-script


【解决方案1】:

似乎 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' 都是 String 类型,但我们仍然可以使用上述语法在全局对象中引用它们。 apply() 简单地调用 'this' 上的函数,使结果在全局范围内可用。

从客户端调用库函数的方法如下:

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

我没有声称这个解决方案是我自己的 - 这是我不久前在 Bruce McPherson 的网站上看到的。您可以提出其他可能更适合您的情况的临时解决方案,但我认为这是最通用的。

【讨论】:

    【解决方案2】:

    经过很长时间的研究,我发现您使用 google.script.run 从库中调用的任何函数都必须存在于主脚本和库脚本中。该函数必须至少在主脚本中声明,而实现和参数并不重要。实现将在您的库中。如果主脚本不包含函数名,则会出现错误&lt;your function&gt; is not a function

    现在,如果每个单独的函数都需要存在于主函数中,那么拥有库没有任何意义,@Anton Dementiev 提供的解决方案将用作解决方法。假设您的库中有一个名为 testFunc 的函数,您可以使用以下方法调用它:

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

    图书馆有这个功能的地方:

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

    主脚本有这个声明:

    function callLibraryFunctdion() {
    
    }
    

    Google 必须纠正这种愚蠢的行为

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多