google-apps-script - 使用谷歌应用脚本构建实时仪表板
问题描述
我希望能够不断(实时)更新我的网络应用程序,这样每当我的 Google 表格上有更新(通过使用应用程序脚本doGet
功能配置的网络挂钩)时,我构建的 HTML 仪表板中也会显示相同的内容.
我不需要帮助来设置我的工作表、webhook 或 HTML 仪表板 - 我已经设置了所有这些。
我确实需要有关如何在我的函数或工作表上有更新时如何更新我的 HTML 仪表板(网络应用程序)的帮助/建议doGet
(那部分并不重要)。
最好的例子是每次有新用户登陆您的网站时,Google Analytics(分析)实时仪表板的变化方式。
PS。我知道我应该分享一些代码,但我所拥有的一切都与我真正想要的无关;希望这很清楚,但如果你们中的任何人需要查看我的代码/表格,我很乐意创建一个虚拟版本。
解决方案
您需要使用:
google.script.run.withSuccessHandler
这是一个 JavaScript、异步、客户端 API,允许您与服务器端函数进行交互(参考可以在这里找到)。setInterval
以您认为合适的频率调用上述客户端 API 的函数- 3000/3500 毫秒是我到目前为止一直在使用的,服务配额并没有具体谈论它的限制
服务器端
这几乎是在脚本的code.gs部分中编写的代码;您的所有功能都驻留在哪里,这些功能可能与您的电子表格交互或充当 webhook
客户端
这是从您的*.html文件运行并在加载后在您的 Web 浏览器上运行的代码。这是您可以使用“异步”API 的地方
例子
在我的虚拟设置中,我 -
- 从simpsonsquoteapi 中获取随机引用
- 显示每秒变化的计时器
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 秒
浏览器控制台日志可以在这里查看 -
推荐阅读
- c# - 需要 for 循环而不是嵌套的 if 语句
- flutter - 如何创建卷曲页面
- python - 在Django中获取外键的所有外键
- puppeteer - 使用 puppeteer 从匿名函数中提取 JSON 数据
- webpack - Webpack 4 和 Pug 不显示图像
- laravel - 我收到对未定义方法 App\Models\User::identifiableAttribute() 的 BadMethodCallException 调用
- flutter - 在 Flutter 中定位 Grid-View
- android - sqllite-pcl xamarin 表单的 sql lite 动态查询
- javascript - (Node.js) Discord 机器人不会准备好
- apache-nifi - Nifi 中的 ReportLineagetoAtlas 未维护 Nifi 集群中所有节点的状态