Google chrome 使用GM_xmlhttpRequest在Chrome上发布数据?
我正在编写一个用户脚本,从页面中获取一个图像,并将其上传到服务器。 该脚本在FF(Greasemonkey和Scriptish)中运行良好,但当我使用Chrome(使用Tampermonkey或Ninjakit)时,它不会发送数据,而是发送字符串*[object]* 这是我的剧本:Google chrome 使用GM_xmlhttpRequest在Chrome上发布数据?,google-chrome,greasemonkey,tampermonkey,gm-xmlhttprequest,ninjakit,Google Chrome,Greasemonkey,Tampermonkey,Gm Xmlhttprequest,Ninjakit,我正在编写一个用户脚本,从页面中获取一个图像,并将其上传到服务器。 该脚本在FF(Greasemonkey和Scriptish)中运行良好,但当我使用Chrome(使用Tampermonkey或Ninjakit)时,它不会发送数据,而是发送字符串*[object]* 这是我的剧本: // ==UserScript== // @id myid // @name myname // @version 1.0 // @namespace
// ==UserScript==
// @id myid
// @name myname
// @version 1.0
// @namespace ohadcn
// @author Ohad Cohen
// @description mydescription
// @include https://*
// @grant GM_xmlhttpRequest
// @require https://code.jquery.com/jquery-2.0.3.min.js
// @run-at document-end
// ==/UserScript==
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
img=$("img[alt=myImage]").get(0);
img.onload=function(){
var img64=getBase64Image(img)
var _data=new FormData();
_data.append("image64",img64);
GM_xmlhttpRequest({
method: "POST",
url: "http://myserver.org/mysscript.py",
headers: {
"Content-Type": "multipart/form-data"
},
data:_data,
onload: function(response) {
console.log ("gut response");
$("#input").get()[0].value=response.responseText;
}
});
}
Tampermonkey和Ninjakit都会发送请求。在Tampermonkey中,我得到一个响应,在Ninjakit中我没有(onload从未被调用) 但是他们不发送用base64编码的实际图像-当我读取数据时-服务器获取[object object]作为POST主体(而不是数据主体,我无法让devtools网络面板显示GM_xmlhttpRequest发出的请求,所以我在服务器端进行了检查).可能是
FormData
和multipart/FormData
在这些平台上没有得到很好的支持。需要(稍后)进一步研究
同时,尝试更典型的方法;使用application/x-www-form-urlencoded
或JSON
例如:
看起来更改内容类型没有效果。将图像直接放入数据字段作为简单的解决方法,但一般情况下的问题仍然存在。我认为这个问题已经解决了,即使我认为这个问题仍然存在,也许chrome/tampermonkey背后的人需要解决这个问题。
GM_xmlhttpRequest ( {
method: "POST",
url: "http://myserver.org/mysscript.py",
data: "image64=" + encodeURIComponent (img64),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function (response) {
console.log ("gut response");
$("#input").get()[0].value=response.responseText;
}
} );