首页 > 解决方案 > 使用谷歌应用脚​​本构建实时仪表板

问题描述

我希望能够不断(实时)更新我的网络应用程序,这样每当我的 Google 表格上有更新(通过使用应用程序脚本doGet功能配置的网络挂钩)时,我构建的 HTML 仪表板中也会显示相同的内容.

我不需要帮助来设置我的工作表、webhook 或 HTML 仪表板 - 我已经设置了所有这些。

我确实需要有关如何在我的函数或工作表上有更新时如何更新我的 HTML 仪表板(网络应用程序)的帮助/建议doGet(那部分并不重要)。

最好的例子是每次有新用户登陆您的网站时,Google Analytics(分析)实时仪表板的变化方式。

PS。我知道我应该分享一些代码,但我所拥有的一切都与我真正想要的无关;希望这很清楚,但如果你们中的任何人需要查看我的代码/表格,我很乐意创建一个虚拟版本。

标签: google-apps-scriptgoogle-sheetsweb-applications

解决方案


您需要使用:

  • google.script.run.withSuccessHandler这是一个 JavaScript、异步、客户端 API,允许您与服务器端函数进行交互(参考可以在这里找到)。
  • setInterval以您认为合适的频率调用上述客户端 API 的函数
    • 3000/3500 毫秒是我到目前为止一直在使用的,服务配额并没有具体谈论它的限制

服务器端

这几乎是在脚本的code.gs部分中编写的代码;您的所有功能都驻留在哪里,这些功能可能与您的电子表格交互或充当 webhook

客户端

这是从您的*.html文件运行并在加载后在您的 Web 浏览器上运行的代码。这是您可以使用“异步”API 的地方

例子

在我的虚拟设置中,我 -

  1. 从simpsonsquoteapi 中获取随机引用
  2. 显示每秒变化的计时器

Code.gs(服务器端代码)

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('Index').setTitle('Realtime Data');
}

function randomQuotes() {
  var baseURL = 'https://thesimpsonsquoteapi.glitch.me/quotes';
  var quotesData = UrlFetchApp.fetch(baseURL, { muteHttpExceptions: true });
  var quote;
  var imageURL;
  if (quotesData.getResponseCode() == 200 || quotesData.getResponseCode() == 201) {
    var response = quotesData.getContentText();
    var data = JSON.parse(response)[0];
    quote = data["quote"];
    imageURL = data["image"];
  } else {
    quote = 'Random Quote Generator is broken!';
    imageURL = 'https://cdn.shopify.com/s/files/1/1061/1924/products/Sad_Face_Emoji_large.png?v=1480481055';
  }
  var randomQuote = {
    "quote": quote,
    "imageTag": '<img class="responsive-img" src="' + imageURL + '">'
  }
  return randomQuote;
}

function getTime() {
  var now = new Date();
  return now;
}

Index.html(客户端代码)

我只强调代码的相关方面

以下每 10 秒(10000 毫秒)获取随机报价

<script>
    function onSuccess1(quotedata) {
        var quoteactual = document.getElementById('quote');
        quoteactual.innerhtml = quotedata.quote;
        var quoteimg = document.getElementById('quoteImage');
        quoteimg.innerhtml = quotedata.imagetag;
    }

    setInterval(function() {
        console.log("getting quote...")
        google.script.run.withSuccessHandler(onsuccess1).randomQuotes();
    }, 10000);
</script>

这每 1 秒(1000 毫秒)获取时间

<script>
    function onSuccess2(now) {
        var div = document.getElementById('time');
        var today = new Date();
        var time = today.getHours() + " : " + today.getMinutes() + " : " + today.getSeconds();
        div.innerhtml = time;
    }

    setInterval(function() {
        console.log("getting time...")
        google.script.run.withSuccessHandler(onsuccess2).getTime();
    }, 1000);
</script>

您可以访问我的 github 存储库上的整个脚本或从原始脚本复制

输出

这里的图像应该每 10 秒和计时器更改一次,每 1 秒

即时的

浏览器控制台日志可以在这里查看 -

实时控制台

几周前我写了这篇文章,概述了到目前为止每个人都在回答/评论的大部分内容,但我希望我在这里的解释也能有所帮助。


推荐阅读