I have a working Google Apps script that displays a single web app output at the end.
The script lasts about ~20 seconds, and I'm looking to improve the user experience, by intermittently update the script status during this period.
I understand the challenges of asynchronous server/client operation, but I'm surprised that such "trivial" functionaly seems quite hard to realize.
I reviewed similar topics, but miss a good example.
Code Example :
function doGet(e){
output = function1();
output = function2();
return HtmlService.createHtmlOutput(output).
}
function function1() {
//DoSomething
return = "output1";
}
function function2() {
//DoSomething
return = "output2";
}
I'm not looking to replace the function calls by HTML calls. But maybe continously poll a global variable until script execution is completed, if this is feasible?
Maybe to make it more concrete,
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>
but I cannot find anyway to display the valid data
variable ...
CodePudding user response:
I found the answer,
- Create cache service in .gs
- update cache key throughout several .gs functions
- poll for cache key updates from hmtl using setInterval()
I got triggered by this very well maintained & interesting blog post: https://ramblings.mcpher.com/gassnippets2/implementing-a-client-side-progress-bar-reporting-on-server-side-work-for-htmlservice/
Best Regards, Kristof