【问题标题】:Console Status Update Text Messages控制台状态更新文本消息
【发布时间】:2022-01-06 04:20:11
【问题描述】:

我有一个有效的 Google Apps 脚本,它在最后显示一个网络应用程序输出。

脚本持续约 20 秒, 我希望改善用户体验, 在此期间间歇性地更新脚本状态。

我了解异步服务器/客户端操作的挑战, 但令我惊讶的是,这种“微不足道”的功能似乎很难实现。

我回顾了类似的主题,但错过了一个很好的例子。

代码示例:

function doGet(e){
  output = function1();
  output = function2();
  return HtmlService.createHtmlOutput(output).
}

function function1() {
 //DoSomething
 return = "output1";
}

function function2() {
 //DoSomething
 return = "output2";
}

我不想用 HTML 调用替换函数调用。 但是如果可行的话,可能会不断地轮询一个全局变量,直到脚本执行完成?

也许是为了让它更具体,

code.gs:

var data = "test";
Logger.log(data);

function doGet(){
  return HtmlService.createHtmlOutputFromFile('index');
}

function main() {
  data = "1";
  pushMSG(data);
  Logger.log(data);
  Utilities.sleep(2000);

  data = "2";
  pushMSG(data);
  Logger.log(data);
  Utilities.sleep(2000);

  data = "3";
  pushMSG(data);
  Logger.log(data);
  Utilities.sleep(2000);

  data = "4";
  pushMSG(data);
  Logger.log(data);
  Utilities.sleep(2000);

  data = "5";
  pushMSG(data);
  Logger.log(data);
  Utilities.sleep(2000);
}

function pushMSG(str){
  return str
}

index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>

  <body>
    <div id="output">Script Started ...</div>
   
    <script>
      google.script.run.main();

      var i = 0;
      var refreshId = setInterval( function () { 
        document.getElementById('output').innerHTML = data;
        google.script.run.withSuccessHandler(onSuccess).pushMSG();
        i = i + 1;
        if (i > 10) {
          clearInterval(refreshId);
          document.getElementById('output').innerHTML = "done1";
        }
      }, 500);

      function onSuccess(pushMSG) {
        document.getElementById('output').innerHTML = data;
      }

      document.getElementById('output').innerHTML = "done2";
    </script>
  </body>
</html>

但我无论如何都找不到显示有效的data 变量...

【问题讨论】:

  • 我必须为我糟糕的英语水平道歉。不幸的是,我无法理解您的脚本和I'm not looking to replace the function calls by HTML calls.。在您的脚本中,将返回 HTML 数据。在您的目标中,您希望在不使用return HtmlService.createHtmlOutput(output) 的情况下实现您的目标。我的理解正确吗?顺便说一句,在您的脚本中,我认为需要删除.return HtmlService.createHtmlOutput(output).
  • 'm not looking to replace the function calls by HTML calls 这是最好的办法。
  • ...可能是唯一的方法。
  • 也许我忽略了一些东西,但我不完全理解为什么它必须如此困难。 :) 理想情况下,它使用 hmtl 页面来输出脚本状态消息。
  • html 页面致电maingoogle.script.run.withSuccessHandler((e)=&gt;alert('completed'+e)).main(1)

标签: google-apps-script web-applications


【解决方案1】:

我找到了答案,

  1. 在 .gs 中创建缓存服务
  2. 在多个 .gs 函数中更新缓存键
  3. 使用 setInterval() 从 hmtl 轮询缓存键更新

我被这篇维护良好且有趣的博客文章所触发: https://ramblings.mcpher.com/gassnippets2/implementing-a-client-side-progress-bar-reporting-on-server-side-work-for-htmlservice/

最好的问候, 克里斯托夫

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-27
    • 2010-09-27
    • 2015-07-03
    • 1970-01-01
    • 2020-03-19
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多