如何通过gmail插件按钮在JS文件中触发功能?

时间:2019-05-28 11:27:07

标签: google-apps-script google-api gsuite google-apps-marketplace gmail-addons

我有js库,该库具有我们应用程序所需的一些内置功能。现在,我想在Gmail插件中导入我的js库及其CSS文件。之后,我想将函数绑定到该按钮ID,以便每当单击按钮时,库中的函数就会执行。

我该怎么做?请查看示例代码

根据示例代码 myLib.js ,具有函数 myFunc(),该函数需要打开组件ID和URL。因此,我创建了按钮并将 myFunc 绑定到该按钮。我如何使用 googlescript for gmail addon 做同样的事情。

预先感谢

   <head>
      <script src="https://*/app.bundle.js"> </script>
      <script src="https://*/app.bundle.css"> </script>
      <script src="https://*/myLib.js"> </script>
   </head>
   <body>
     <button id="app">Clickhere</button>
     <script>
        myFunc('#app',URL);
     </script>
   </body>

1 个答案:

答案 0 :(得分:0)

Gmail附加组件(如果您所说的确实是Gmail附加组件)使用Card-based interface,并且无法使用自定义html和'css'创建。建立了这样的接口后,请创建一个执行您库函数的函数:

/**
 * Triggers library function;
 * @param {Object} e event object;
 */
function myTrigger(e) {
  //access event object's params;
  var parameters = e.parameters; 
  var id  = parameters.id;
  var url = parameters.url;      

  //you can reference lib functions by prepending its name;
  myLibrary.myFunc();
}

通过单击项目的命令栏按钮资源导入您的库,然后选择并导入您的项目(假设您的库可以转换为应用脚本项目,如果没有,您将无能为力。此外,Google discourages from使用附加组件中的库。

您当然可以使用UrlFetchApp.fetch()通过eval()加载外部非GAS库(ctrq的操作方法是great tutorial),但是您可能知道eval()为您的应用带来了security risks

然后,在目标Ui元素(很可能是Action)上配置TextButton

//...created a TextButton and wrote it into a var tb;

//create parameters object (aquire id and url however you want)
var parameters = {
 id  : '', 
 url : '' 
};

//reference Enum loadIndicator (only NONE or SPINNER currently);
var loadIndicator = CardService.LoadIndicator.SPINNER;

//create Action to set;
var action = CardService.newAction();
    action.setFunctionName('myTrigger'); //reference trigger function;
    action.setLoadIndicator(loadIndicator); //set a load indicator, if not invoked equals NONE;
    action.setParameters(parameters) //every key in this object are strings!;

//set Action to TextButton;
tb.setOnClickAction(action);