[英]Making POST request in Tampermonkey to Google Apps Script
I am using Tampermonkey to monitor a webpage for certain changes, which I am trying to record in a Google Sheet.我正在使用 Tampermonkey 来监控网页的某些更改,我正试图将这些更改记录在 Google 表格中。 To do this, I have a Google Apps Script, and I want to make POST requests to the Apps Script.为此,我有一个 Google Apps 脚本,我想向 Apps 脚本发出 POST 请求。
A snippet of my code in Tampermonkey is shown below:我在 Tampermonkey 中的代码片段如下所示:
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.但是,我收到一条错误消息,指出对 XMLHttpRequest 的访问已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header,以及 a.net::ERR_FAILED 404。
I know that data
is correct, since it has been logged to the console.我知道data
是正确的,因为它已被记录到控制台。 I have also deployed the Apps Script as a Web app, and setting it to execute as Me and for Anyone to have access.我还将 Apps 脚本部署为 Web 应用程序,并将其设置为以我的身份执行,任何人都可以访问。
I do not have much experience with JavaScript, so any help would be appreciated.我对 JavaScript 没有太多经验,因此我们将不胜感激。 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();
For documentation, here another solution for this case (tested in Chrome only)对于文档,这里是针对这种情况的另一种解决方案(仅在 Chrome 中测试过)
Script in Tampermonkey: 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代码.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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.