GM.xmlHttpRequest: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
(4.x updates)
(14 intermediate revisions by 3 users not shown)
Line 1: Line 1:
{{DISPLAYTITLE:GM_xmlhttpRequest}}
== Description ==
== Description ==


This method performs a similar function to the standard [http://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest] object, but allows these requests to cross the [https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript same origin policy] boundaries.
This method performs a similar function to the standard [http://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest] object, but allows these requests to cross the [https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript same origin policy] boundaries.


Compatibility: [[Version_history#0.2.5|Greasemonkey 0.2.5+]]
== Syntax ==


== Syntax ==
{{Function|GM.xmlHttpRequest|details}}


{{Function|GM_xmlhttpRequest|details}}
Compatibility: [[Version_history#4.0_2|Greasemonkey 4.0+]]


=== Arguments ===
=== Arguments ===
Line 16: Line 14:
Described below are the ''properties'' that may be defined on that object.
Described below are the ''properties'' that may be defined on that object.
See [[#Examples]] for more detail on how to use each.
See [[#Examples]] for more detail on how to use each.
Fields:


; <code>binary</code>
; <code>binary</code>
: <code>Boolean</code> (Compatibility: [[Version_history#0.8.3|0.8.3+]]) Optional, default false. When true, use the underlying <code>.sendAsBinary()</code> method.
: <code>Boolean</code> Optional, default false. When true, the <code>data</code> is sent as a Blob.
; <code>context</code>
: <code>Object</code> (Compatibility: [[Version_history#1.10|1.10+]]) Optional, any object. This object will also be the <code>context</code> property of the [[#Response Object]].
; <code>data</code>
; <code>data</code>
: <code>String</code> Optional. Data to send in the request body.  Usually for <code>POST</code> method requests. <sup>[[#Notes|[1]]]</sup>
: <code>String</code> Optional. Data to send in the request body.  Usually for <code>POST</code> method requests. <sup>[[#Notes|[1]]]</sup>
Line 25: Line 27:
; <code>method</code>
; <code>method</code>
: <code>String</code> Type of HTTP request to make (E.G. <code>"GET"</code>, <code>"POST"</code>)
: <code>String</code> Type of HTTP request to make (E.G. <code>"GET"</code>, <code>"POST"</code>)
; <code>overrideMimeType</code>
: <code>String</code> Optional. A MIME type to specify with the request (E.G. <code>"text/html; charset=ISO-8859-1"</code>).
; <code>password</code>
: <code>String</code> Optional. Password to use for authentication purposes.
; <code>synchronous</code>
: <code>Boolean</code> 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>Number</code> The number of milliseconds to wait before terminating the call; zero (the default) means wait forever.
; <code>upload</code>
: <code>Object</code> 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>url</code>
: <code>String</code> The URL to make the request to.  Must be an absolute URL, beginning with the scheme. May be relative to the current page.
; <code>user</code>
: <code>String</code> Optional. User name to use for authentication purposes.
Event handlers:
; <code>onabort</code>
; <code>onabort</code>
: <code>Function</code> (Compatibility: [[Version_history#0.9.9|0.9.9+]]) Optional. Will be called when the request is aborted.  Passed one argument, the [[#Response Object]].
: <code>Function</code> Optional. Will be called when the request is aborted.  Passed one argument, the [[#Response Object]].
; <code>onerror</code>
; <code>onerror</code>
: <code>Function</code> Optional. Will be called if an error occurs while processing the request. Passed one argument, the [[#Response Object]].
: <code>Function</code> Optional. Will be called if an error occurs while processing the request. Passed one argument, the [[#Response Object]].
Line 32: Line 51:
: <code>Function</code> Optional. Will be called when the request has completed successfully.  Passed one argument, the [[#Response Object]].
: <code>Function</code> Optional. Will be called when the request has completed successfully.  Passed one argument, the [[#Response Object]].
; <code>onprogress</code>
; <code>onprogress</code>
: <code>Function</code> (Compatibility: [[Version_history#0.9.9|0.9.9+]]) Optional. Will be called when the request progress changes.  Passed one argument, the [[#Response Object]].
: <code>Function</code> Optional. Will be called when the request progress changes.  Passed one argument, the [[#Response Object]].
; <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>overrideMimeType</code>
; <code>ontimeout</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>Function</code> Optional. Will be called if/when the request times outPassed one argument, the [[#Response Object]].
; <code>password</code>
: <code>String</code> (Compatibility: [[Version_history#0.9.0|0.9.0+]]) Optional. Password to use for authentication purposes.
; <code>synchronous</code>
: <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>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 dataEach is passed one argument, the [[#Response Object]].
; <code>url</code>
: <code>String</code> The URL to make the request to.  Must be an absolute URL, beginning with the scheme. As of [[Version history#0.8.20100408.6|version 0.8.6]], the URL may be relative to the current page.
; <code>user</code>
: <code>String</code> (Compatibility: [[Version_history#0.9.0|0.9.0+]]) Optional. User name to use for authentication purposes.


==== Response Object ====
==== Response Object ====
Line 61: Line 70:


Greasemonkey custom properties:
Greasemonkey custom properties:
* <code>context</code><br><code>Object</code> The same object passed into the original request.
<!-- Not yet in 4.x
* <code>finalUrl</code><br><code>String</code> (Compatibility: [[Version_history#0.8.20080609.0|0.8.0+]]) The final URL requested, if <code>Location</code> redirects were followed.
* <code>finalUrl</code><br><code>String</code> (Compatibility: [[Version_history#0.8.20080609.0|0.8.0+]]) The final URL requested, if <code>Location</code> redirects were followed.
-->


Properties for <code>progress</code> callbacks, based on [https://developer.mozilla.org/En/nsIDOMProgressEvent nsIDOMProgressEvent]:
Properties for <code>progress</code> callbacks, based on [https://developer.mozilla.org/En/nsIDOMProgressEvent nsIDOMProgressEvent]:
Line 70: Line 82:
== Returns ==
== Returns ==


(Compatibility: [[Version history#0.8.20100211.5|version 0.8.5+]])
<code>undefined</code>
In the normal (asynchronous) case, an object with one method: <code>abort()</code>.
 
(Compatibility: [[Version history#0.9.9|version 0.9.9+]])
In the synchronous case, an object with the <code>abort()</code> method, and properties describing the response:
* <code>finalUrl</code>
* <code>readyState</code>
* <code>responseHeaders</code>
* <code>responseText</code>
* <code>status</code>
* <code>statusText</code>
These values are the same as those for a standard <code>XMLHttpRequest</code> object, see the [https://developer.mozilla.org/en/xmlhttprequest#Properties MDN Docs].
(Note: <code>responseHeaders</code> is the result of the <code>getAllResponseHeaders()</code> method.)


== Examples ==
== Examples ==
Line 89: Line 89:


<pre class='sample'>
<pre class='sample'>
GM_xmlhttpRequest({
GM.xmlHttpRequest({
   method: "GET",
   method: "GET",
   url: "http://www.example.com/",
   url: "http://www.example.com/",
Line 101: Line 101:


<pre class='sample'>
<pre class='sample'>
GM_xmlhttpRequest({
GM.xmlHttpRequest({
   method: "GET",
   method: "GET",
   url: "http://www.example.net/",
   url: "http://www.example.net/",
Line 109: Line 109:
   },
   },
   onload: function(response) {
   onload: function(response) {
    var responseXML = null;
     // Inject responseXML into existing Object (only appropriate for XML content).
     // Inject responseXML into existing Object (only appropriate for XML content).
     if (!response.responseXML) {
     if (!response.responseXML) {
       response.responseXML = new DOMParser()
       responseXML = new DOMParser()
         .parseFromString(response.responseText, "text/xml");
         .parseFromString(response.responseText, "text/xml");
     }
     }


     GM_log([
     console.log([
       response.status,
       response.status,
       response.statusText,
       response.statusText,
Line 122: Line 123:
       response.responseText,
       response.responseText,
       response.finalUrl,
       response.finalUrl,
       response.responseXML
       responseXML
     ].join("\n"));
     ].join("\n"));
   }
   }
Line 133: Line 134:


<pre class='sample'>
<pre class='sample'>
GM_xmlhttpRequest({
GM.xmlHttpRequest({
   method: "POST",
   method: "POST",
   url: "http://www.example.net/login",
   url: "http://www.example.net/login",
Line 153: Line 154:


<pre class='sample'>
<pre class='sample'>
GM_xmlhttpRequest({
GM.xmlHttpRequest({
   url: "http://www.example.com",
   url: "http://www.example.com",
   method: "HEAD",
   method: "HEAD",
   onload: function(response) {
   onload: function(response) {
     GM_log(response.responseHeaders);
     console.log(response.responseHeaders);
   }
   }
});</pre>
});</pre>
Line 163: Line 164:
== Notes ==
== Notes ==


<sup>1</sup>
If the <code>data</code> field contains form-encoded data, you usually must also set the header <code>'Content-Type': 'application/x-www-form-urlencoded'</code> in the <code>headers</code> field.
Note that if the <code>data</code> field contains form-encoded data, you usually must also set the header <code>'Content-Type': 'application/x-www-form-urlencoded'</code> in the <code>headers</code> field.
 
<sup>2</sup>
Some headers may not actually work through GM_xmlhttpRequest.
For example, the <code>Referer</code> header cannot be overriden.
[http://groups.google.com/group/greasemonkey-dev/browse_thread/thread/77c94cc17c6b2669]
[http://userscripts.org/forums/1/topics/1302]


[[Category:API_Reference|X]]
[[Category:API_Reference|X]]

Revision as of 16:45, 21 November 2017

Description

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

Syntax

function GM.xmlHttpRequest( details )

Compatibility: Greasemonkey 4.0+

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.

Fields:

binary
Boolean Optional, default false. When true, the data is sent as a Blob.
context
Object (Compatibility: 1.10+) Optional, any object. This object will also be the context property of the #Response Object.
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")
overrideMimeType
String Optional. A MIME type to specify with the request (E.G. "text/html; charset=ISO-8859-1").
password
String Optional. Password to use for authentication purposes.
synchronous
Boolean 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 The number of milliseconds to wait before terminating the call; zero (the default) means wait forever.
upload
Object 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. May be relative to the current page.
user
String Optional. User name to use for authentication purposes.

Event handlers:

onabort
Function 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 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 Optional. Will be called if/when the request times out. Passed one argument, the #Response Object.

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:

  • context
    Object The same object passed into the original request.

Properties for progress callbacks, based on nsIDOMProgressEvent:

  • lengthComputable
  • loaded
  • total

Returns

undefined

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) {
    var responseXML = null;
    // Inject responseXML into existing Object (only appropriate for XML content).
    if (!response.responseXML) {
      responseXML = new DOMParser()
        .parseFromString(response.responseText, "text/xml");
    }

    console.log([
      response.status,
      response.statusText,
      response.readyState,
      response.responseHeaders,
      response.responseText,
      response.finalUrl,
      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) {
    console.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.