javascriptformsgreasemonkeygm-xmlhttprequest

How to submit to a basic, external form page using GM_xmlhttpRequest?


I created a basic script for Greasemonkey in order to search for the word test on Stack Overflow.

According to GM_xmlhttpRequest documentation, parameters for the request should be indicated in the data argument.

// ==UserScript==
// @name        Test Search SO
// @namespace   Test Search SO
// @description Test Search SO
// @include     http://YOUR_SERVER.COM/YOUR_PATH/*
// @version     1
// @grant       GM_xmlhttpRequest
// ==/UserScript==

alert("Ready?");

GM_xmlhttpRequest({
  url: "http://stackoverflow.com/search",
  method: "GET",
  data: "q=test",
  onload: function(response) {
    document.getElementsByTagName("html")[0].innerHTML = response.responseText;
    alert("Done.");
  }
});

Unfortunately, the result is just the page http://stackoverflow.com/search like if data was ignored.

How can I fix this, please?


Solution

  • To send data to a form page, you normally must use POST.
    To use POST, you also usually must make sure the encoding is as the page expects.

    This works:

    GM_xmlhttpRequest ( {
        url:        "http://stackoverflow.com/search",
        method:     "POST",
        data:       "q=" + encodeURIComponent ("test"),
        headers:    {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        onload:     function (response) {
            document.getElementsByTagName ("html")[0].innerHTML = response.responseText;
            alert ("Done.");
        }
    } );
    

    (Don't forget to URI encode the parameters.)


    Alternatively, many such pages will accept GET requests but then you send the data as URL parameters:

    GM_xmlhttpRequest ( {
        url:        "http://stackoverflow.com/search?q=" + encodeURIComponent ("test"),
        method:     "GET",
        onload:     function (response) {
            document.getElementsByTagName ("html")[0].innerHTML = response.responseText;
            alert ("Done.");
        }
    } );