Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make XHR/ajax requests against Google Apps Script ContentService work?

I have a simple Google Apps Script ContentService that emits a string like "Hello world Sat Jul 14 2012 14:17:21 GMT+1000 (EST)" The url is https://script.google.com/macros/s/AKfycbxbFFG95mi8PWVNCE8366XaxnXQrt6p7p3OWbclXch_bbWczQ/exec and it's open to anonymous. Feel free to hit it. The code is:

function doGet() {
  var output = ContentService.createTextOutput()
      .setMimeType(ContentService.MimeType.TEXT)
      .setContent("Hello world " + new Date());
  Logger.log(output.getContent());
  return output;
}

When I visit the URL in a browser it returns the string as expected (pass.png). When I use the same URL in an XHR (ajax call) it fails with an empty error. In the developer tools in Chrome the redirect is "(canceled)" (fail.png) . Here is the code to reproduce the fail:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
  xhr=new XMLHttpRequest();
  xhr.onreadystatechange=function() {
  if (xhr.readyState==4 && xhr.status==200) {
    document.getElementById("myDiv").innerHTML=xhr.responseText;
    }
  };
  xhr.open("GET","https://script.google.com/macros/s/AKfycbxbFFG95mi8PWVNCE8366XaxnXQrt6p7p3OWbclXch_bbWczQ/exec",true);
  xhr.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Get Content via XHR</button>
</body>
</html>

Direct request: DIrect requestpass.png XHR request: enter image description here My question (hopefully specific enough): How do I make XHR calls from a plain old web page on example.com to GET content from anonymous Google Apps Script ContentService scripts?

like image 207
Pete Avatar asked Jul 14 '12 05:07

Pete


People also ask

How do I handle GET and POST HTTP requests in Google Apps Script?

Handle POST Requests with Google ScriptsThe callback function doPost is invoked when an HTTP POST request is make to your Google Script URL that is published as a web app with anonymous access. const doPost = (request) => { console. log(request); return ContentService. crateTextOutput(JSON.


1 Answers

I am not sure this is currently possible. We considered the JSONP method (which does work; I've tested it) but I don't think making an XHR against ContentService was ever tested. We'd probably need to set up CORS headers for this. Please file a feature request on the issue tracker and we'll see if it can be done.

like image 123
Corey G Avatar answered Oct 06 '22 08:10

Corey G