Reputation: 21
I am using Tampermonkey to monitor a webpage for certain changes, which I am trying to record in a Google Sheet. To do this, I have a Google Apps Script, and I want to make POST requests to the Apps Script.
A snippet of my code in Tampermonkey is shown below:
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://script.google.com/macros/s/~~scriptId~~/exec", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
However, I am getting an error that says Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource, and a net::ERR_FAILED 404 as well.
I know that data
is correct, since it has been logged to the console. I have also deployed the Apps Script as a Web app, and setting it to execute as Me and for Anyone to have access.
I do not have much experience with JavaScript, so any help would be appreciated. Is there anything I can do to fix this?
Edit: I resolved it by changing the code to
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://script.google.com/macros/s/~~scriptId~~/exec?"+data, true);
xhr.send();
Upvotes: 2
Views: 4406
Reputation: 917
For documentation, here another solution for this case (tested in Chrome only)
Script in Tampermonkey:
// @grant GM.xmlHttpRequest
function test() {
var obj = {};
obj.param_0 = "abc";
obj.param_1 = "xyz";
sending_xml(obj);
}
function sending_xml(obj) {
console.log("SENDING DATA");
GM.xmlHttpRequest ({
method: "POST",
url: "https://script.google.com/macros/s/[DEPLOYMENT_ID]/exec",
data: JSON.stringify(obj),
headers: {
"Content-Type": "application/json"
},
onload: function (response) {
console.log(response); //display "ok"
}
});
}
Code.gs
function doPost(e) {
var string = e.postData.getDataAsString();
var data = JSON.parse(string);
Logger.log(data);
//do stuff;
return "ok";
}
//must be deployed as WebApp, with "Access to All"
Upvotes: 3