Peter
Peter

Reputation: 5601

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?

Upvotes: 12

Views: 7200

Answers (1)

Corey G
Corey G

Reputation: 7858

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.

Upvotes: 9

Related Questions