Search code examples
curlxmlhttprequestgreasemonkeytampermonkeygm-xmlhttprequest

Difference between curl request and Grease/TamperMonkey GM_xmlHttpRequest


I am trying to inject buttons in a website client-sided for easily sending URLs to my pyload instance. I already did a similar thing to create packages in a local jDownloader instance, so i am not too far off here.

I already managed to successfully talk to the pyload API with curl:

curl -s -d "username=myusername&password=mypassword" -X POST http://MYPYLOADINSTANCE:8000/api/login

which returns me - as it should - a session-id which i need to continue using the api.

However, when i try to make the same call from within Tampermonkey with GM_xmlhttpRequest i always get a success with responseText 'false' - which means the authentication was not successful:

GM_xmlhttpRequest ( {
  context: { contextData: 'foo', contextData2: 'bar' }, // <- ignore that, only for testing
  method:  'POST',
  data: 'username=myusername&password=mypassword',
  synchronous: false,
  url:     'http://MYPYLOADINSTANCE:8000/api/login',
  onload:  function(responseDetails) { alert(responseDetails.responseText
          + '\n' + responseDetails.context.contextData); },
  onerror: function(responseDetails) { alert(responseDetails); },
  onabort: function(responseDetails) { alert(responseDetails); }

} );

My question is: what am i doing wrong, where is the difference (for the server / pyload) between using curl and using GM_xmlhttpRequest? I thought it should result in basically the same query ?

And no, sadly i do not see anything in the pyload-logs. :-(


Solution

  • When using POST method in GM.xmlHttpRequest/GM_xmlhttpRequest, you need to set Content-Type header as well.

    POST request

    When making a POST request, most sites require the Content-Type header to be defined as such:

    GM.xmlHttpRequest({
      method: "POST",
      url: "http://www.example.net/login",
      data: "username=johndoe&password=xyz123",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      onload: function(response) {
        if (response.responseText.indexOf("Logged in as") > -1) {
          location.href = "http://www.example.net/dashboard";
        }
      }
    });