Workaround: Showing Log in Web Apps to Apps Script Dashboard using Javascript

Gists

I have already reported for showing the log to “Apps Script Dashboard” when it requests to the Web Apps. Ref In order to show the log to “Apps Script Dashboard” when it requests to the Web Apps, it is required to use the access token. But in the current stage, when the access token is used for XMLHttpRequest and fetch of Javascript in the request headers, the error related to CORS occurs. So, in this report, I would like to propose the workaround for resolving this issue.

Workaround

In this workaround, the access token is NOT used for requesting with Javascript. Javascript which is the client side requests to the Web Apps without the access token. By this, no error occurs.

At Web Apps which is the server side, the log is shown in “Apps Script Dashboard” using the access token.

Sample script

Google Apps Script (Server side)

const doGet = (e) => {
  console.log("Done");
  if (!e.parameter.hasOwnProperty("key")) {
    const url = "https://script.google.com/macros/s/###/exec?key=ok";
    UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + ScriptApp.getOAuthToken()}});
  }

  // do something.

  return ContentService.createTextOutput(JSON.stringify({method: "GET", eventObject: e})).setMimeType(ContentService.MimeType.JSON);

  // DriveApp.getFiles() // This is for the scope of "https://www.googleapis.com/auth/drive.readonly"
}

Javascript (Client side)

For XMLHttpRequest

const url = "https://script.google.com/macros/s/###/exec"
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => console.log(xhr.responseText);
xhr.onerror = () => console.log(xhr.response);
xhr.send(null);

For fetch

const url = "https://script.google.com/macros/s/###/exec";
fetch(url).then((res) => res.json()).then(console.log).catch(console.log);

Usage

  1. Please set the Web Apps using above Google Apps Script.
  2. Please request to Web Apps using above Javascript.

By this, even when Javascript doesn’t use the access token, the log shows Done at “Apps Script Dashboard” of the Web Apps. In this case, 1st console.log("Done") is not shown in the log. 2nd one is shown in the log. Because the access token is used in the Web Apps.

Note

  • When you modified the script of Web Apps, please redeploy the Web Apps. By this, the latest script is reflected to Web Apps. Please be careful this.

References

 Share!