Reputation: 89053
According to its documentation, GM_xmlhttpRequest
should be able to take a data
parameter as part of its argument.
However, I can't seem to get it to work.
I have a simple server that echoes the parameters given to it:
require 'sinatra'
require 'json'
get '/' do
JSON.dump params
end
post '/' do
JSON.dump params
end
And a simple greasemonkey script that just tries to POST some data to the server. It tries to pass data as query parameters in the URL and as postdata:
// ==UserScript==
// @name PostDataTest
// @namespace Test
// @description Simple test of GM_xmlhttpRequest's data parameter
// @include http://localhost:4567/
// @version 1
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @grant metadata
// @grant GM_xmlhttpRequest
// ==/UserScript==
var url = '/?q0=0&q1=1';
var data = 'd0=0&d1=1'
GM_xmlhttpRequest({ method: 'POST', url: url, data: data, onload: function(r){
console.log('gm:' + r.responseText);
}});
$.post(url, data, function(d,s,r){
console.log('jq:' + r.responseText);
});
When I POST postdata using jQuery, it works fine, but any postdata I POST using GM_xmlhttpRequest
is ignored:
jq:{"q0":"0","q1":"1","d0":"0","d1":"1"}
gm:{"q0":"0","q1":"1"}
This leads me to believe that GM_xmlhttpRequest
isn't actually using the data
parameter I'm giving it. (I'm not sure b/c I can't monitor GM_xmlhttpRequest
's network activity in Firebug).
What's going on here? Did I screw something up? Did the API shift? How can I use GM_xmlhttpRequest
to post data without packing it into the URL?
Upvotes: 1
Views: 3754
Reputation: 89053
Ok, I used the TamperData firefox add-on to monitor my GM_xmlhttpRequests
(which were sending the postdata) to see what they were doing differently.
The difference was four headers. Where jQuery sent
Accept: */*
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:4567/
GM_xmlhttpRequest
sent:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type: text/plain; charset=UTF-8
Using the headers:
parameter I was able to specify the Content-Type
of my GM_xmlhttpRequest
, which got it to work.
// ==UserScript==
// @name PostDataTest
// @namespace Test
// @description Simple test of GM_xmlhttpRequest's data parameter
// @include http://localhost:4567/
// @version 1
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @grant metadata
// @grant GM_xmlhttpRequest
// ==/UserScript==
var url = '/?q0=0&q1=1';
var data = 'd0=0&d1=1'
GM_xmlhttpRequest({
method: 'POST',
url: url+'gm',
data: data+'gm',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
onload: function(r){
console.log('gm:' + r.responseText);
}});
$.post(url+'jq', data+'jq', function(d,s,r){
console.log('jq:' + r.responseText);
});
Upvotes: 3