GM.xmlHttpRequest: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
m (Text replace - "</pre>}}" to "</pre>")
(simplify)
Line 3: Line 3:
== Description ==
== Description ==


This [[API_reference|API]] method provides access to the chrome-privileged [http://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest] object.
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 means that it '''is''' possible to issue requests to domains other than that of the current page.


Additional reference may be found at:
Compatibility: [[Version_history#0.2.5|Greasemonkey 0.2.5+]]
* [http://www.w3.org/TR/XMLHttpRequest/ http://www.w3.org/TR/XMLHttpRequest]


== Syntax ==
== Syntax ==


'''GM_xmlhttpRequest(''' ''details'' ''')'''
{{Function|GM_xmlhttpRequest|details}}


:Value: Function
== Arguments ==
:Returns: undefined, response Object
:Compatibility: [[Version_history#0.2.5|Greasemonkey 0.2.5+]]


:{| cellpadding="5" style="border-style:solid; background:#FFFFE0;"
This method only takes one argument, the <code>details</code> object.
|+ ''details'' Object
Described below are the ''properties'' that may be defined on that object.
!style="background:#CC9900;"|'''Properties''' || style="background:#CC9900;"|'''Event Handler Callbacks'''
See [[#Examples]] for more detail on how to use each.
|-
| <code><span style="background:#FFFFE0;">[[#method |method]]</span></code> || <code><span style="background:#FFFFE0;">[[#onload|onload]]</span></code>
|-
|<code><span style="background:#FFFFE0;">[[#url |url]]</span></code> ||<code><span style="background:#FFFFE0;">[[#onreadystatechange|onreadystatechange]]</span></code>
|-
|<code><span style="background:#FFFFE0;">[[#headers |headers]]</span></code> ||<code><span style="background:#FFFFE0;">[[#onerror|onerror]]</span></code>
|-
|<code><span style="background:#FFFFE0;">[[#overrideMimeType |overrideMimeType]]</span></code>
|-
|<code><span style="background:#FFFFE0;">[[#data |data]]</span></code>
|-
|<code><span style="background:#FFFFE0;">[[#binary |binary]]</span></code>
|}


:* All properties and event handler callbacks are optional except [[#method|method]] and [[#url|url]].
; <code>method</code>
: <code>String</code> Type of HTTP request to make (E.G. <code>"GET"</code>, <code>"POST"</code>)
; <code>url</code>
: <code>String</code> The URL to make the request to.  Must be an absolute URL, beginning with the scheme.
; <code>headers</code>
: <code>Object</code> Optional.  A set of headers to include in the request. <sup>[[#Notes|[2]]]</sup>
; <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>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>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>onerror</code>
: <code>Function</code> Optional. Will be called when the request has completed successfully.  Passed one argument, the [[#Response Object]].
; <code>onload</code>
: <code>Function</code> Optional. Will be called when the request has completed successfully.  Passed one argument, the [[#Response Object]].
; <code>onreadystatechange</code>
: <code>Function</code> Optional. Will be called when the request has completed successfully.  Passed one argument, the [[#Response Object]].


=== Properties ===
=== Response Object ===
----
==== <code>method</code> ====
:Value: String
:Usage: <code>''details''.'''method''' = "GET"';</code>
 
 
==== <code>url</code> ====
:Value: String
:Usage: <code>''details''.'''url''' = "<nowiki>http://www.greasespot.net/</nowiki>";</code>
 
:*Must be an absolute URL.
 
 
 
==== <code>headers</code> ====
:Value: Object
:Usage: <code>''details''.'''headers''' = {"User-Agent":"Mozilla/5.0"};</code>
 
:* The <code>headers</code> property is an object which is typically used to override the default browser generated headers, also known as atoms. It should contain the atom-value pairs of the headers to send.<sup>[[#Notes|[2]]]</sup>
 
 
 
==== <code>overrideMimeType</code> ====
:Value: String
:Compatibility: [[Version_history#0.6.8|Greasemonkey 0.6.8+]]
:Usage: <code>''details''.'''overrideMimeType''' = "text/html; charset=ISO-8859-1";</code>
 
:* While each character set name may have multiple aliases defined, there may be a preferred name which can be found at [http://www.iana.org/assignments/character-sets IANA]
 
 
==== <code>data</code> ====
:Value: String
:Usage: <code>''details''.'''data''' = null; ''/* some code */'' if (''details''.'''data''') { ''/* some code */'' }</code>
:* <sup>[[#Notes|[1]]]</sup>
:* Note that if the <code>data</code> field contains form-encoded data, you must also set the header <code>'Content-Type': 'application/x-www-form-urlencoded'</code> in the <code>headers</code> field.
 
==== <code>binary</code> ====
:Value: Boolean
:Usage: <code>''details''.'''binary''' = true;</code>
:Compatibility: [[Version_history#0.8.3|Greasemonkey 0.8.3+]]
:* Optional.  Default false.  If true, the underling xmlHttpRequest will have <tt>.sendAsBinary()</tt> instead of <tt>.send()</tt> called.
 
 
 
=== Event Handler Callbacks ===
----
==== onload ====
:Usage: <code>''details''.'''onload''' = function (''response'') { ''/* some code */'' };</code>
:Returns: undefined, response Object
 
 
 
==== onreadystatechange ====
:Usage: <code>''details''.'''onreadystatechange''' = function (''response'') { ''/* some code */'' };</code>
:Returns: undefined, response Object
 
 
 
==== onerror ====
:Usage: <code>''details''.'''onerror''' = function (''response'') { ''/* some code */'' };</code>
:Returns: undefined, response Object
 
 
:{| cellpadding="5" style="border-style:solid; background:#FFFFE0;"
|+ ''response'' Object
! colspan="4" style="background:#CC9900;" |'''Properties'''
|-
|<code><span style="background:#FFFFE0;">[[#status |status]]</span></code> || <code><span style="background:#FFFFE0;">[[#readyState |readyState]]</span></code> || <code><span style="background:#FFFFE0;">[[#responseText |responseText]]</span></code> || <code><span style="background:#FFFFE0;">[[#finalUrl |finalUrl]]</span></code>
|-
|<code><span style="background:#FFFFE0;">[[#statusText |statusText]]</span></code> || || <code><span style="background:#FFFFE0;">[[#responseHeaders |responseHeaders]]</span></code>
|}
:* Note: there is no <code>responseXML</code> property, contrary to what people used to XMLHttpRequest might expect. This is due to security restrictions imposed on the XMLDocument created in the privileged GM core context. One can easily create its own XMLDocument out of <code>responseText</code> using a DOMParser (see [[#Examples|examples]] below).
 
=== Properties ===
----
 
==== status ====
:Value: Number
:Usage: <code>if (''response''.'''status''' == 200) { ''/* some code */'' }</code>
 
 
 
==== statusText ====
:Value: String
:Usage: <code>if (''response''.'''statusText''' == "OK") { ''/* some code */'' }</code>
 
 
 
==== readyState ====
:Value: Number
:Usage: <code>if (''response''.'''readyState''' == 4) { ''/* some code */'' }</code>
 
 
 
==== responseText ====
:Value: String
:Usage: <code>alert(''response''.'''responseText''');</code>
 
 
 
==== responseHeaders ====
:Value: String
:Usage: <code>if (''response''.'''responseHeaders''') { ''/* some code */'' }</code>
 
:* The <code>responseHeaders</code> is the string representation of response headers returned by <code>XMLHTTPRequest.getAllResponseHeaders()</code>.
 
==== finalUrl ====
:Value: String
:Compatibility: [[Version_history#0.8.20080609.0|Greasemonkey 0.8.0+]]
:Usage: <code>if (''response''.'''finalUrl''') { ''/* some code */'' }</code>


All three of the callback functions defined in the <code>details</code> object, if called, will receive this type of object as their first (and only) argument.


; <code>status</code>
: <code>Integer</code> The HTTP response status (E.G. 200 or 404) upon success, or <code>null</code> upon failure.
; <code>statusText</code>
: <code>String</code> The HTTP response status line (E.G. <code>"OK"</code>, <code>"Not Found"</code>) upon success, or <code>null</code> upon failure.
; <code>readyState</code>
: <code>Number</code> The <code>readyState</code> as defined in [https://developer.mozilla.org/en/XMLHttpRequest XMLHttpRequest].
; <code>responseText</code>
: <code>String</code> The <code>responseText</code> as defined in [https://developer.mozilla.org/en/XMLHttpRequest XMLHttpRequest].
; <code>responseHeaders</code>
: <code>String</code> The response headers as defined in [https://developer.mozilla.org/en/XMLHttpRequest#getAllResponseHeaders() XMLHttpRequest].
; <code>finalUrl</code>
: <code>String</code> (Compatibility: [[Version_history#0.8.20080609.0|0.8.0+]]) The final URL requested, if <code>Location</code> redirects were followed.


== Examples ==
== Examples ==


=== Core ===
=== GET request ===
 
==== GET request ====


<pre class='sample'>
<pre class='sample'>
Line 161: Line 62:
   url: "http://www.example.net/",
   url: "http://www.example.net/",
   headers: {
   headers: {
     "User-Agent": "Mozilla/5.0",           // If not specified, navigator.userAgent will be used.
     "User-Agent": "Mozilla/5.0",   // If not specified, navigator.userAgent will be used.
     "Accept": "text/xml"                   // If not specified, browser defaults will be used.
     "Accept": "text/xml"           // If not specified, browser defaults will be used.
   },
   },
   onload: function(response) {
   onload: function(response) {
     // Inject responseXML into existing Object if not present
     // Inject responseXML into existing Object if not present
     if (!response.responseXML)
     if (!response.responseXML) {
       response.responseXML = new DOMParser().parseFromString(response.responseText, "text/xml");
       response.responseXML = new DOMParser()
        .parseFromString(response.responseText, "text/xml");
    }


     GM_log([
     GM_log([
Line 182: Line 85:
</pre>
</pre>


==== POST request ====
=== POST request ===


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


<pre class='sample'>
<pre class='sample'>
Line 195: Line 98:
   },
   },
   onload: function(response) {
   onload: function(response) {
     if (response.responseText.indexOf("Logged in as") > -1)
     if (response.responseText.indexOf("Logged in as") > -1) {
       location.href = "http://www.example.net/dashboard";
       location.href = "http://www.example.net/dashboard";
    }
   }
   }
});
});
</pre>
</pre>


==== HEAD request ====
=== HEAD request ===
 
As defined in HTTP, you may issue a HEAD request to read the response headers, but skip reading the entire response body.
This request type must be supported by the server (but is by most).


Sometimes <code>responseText</code> may be unnecessary, in which case a "HEAD" request is more advisable.
<pre class='sample'>
<pre class='sample'>
GM_xmlhttpRequest({
GM_xmlhttpRequest({
Line 212: Line 118:
   }
   }
});</pre>
});</pre>


== Notes ==
== Notes ==


<sup>[[GM_xmlhttpRequest#data|[1]]]</sup>Some users have reported problems with international character sets.
<sup>1</sup>
See these [[mailing list]] threads
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.
 
* http://www.mozdev.org/pipermail/greasemonkey/2006-June/008785.html
* http://www.mozdev.org/pipermail/greasemonkey/2006-April/008064.html
'''Resolved:''' Greasemonkey exposed the [[#overrideMimeType|overrideMimeType]] method to allow changing of the desired charset.


<sup>[[GM_xmlhttpRequest#headers|[2]]]</sup>Some header atoms may not actually work through GM_xmlhttpRequest. The Referer atom is one that is known to be recognized but appears to be content filtered by the browser. This may be due to security restrictions to keep user scripts from doing unsafe things.
<sup>2</sup>
* http://groups.google.com/group/greasemonkey-dev/browse_thread/thread/77c94cc17c6b2669
Some headers may not actually work through GM_xmlhttpRequest.
* http://userscripts.org/forums/1/topics/1302
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 22:30, 8 February 2010


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.

method
String Type of HTTP request to make (E.G. "GET", "POST")
url
String The URL to make the request to. Must be an absolute URL, beginning with the scheme.
headers
Object Optional. A set of headers to include in the request. [2]
overrideMimeType
String (Compatibility: 0.6.8+) Optional. A MIME type to specify with the request (E.G. "text/html; charset=ISO-8859-1").
data
String Optional. Data to send in the request body. Usually for POST method requests. [1]
binary
Boolean (Compatibility: 0.8.3+) Optional, default false. When true, use the underlying .sendAsBinary() method.
onerror
Function Optional. Will be called when the request has completed successfully. Passed one argument, the #Response Object.
onload
Function Optional. Will be called when the request has completed successfully. Passed one argument, the #Response Object.
onreadystatechange
Function Optional. Will be called when the request has completed successfully. Passed one argument, the #Response Object.

Response Object

All three of the callback functions defined in the details object, if called, will receive this type of object as their first (and only) argument.

status
Integer The HTTP response status (E.G. 200 or 404) upon success, or null upon failure.
statusText
String The HTTP response status line (E.G. "OK", "Not Found") upon success, or null upon failure.
readyState
Number The readyState as defined in XMLHttpRequest.
responseText
String The responseText as defined in XMLHttpRequest.
responseHeaders
String The response headers as defined in XMLHttpRequest.
finalUrl
String (Compatibility: 0.8.0+) The final URL requested, if Location redirects were followed.

Examples

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 if not present
    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 read the response headers, but skip reading the entire response body. This request type must be supported by the server (but is by most).

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

Notes

1 Note that 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.

2 Some headers may not actually work through GM_xmlhttpRequest. For example, the Referer header cannot be overriden. [1] [2]