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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With