Os resultados do Java Script não aparecem em HTML

Nov 30 2020

Eu escrevi um código GAS para verificar se o funcionário está dentro ou não (extraindo dados das planilhas do Google). O log do console me dá a resposta certa, mas quando clico no botão, a resposta não aparece no front end. Você pode me ajudar a solucionar onde eu errei?

<div>
<script>
 function onStatus(notify) { 
 
 var employee = "John Peter";
 
 var ss = SpreadsheetApp.getActiveSpreadsheet();        
 var mainSheet = ss.getSheetByName("MAIN");
 var data = mainSheet.getDataRange().getValues();
 
 
   for (var j = 0; j < data.length; j++){
    var row = data[j];
    var mainSheet2 = row[4];
    var mainSheet3 = row[0];
    var status = (mainSheet2 =="IN" && mainSheet3 == employee) ; 
    if (status == true){
      var notify = employee +" You Are In"
      
      return notify;
 
  }
      }
document.getElementById('status').innerHTML= notify;       
      }
     
    </script>
<button onclick="onStatus()">Check Status</button>

 <font color='Green' id="status" ></font>
</div>

Respostas

4 Diego Nov 30 2020 at 10:49

O Google oferece um excelente guia de comunicação cliente-servidor, que sugiro que você leia para compreender melhor como isso funciona.

Você não pode colocar código de script de aplicativos (por exemplo SpreadsheetApp.getActiveSpreadsheet()) em seus scripts de frontend. Esse código deve ser executado pelo servidor de script de aplicativos no back-end e você o chamará usando uma google.script.runchamada.

Code.gs

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

function checkStatus() { 
  var employee = "John Peter";
  var ss = SpreadsheetApp.getActiveSpreadsheet();        
  var mainSheet = ss.getSheetByName("MAIN");
  var data = mainSheet.getDataRange().getValues();
  
  for (var j = 0; j < data.length; j++){
    var row = data[j];
    var mainSheet2 = row[4];
    var mainSheet3 = row[0];
    var status = (mainSheet2 =="IN" && mainSheet3 == employee) ; 
    if (status == true){
      return employee + " You Are In";
    }
  }
}

Index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div>
      <button onclick="onStatus()">Check Status</button>
      <font color='Green' id="status" ></font>
    </div>

    <script>
      function onStatus() {
        google.script.run
          .withSuccessHandler(updateStatus) // Send the backend result to updateStatus()
          .checkStatus(); // Call the backend function
      }
  
      function updateStatus(notify) {
        document.getElementById('status').innerHTML= notify;
      }
    </script>
  </body>
</html>