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: XHR request: 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?