Cannot log values using Logger in google app script

折月煮酒 提交于 2021-02-07 10:19:25

问题


Here is my HTML code, from where I call the function loadClient when load button is clicked,

//LOAD CLIENT BUTTON`
document.getElementById("load_button").addEventListener('click',function(){
google.script.run.loadClient();
});

here is the respective function in the code.gs file

//function02-loadClient
function loadClient() {
    eval(UrlFetchApp.fetch('https://apis.google.com/js/api.js').getContentText());
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/webmasters/v3/rest")
       .then(function() { Logger.log("GAPI client loaded for API"); },
              function() { Logger.log("Error loading GAPI client for API" ); });
}

回答1:


When you call google.script.run in the client-side environment, you're requesting execution of a server side Apps Script function.

Your implementation of loadClient() doesn't make sense in the context of server-side Apps Script execution.

Here's a full, simple example of successfully triggering a Logger.log() call on the server-side by way of a client side button click:

client.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <script>
    function registerListener() {
      document.getElementById('callServerFunction').addEventListener('click', function() {
        google.script.run
            .withSuccessHandler(function() {
              alert("Successfully called server function.");
            })
            .withFailureHandler(function() {
              alert("Failed to call server function.");
            })
            .serverFunction();
      });
    }
  </script>
  <body onload="registerListener()">
    <button id="callServerFunction">Call Server Side Function</button>
  </body>
</html>

Code.gs

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

function serverFunction() {
  Logger.log("Server function called.");
}

Server side logging results after the button is clicked

[18-06-10 13:48:20:359 PDT] Server function called.

Regarding the Javascript Google API Client Libraries (i.e. https://apis.google.com/js/api.js), that's not meant to be used in the Apps Script server side context. The whole point of Apps Script is that there is a laundry list of services ready to use immediately without any setup. In addition to not being compatible, trying to load the client-side JS libraries in the server side Apps Script context is simply redundant.

Similarly, trying to use the client-side JS libraries in client-side Apps Script code doesn't make too much sense either, as you have the full set of server-side functionality available via google.script.run.



来源:https://stackoverflow.com/questions/50786526/cannot-log-values-using-logger-in-google-app-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!