GM.xmlHttpRequest: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
Marti (talk | contribs)
Gholk (talk | contribs)
→‎Response Object: responseHeaders is string with CRLF
 
(144 intermediate revisions by 32 users not shown)
Line 1: Line 1:
{{underscore|title=GM_xmlhttpRequest}}
__NOTOC__
== 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:
* [http://www.w3.org/TR/XMLHttpRequest/| http://www.w3.org/TR/XMLHttpRequest]
 
[[#Examples|Examples]] | [[#Notes|Notes]]


== Syntax ==
== Syntax ==


'''GM_xmlhttpRequest(''' ''details'' ''')'''
{{Function|GM.xmlHttpRequest|details}}
 
:Returns: Nothing, details Object
:Compatibility: [[Version_history#0.2.5|Greasemonkey 0.2.5+]]
 
:{| border="1" cellpadding="5"
|+ details Object
!|'''Properties''' || !|'''Event Handler Callbacks'''
|-
| <code>[[#method |method]]</code> ||<code>[[#onload|onload]]</code>
|-
|<code>[[#url |url]]</code> ||<code>[[#onreadystatechange|onreadystatechange]]</code>
|-
|<code>[[#headers |headers]]</code> ||<code>[[#onerror|onerror]]</code>
|-
|<code>[[#overrideMimeType |overrideMimeType]]</code>
|-
|<code>[[#data |data]]</code>
|}
 
:* All properties and event handler callbacks are optional except method and url.
 
[[#Description|top]]
=== Properties ===
----
==== <code>method</code> ====
:Value: String
:Usage: <code>details.'''method''' = "GET"';</code>
 
[[#Description|top]] | [[#Syntax|back]]''
 
==== <code>url</code> ====
:Value: String
:Usage: <code>details.'''url''' = "<nowiki>http://www.greasespot.net/</nowiki>"';</code>
 
[[#Description|top]] | [[#Syntax|back]]
 
==== <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>
Compatibility: [[Version_history#4.0_2|Greasemonkey 4.0+]]


[[#Description|top]] | [[#Syntax|back]]
=== Arguments ===


==== <code>overrideMimeType</code> ====
This method only takes one argument, the <code>details</code> object.
:Value: String
Described below are the ''properties'' that may be defined on that object.
:Compatibility: [[Version_history#0.6.8|Greasemonkey 0.6.8+]]
See [[#Examples]] for more detail on how to use each.
:Usage: <code>details.'''overrideMimeType''' = "application/xhtml+xml";</code>


[[#Description|top]] | [[#Syntax|back]]
Fields:


==== <code>data</code> ====
; <code>binary</code>
:Value: String
: <code>Boolean</code> Optional, default false. When true, the <code>data</code> is sent as a Blob.
:Usage: <code>details.'''data''' = null;</code>
; <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>String</code> Optional. Data to send in the request body.  Usually for <code>POST</code> method requests. <sup>[[#Notes|[1]]]</sup>
; <code>headers</code>
: <code>Object</code> Optional.  A set of headers to include in the request. <sup>[[#Notes|[2]]]</sup>
; <code>method</code>
: <code>String</code> Required. 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>responseType</code>
: <code>String</code> Optional. Decode the response as specified type. Accepted values are <code>""</code>, <code>"arraybuffer"</code>, <code>"blob"</code>, <code>"document"</code>, <code>"json"</code>, <code>"text"</code>, <code>"ms-stream"</code>. Default value is <code>"text"</code>. See [https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType XMLHttpRequest responseType].
; <code>synchronous</code>
: <code>Boolean</code> Defaults to false. 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> Required. 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.


[[#Description|top]] | [[#Syntax|back]]
Event handlers:


=== Event Handler Callbacks ===
; <code>onabort</code>
----
: <code>Function</code> Optional. Will be called when the request is aborted.  Passed one argument, the [[#Response Object]].
==== onload ====
; <code>onerror</code>
:Usage: <code>details.'''onload''' = function (response) { // ''Some code'' };</code>
: <code>Function</code> Optional. Will be called if an error occurs while processing the request. Passed one argument, the [[#Response Object]].
:Returns: Nothing, 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>onprogress</code>
: <code>Function</code> Optional. Will be called when the request progress changes.  Passed one argument, the [[#Response Object]].
; <code>onreadystatechange</code>
: <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> Optional. Will be called if/when the request times out.  Passed one argument, the [[#Response Object]].


[[#Description|top]] | [[#Syntax|back]]
==== Response Object ====


==== onreadystatechange ====
All 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.
:Usage: <code>details.'''onreadystatechange''' = function (response) { // ''Some code'' };</code>
The data available will vary slightly, depending on the type of callback.
:Returns: Nothing, response Object


[[#Description|top]] | [[#Syntax|back]]
Properties based on a standard [https://developer.mozilla.org/en/xmlhttprequest#Properties XMLHttpRequest] object:
* <code>readyState</code>
* <code>responseHeaders</code>: <code>String</code>, with <code>CRLF</code> line terminators.
* <code>responseText</code>
* <code>status</code>
* <code>statusText</code>


==== onerror ====
Greasemonkey custom properties:
:Usage: <code>details.'''onerror''' = function (response) { // ''Some code'' };</code>
* <code>context</code><br><code>Object</code> The same object passed into the original request.
:Returns: Nothing, response Object
<!-- 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.
-->


[[#Description|top]] | [[#Syntax|back]]
Properties for <code>progress</code> callbacks, based on [https://developer.mozilla.org/En/nsIDOMProgressEvent nsIDOMProgressEvent]:
:{| border="1" cellpadding="5"
* <code>lengthComputable</code>
|+ response Object
* <code>loaded</code>
!|'''Properties''' ||'''Event Handler Callbacks'''
* <code>total</code>
|-
|<code>[[#responseText |responseText]]</code>
|-
|<code>[[#status |status]]</code>
|-
|<code>[[#statusText |statusText]]</code>
|-
|<code>[[#readyState |readyState]]</code>
|-
|<code>[[#responseHeaders |responseHeaders]]</code>
|}


=== Properties ===
== Returns ==
----
==== responseText ====
:Value: String
:Usage: <code>alert(response.'''responseText''');</code>


[[#Description|top]] | [[#Event_Handler_Callbacks|back]]
<code>undefined</code>


==== status ====
== Examples ==
:Value: Number
:Usage: <code>if (response.'''status''' == 200) { ''//Some code'' };</code>


[[#Description|top]] | [[#Event_Handler_Callbacks|back]]
=== Bare Minimum ===


==== statusText ====
<pre class='sample'>
:Value: String
GM.xmlHttpRequest({
:Usage: <code>if (response.'''statusText''' == "OK") { ''//Some code'' };</code>
  method: "GET",
  url: "http://www.example.com/",
  onload: function(response) {
    alert(response.responseText);
  }
});
</pre>


[[#Description|top]] | [[#Event_Handler_Callbacks|back]]
=== GET request ===


==== readyState ====
<pre class='sample'>
:Value: Number
GM.xmlHttpRequest({
:Usage: <code>if (response.'''readyState''' == 4) { ''//Some code'' }</code>
  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");
    }


[[#Description|top]] | [[#Event_Handler_Callbacks|back]]
    console.log([
      response.status,
      response.statusText,
      response.readyState,
      response.responseHeaders,
      response.responseText,
      response.finalUrl,
      responseXML
    ].join("\n"));
  }
});
</pre>


==== responseHeaders ====
=== POST request ===
: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>.
When making a POST request, '''most''' sites require the Content-Type header to be defined as such:


[[#Description|top]] | [[#Event_Handler_Callbacks|back]]
<pre class='sample'>
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";
    }
  }
});
</pre>


= Examples =
=== HEAD request ===
<code>
GM_xmlhttpRequest({
  method:"GET",
  url:"<nowiki>http://www.greasespot.net/</nowiki>",
  headers:{
    "User-Agent":"Mozilla/5.0",            ''// Recommend using navigator.userAgent when possible''
    "Accept":"text/xml"
  },
  onload:function(response) {
    alert([
      response.status,
      response.statusText,
      response.readyState,
      response.responseHeaders,
      response.responseText
    ].join("\n"));
  }
});
</code>


[[#Description|top]]
As defined in HTTP, you may issue a HEAD request to get the response headers, without receiving the entire response body.


= Notes =
<pre class='sample'>
<sup>[1]</sup>Some users have reported problems with international character sets.
GM.xmlHttpRequest({
See these [[mailing list]] threads
  url: "http://www.example.com",
  method: "HEAD",
  onload: function(response) {
    console.log(response.responseHeaders);
  }
});</pre>


* http://www.mozdev.org/pipermail/greasemonkey/2006-June/008785.html
== Notes ==
* http://www.mozdev.org/pipermail/greasemonkey/2006-April/008064.html


<sup>[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.
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://groups.google.com/group/greasemonkey-dev/browse_thread/thread/77c94cc17c6b2669
* http://userscripts.org/forums/1/topics/1302?page=1#posts-5312


[[#Description|top]]
[[Category:API_Reference|X]]
[[Category:API_Reference|G]]

Latest revision as of 12:57, 23 August 2021

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 Required. 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.
responseType
String Optional. Decode the response as specified type. Accepted values are "", "arraybuffer", "blob", "document", "json", "text", "ms-stream". Default value is "text". See XMLHttpRequest responseType.
synchronous
Boolean Defaults to false. 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 Required. 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: String, with CRLF line terminators.
  • 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.