【问题标题】:Run a Google apps script automatically upon loading a Google Site?加载 Google 站点时自动运行 Google 应用程序脚本?
【发布时间】:2015-12-09 21:41:10
【问题描述】:

我编写了一个应用程序脚本,它采用电子表格并将其转换为 Google 表单。我想在我的谷歌网站上显示表格;但是,我希望表单在每次打开网站时自动刷新,这样如果电子表格发生更改,表单也会在显示时更新。本质上,我希望脚本在打开 Google 网站时自动运行——知道如何执行此操作吗?

另外,作为旁注(不那么重要),有没有办法将脚本合并到谷歌网站而不将其显示为小工具?我不想显示脚本,我只想让它在后台运行。

【问题讨论】:

    标签: google-apps-script google-sheets google-forms google-sites


    【解决方案1】:

    您可以在网站加载时间接运行应用程序脚本功能,方法是使用 HTML 服务创建一个独立的 Web 应用程序,发布它,并将window.onload 放入脚本标签中:

    <script>
      window.onload = function() {
        console.log('Onload ran. ');
    
      };
    </script>
    

    然后您将使用google.script.run 来运行服务器功能:

    <script>
      window.onload = function() {
        console.log('hah! it ran. ');
        google.script.run
          .withSuccessHandler(run_This_On_Success)
          .gsServerFunction();
      };
    
     window.run_This_On_Success = function(the_Return) {
       console.log('was successful!: ' + the_Return);
     };
    

    代码.gs

    function doGet() {
      return HtmlService.createHtmlOutputFromFile('index')
                .setSandboxMode(HtmlService.SandboxMode.IFRAME);
    };
    
    function gsServerFunction() {
      return true;
    };
    

    index.html

    <!DOCTYPE html>
    <html>
      <head>
        <base target="_top">
      </head>
      <body>
        This is the body
    
    
        <script>
          window.onload = function() {
            console.log('hah! it ran. ');
            google.script.run
              .withSuccessHandler(wuzSugzezvul)
              .gsServerFunction();
           };
    
           window.wuzSugzezvul = function() {
             console.log('was successful!');
           };
        </script>
      </body>
    </html>
    

    然后你可以去掉apps script gadget的边框和标题,让它变得非常小,并且不要放入任何文本显示在HTML中。

    【讨论】:

    • 谢谢——我认为这是有道理的。但是,我收到错误消息,“找不到名为 index 的 HTML 文件。(第 7 行,文件“代码”...)”——我需要将 index.html 添加为自定义 HTML 框,还是我需要添加有什么问题吗?
    • index.html 文件是 Apps 脚本代码编辑器中的一个 HTML 文件,code.gs 文件也是如此。 code.gs 文件是新项目中的默认脚本文件。使用这种策略,您根本不需要使用 HTML 框。您创建一个新的 Apps 脚本,然后将其添加到 Apps 脚本小工具中。
    • 这就是我所做的——我创建了一个新的 Apps 脚本项目,其中包含我的 Code.gs 和我的 index.html 文件,然后我将它发布为一个网络应用程序,并将一个 Apps 脚本小工具添加到我的将 Web 应用程序的 URL 粘贴为脚本的站点,但它仍然告诉我它找不到 index.html 文件
    • 不要在代码中加入“.html”。只需使用名称。 createHtmlOutputFromFile('index') 假定扩展名。这是我能想到的唯一导致问题的另一件事。
    • 尝试通过单击代码编辑器中的“运行”按钮手动运行doGet() 代码。您可能需要批准一些权限。另外,您是否将脚本发布为 Web 应用程序?发布 -> 部署为 Web 应用
    猜你喜欢
    • 1970-01-01
    • 2014-03-26
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多