GM.xmlHttpRequest: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
Line 35: Line 35:
; <code>onreadystatechange</code>
; <code>onreadystatechange</code>
: <code>Function</code> Optional. Will be called repeatedly while the request is in progress.  Passed one argument, the [[#Response Object]].
: <code>Function</code> Optional. Will be called repeatedly while the request is in progress.  Passed one argument, the [[#Response Object]].
; <code>ontimeout</code>
: <code>Function</code> (Compatibility: [[Version_history#1.0|1.0+]]) Optional. Will be called if/when the request times out.  Passed one argument, the [[#Response Object]].
; <code>overrideMimeType</code>
; <code>overrideMimeType</code>
: <code>String</code> (Compatibility: [[Version_history#0.6.8|0.6.8+]]) Optional. A MIME type to specify with the request (E.G. <code>"text/html; charset=ISO-8859-1"</code>).
: <code>String</code> (Compatibility: [[Version_history#0.6.8|0.6.8+]]) Optional. A MIME type to specify with the request (E.G. <code>"text/html; charset=ISO-8859-1"</code>).
Line 42: Line 44:
: <code>Boolean</code> (Compatibility: [[Version_history#0.9.9|0.9.9+]]) When true, this is a ''synchronous'' request.  '''Be careful''': The entire Firefox UI will be locked and frozen until the request completes.  In this mode, more data will be available in the [[#Returns|return value]].
: <code>Boolean</code> (Compatibility: [[Version_history#0.9.9|0.9.9+]]) When true, this is a ''synchronous'' request.  '''Be careful''': The entire Firefox UI will be locked and frozen until the request completes.  In this mode, more data will be available in the [[#Returns|return value]].
; <code>timeout</code>
; <code>timeout</code>
: <code>Number</code> (Compatibility: Greasemonkey [[Version_history#1.0|1.0]], Firefox 12) The number of milliseconds to wait before terminating the call; zero (the default) means wait forever.
: <code>Number</code> (Compatibility: Greasemonkey [[Version_history#1.0|1.0+]], Firefox 12) The number of milliseconds to wait before terminating the call; zero (the default) means wait forever.
; <code>upload</code>
; <code>upload</code>
: <code>Object</code> (Compatibility: [[Version_history#0.9.9|0.9.9+]]) Optional. Object containing optional function callbacks (<code>onabort</code>, <code>onerror</code>, <code>onload</code>, <code>onprogress</code>) to monitor the upload of data.  Each is passed one argument, the [[#Response Object]].
: <code>Object</code> (Compatibility: [[Version_history#0.9.9|0.9.9+]]) Optional. Object containing optional function callbacks (<code>onabort</code>, <code>onerror</code>, <code>onload</code>, <code>onprogress</code>) to monitor the upload of data.  Each is passed one argument, the [[#Response Object]].

Revision as of 19:32, 15 June 2012


Description

This method performs a similar function to the standard XMLHttpRequest object, but allows these requests to cross the same origin policy boundaries.

Compatibility: Greasemonkey 0.2.5+

Syntax

function GM_xmlhttpRequest( details )

Arguments

This method only takes one argument, the details object. Described below are the properties that may be defined on that object. See #Examples for more detail on how to use each.

binary
Boolean (Compatibility: 0.8.3+) Optional, default false. When true, use the underlying .sendAsBinary() method.
data
String Optional. Data to send in the request body. Usually for POST method requests. [1]
headers
Object Optional. A set of headers to include in the request. [2]
method
String Type of HTTP request to make (E.G. "GET", "POST")
onabort
Function (Compatibility: 0.9.9+) Optional. Will be called when the request is aborted. Passed one argument, the #Response Object.
onerror
Function Optional. Will be called if an error occurs while processing the request. Passed one argument, the #Response Object.
onload
Function Optional. Will be called when the request has completed successfully. Passed one argument, the #Response Object.
onprogress
Function (Compatibility: 0.9.9+) Optional. Will be called when the request progress changes. Passed one argument, the #Response Object.
onreadystatechange
Function Optional. Will be called repeatedly while the request is in progress. Passed one argument, the #Response Object.
ontimeout
Function (Compatibility: 1.0+) Optional. Will be called if/when the request times out. Passed one argument, the #Response Object.
overrideMimeType
String (Compatibility: 0.6.8+) Optional. A MIME type to specify with the request (E.G. "text/html; charset=ISO-8859-1").
password
String (Compatibility: 0.9.0+) Optional. Password to use for authentication purposes.
synchronous
Boolean (Compatibility: 0.9.9+) When true, this is a synchronous request. Be careful: The entire Firefox UI will be locked and frozen until the request completes. In this mode, more data will be available in the return value.
timeout
Number (Compatibility: Greasemonkey 1.0+, Firefox 12) The number of milliseconds to wait before terminating the call; zero (the default) means wait forever.
upload
Object (Compatibility: 0.9.9+) Optional. Object containing optional function callbacks (onabort, onerror, onload, onprogress) to monitor the upload of data. Each is passed one argument, the #Response Object.
url
String The URL to make the request to. Must be an absolute URL, beginning with the scheme. As of version 0.8.6, the URL may be relative to the current page.
user
String (Compatibility: 0.9.0+) Optional. User name to use for authentication purposes.

Response Object

All of the callback functions defined in the details object, if called, will receive this type of object as their first (and only) argument. The data available will vary slightly, depending on the type of callback.

Properties based on a standard XMLHttpRequest object:

  • readyState
  • responseHeaders
  • responseText
  • status
  • statusText

Greasemonkey custom properties:

  • finalUrl
    String (Compatibility: 0.8.0+) The final URL requested, if Location redirects were followed.

Properties for progress callbacks, based on nsIDOMProgressEvent:

  • lengthComputable
  • loaded
  • total

Returns

(Compatibility: version 0.8.5+) In the normal (asynchronous) case, an object with one method: abort().

(Compatibility: version 0.9.9+) In the synchronous case, an object with the abort() method, and properties describing the response:

  • finalUrl
  • readyState
  • responseHeaders
  • responseText
  • status
  • statusText

These values are the same as those for a standard XMLHttpRequest object, see the MDN Docs. (Note: responseHeaders is the result of the getAllResponseHeaders() method.)

Examples

Bare Minimum

GM_xmlhttpRequest({
  method: "GET",
  url: "http://www.example.com/",
  onload: function(response) {
    alert(response.responseText);
  }
});

GET request

GM_xmlhttpRequest({
  method: "GET",
  url: "http://www.example.net/",
  headers: {
    "User-Agent": "Mozilla/5.0",    // If not specified, navigator.userAgent will be used.
    "Accept": "text/xml"            // If not specified, browser defaults will be used.
  },
  onload: function(response) {
    // Inject responseXML into existing Object (only appropriate for XML content).
    if (!response.responseXML) {
      response.responseXML = new DOMParser()
        .parseFromString(response.responseText, "text/xml");
    }

    GM_log([
      response.status,
      response.statusText,
      response.readyState,
      response.responseHeaders,
      response.responseText,
      response.finalUrl,
      response.responseXML
    ].join("\n"));
  }
});

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";
    }
  }
});

HEAD request

As defined in HTTP, you may issue a HEAD request to get the response headers, without receiving the entire response body.

GM_xmlhttpRequest({
  url: "http://www.example.com",
  method: "HEAD",
  onload: function(response) {
    GM_log(response.responseHeaders);
  }
});

Notes

If the data field contains form-encoded data, you usually must also set the header 'Content-Type': 'application/x-www-form-urlencoded' in the headers field.