corsxmlhttpfactory.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview This file contain classes that add support for cross-domain XHR
  16. * requests (see http://www.w3.org/TR/cors/). Most modern browsers are able to
  17. * use a regular XMLHttpRequest for that, but IE 8 use XDomainRequest object
  18. * instead. This file provides an adapter from this object to a goog.net.XhrLike
  19. * and a factory to allow using this with a goog.net.XhrIo instance.
  20. *
  21. * IE 7 and older versions are not supported (given that they do not support
  22. * CORS requests).
  23. */
  24. goog.provide('goog.net.CorsXmlHttpFactory');
  25. goog.provide('goog.net.IeCorsXhrAdapter');
  26. goog.require('goog.net.HttpStatus');
  27. goog.require('goog.net.XhrLike');
  28. goog.require('goog.net.XmlHttp');
  29. goog.require('goog.net.XmlHttpFactory');
  30. /**
  31. * A factory of XML http request objects that supports cross domain requests.
  32. * This class should be instantiated and passed as the parameter of a
  33. * goog.net.XhrIo constructor to allow cross-domain requests in every browser.
  34. *
  35. * @extends {goog.net.XmlHttpFactory}
  36. * @constructor
  37. * @final
  38. */
  39. goog.net.CorsXmlHttpFactory = function() {
  40. goog.net.XmlHttpFactory.call(this);
  41. };
  42. goog.inherits(goog.net.CorsXmlHttpFactory, goog.net.XmlHttpFactory);
  43. /** @override */
  44. goog.net.CorsXmlHttpFactory.prototype.createInstance = function() {
  45. var xhr = new XMLHttpRequest();
  46. if (('withCredentials' in xhr)) {
  47. return xhr;
  48. } else if (typeof XDomainRequest != 'undefined') {
  49. return new goog.net.IeCorsXhrAdapter();
  50. } else {
  51. throw Error('Unsupported browser');
  52. }
  53. };
  54. /** @override */
  55. goog.net.CorsXmlHttpFactory.prototype.internalGetOptions = function() {
  56. return {};
  57. };
  58. /**
  59. * An adapter around Internet Explorer's XDomainRequest object that makes it
  60. * look like a standard XMLHttpRequest. This can be used instead of
  61. * XMLHttpRequest to support CORS.
  62. *
  63. * @implements {goog.net.XhrLike}
  64. * @constructor
  65. * @struct
  66. * @final
  67. */
  68. goog.net.IeCorsXhrAdapter = function() {
  69. /**
  70. * The underlying XDomainRequest used to make the HTTP request.
  71. * @type {!XDomainRequest}
  72. * @private
  73. */
  74. this.xdr_ = new XDomainRequest();
  75. /**
  76. * The simulated ready state.
  77. * @type {number}
  78. */
  79. this.readyState = goog.net.XmlHttp.ReadyState.UNINITIALIZED;
  80. /**
  81. * The simulated ready state change callback function.
  82. * @type {Function}
  83. */
  84. this.onreadystatechange = null;
  85. /**
  86. * The simulated response text parameter.
  87. * @type {string}
  88. */
  89. this.responseText = '';
  90. /**
  91. * The simulated status code
  92. * @type {number}
  93. */
  94. this.status = -1;
  95. /** @override */
  96. this.responseXML = null;
  97. /** @override */
  98. this.statusText = null;
  99. this.xdr_.onload = goog.bind(this.handleLoad_, this);
  100. this.xdr_.onerror = goog.bind(this.handleError_, this);
  101. this.xdr_.onprogress = goog.bind(this.handleProgress_, this);
  102. this.xdr_.ontimeout = goog.bind(this.handleTimeout_, this);
  103. };
  104. /**
  105. * Opens a connection to the provided URL.
  106. * @param {string} method The HTTP method to use. Valid methods include GET and
  107. * POST.
  108. * @param {string} url The URL to contact. The authority of this URL must match
  109. * the authority of the current page's URL (e.g. http or https).
  110. * @param {?boolean=} opt_async Whether the request is asynchronous, defaulting
  111. * to true. XDomainRequest does not support syncronous requests, so setting
  112. * it to false will actually raise an exception.
  113. * @override
  114. */
  115. goog.net.IeCorsXhrAdapter.prototype.open = function(method, url, opt_async) {
  116. if (goog.isDefAndNotNull(opt_async) && (!opt_async)) {
  117. throw new Error('Only async requests are supported.');
  118. }
  119. this.xdr_.open(method, url);
  120. };
  121. /**
  122. * Sends the request to the remote server. Before calling this function, always
  123. * call {@link open}.
  124. * @param {(ArrayBuffer|ArrayBufferView|Blob|Document|FormData|null|string)=}
  125. * opt_content The content to send as POSTDATA, if any. Only string data is
  126. * supported by this implementation.
  127. * @override
  128. */
  129. goog.net.IeCorsXhrAdapter.prototype.send = function(opt_content) {
  130. if (opt_content) {
  131. if (typeof opt_content == 'string') {
  132. this.xdr_.send(opt_content);
  133. } else {
  134. throw new Error('Only string data is supported');
  135. }
  136. } else {
  137. this.xdr_.send();
  138. }
  139. };
  140. /**
  141. * @override
  142. */
  143. goog.net.IeCorsXhrAdapter.prototype.abort = function() {
  144. this.xdr_.abort();
  145. };
  146. /**
  147. * Sets a request header to send to the remote server. Because this
  148. * implementation does not support request headers, this function does nothing.
  149. * @param {string} key The name of the HTTP header to set. Ignored.
  150. * @param {string} value The value to set for the HTTP header. Ignored.
  151. * @override
  152. */
  153. goog.net.IeCorsXhrAdapter.prototype.setRequestHeader = function(key, value) {
  154. // Unsupported; ignore the header.
  155. };
  156. /**
  157. * Returns the value of the response header identified by key. This
  158. * implementation only supports the 'content-type' header.
  159. * @param {string} key The request header to fetch. If this parameter is set to
  160. * 'content-type' (case-insensitive), this function returns the value of
  161. * the 'content-type' request header. If this parameter is set to any other
  162. * value, this function always returns an empty string.
  163. * @return {string} The value of the response header, or an empty string if key
  164. * is not 'content-type' (case-insensitive).
  165. * @override
  166. */
  167. goog.net.IeCorsXhrAdapter.prototype.getResponseHeader = function(key) {
  168. if (key.toLowerCase() == 'content-type') {
  169. return this.xdr_.contentType;
  170. }
  171. return '';
  172. };
  173. /**
  174. * Handles a request that has fully loaded successfully.
  175. * @private
  176. */
  177. goog.net.IeCorsXhrAdapter.prototype.handleLoad_ = function() {
  178. // IE only calls onload if the status is 200, so the status code must be OK.
  179. this.status = goog.net.HttpStatus.OK;
  180. this.responseText = this.xdr_.responseText;
  181. this.setReadyState_(goog.net.XmlHttp.ReadyState.COMPLETE);
  182. };
  183. /**
  184. * Handles a request that has failed to load.
  185. * @private
  186. */
  187. goog.net.IeCorsXhrAdapter.prototype.handleError_ = function() {
  188. // IE doesn't tell us what the status code actually is (other than the fact
  189. // that it is not 200), so simulate an INTERNAL_SERVER_ERROR.
  190. this.status = goog.net.HttpStatus.INTERNAL_SERVER_ERROR;
  191. this.responseText = '';
  192. this.setReadyState_(goog.net.XmlHttp.ReadyState.COMPLETE);
  193. };
  194. /**
  195. * Handles a request that timed out.
  196. * @private
  197. */
  198. goog.net.IeCorsXhrAdapter.prototype.handleTimeout_ = function() {
  199. this.handleError_();
  200. };
  201. /**
  202. * Handles a request that is in the process of loading.
  203. * @private
  204. */
  205. goog.net.IeCorsXhrAdapter.prototype.handleProgress_ = function() {
  206. // IE only calls onprogress if the status is 200, so the status code must be
  207. // OK.
  208. this.status = goog.net.HttpStatus.OK;
  209. this.setReadyState_(goog.net.XmlHttp.ReadyState.LOADING);
  210. };
  211. /**
  212. * Sets this XHR's ready state and fires the onreadystatechange listener (if one
  213. * is set).
  214. * @param {number} readyState The new ready state.
  215. * @private
  216. */
  217. goog.net.IeCorsXhrAdapter.prototype.setReadyState_ = function(readyState) {
  218. this.readyState = readyState;
  219. if (this.onreadystatechange) {
  220. this.onreadystatechange();
  221. }
  222. };
  223. /**
  224. * Returns the response headers from the server. This implemntation only returns
  225. * the 'content-type' header.
  226. * @return {string} The headers returned from the server.
  227. * @override
  228. */
  229. goog.net.IeCorsXhrAdapter.prototype.getAllResponseHeaders = function() {
  230. return 'content-type: ' + this.xdr_.contentType;
  231. };