Friday, February 17, 2023

way to get "logger-like" continuously updating Google Apps Script Web app output

Since we need to use client-side Ajax to update html pages of the Google Apps Script Web app - https://developers.google.com/apps-script/guides/html/best-practices - one way to get a terminal-like or console log-like experience in the web app would be like this - 

 In the code.gs, 

function doGet() {
return HtmlService
.createTemplateFromFile('Page')
.evaluate()
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

 In the Page.html, a <script> section at the beginning, which has our ajax code, and the <body> section containing the suitable formatted blocks with the relevant ids as called by the ajax functions. 

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js">
</script>
<script>
$(function() {
google.script.run
.withSuccessHandler(displaylog1)
.
withFailureHandler(displaylog1err)
.getdata1();
});

function displaylog1err(data) {
var logger = document.getElementById('log');
logger.innerHTML += "<p>There was an error 1!</p>";
}


function displaylog1(data) {
var logger = document.getElementById('log');
logger.innerHTML += "<p>Done 1!</p>";
google.script.run.withSuccessHandler(displaylog2)
.getdata2();
// we have to call this inside displaylog1
// if we want getdata2() to execute
// only after getdata1() completes.
}

function displaylog2(data) {
var logger = document.getElementById('log');
logger.innerHTML += "<p>Done 2!</p>";
}
</script>
</head>
<body>
<pre id="log0">Logging the output here: </pre>
<pre id="log"> </pre>
</body>
</html>
 

The method mentioned at https://stackoverflow.com/questions/20256760/javascript-console-log-to-html for redirecting console.log did not work for me, maybe because console.log logs to the console of the client making the call, and in our case, the relevant functions are server-side. Or maybe there are other differences, like the (function () { }) call syntax seems to be different from the one below:

$(function() {
var old = console.log;
var logger = document.getElementById('log');
console.log = function () {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == 'object') {
logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
} else {
logger.innerHTML += arguments[i] + '<br />';
}
}
}

No comments:

Post a Comment