polling-xhr.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /**
  2. * Module requirements.
  3. */
  4. var XMLHttpRequest = require('xmlhttprequest-ssl');
  5. var Polling = require('./polling');
  6. var Emitter = require('component-emitter');
  7. var inherit = require('component-inherit');
  8. var debug = require('debug')('engine.io-client:polling-xhr');
  9. /**
  10. * Module exports.
  11. */
  12. module.exports = XHR;
  13. module.exports.Request = Request;
  14. /**
  15. * Empty function
  16. */
  17. function empty () {}
  18. /**
  19. * XHR Polling constructor.
  20. *
  21. * @param {Object} opts
  22. * @api public
  23. */
  24. function XHR (opts) {
  25. Polling.call(this, opts);
  26. this.requestTimeout = opts.requestTimeout;
  27. this.extraHeaders = opts.extraHeaders;
  28. if (global.location) {
  29. var isSSL = 'https:' === location.protocol;
  30. var port = location.port;
  31. // some user agents have empty `location.port`
  32. if (!port) {
  33. port = isSSL ? 443 : 80;
  34. }
  35. this.xd = opts.hostname !== global.location.hostname ||
  36. port !== opts.port;
  37. this.xs = opts.secure !== isSSL;
  38. }
  39. }
  40. /**
  41. * Inherits from Polling.
  42. */
  43. inherit(XHR, Polling);
  44. /**
  45. * XHR supports binary
  46. */
  47. XHR.prototype.supportsBinary = true;
  48. /**
  49. * Creates a request.
  50. *
  51. * @param {String} method
  52. * @api private
  53. */
  54. XHR.prototype.request = function (opts) {
  55. opts = opts || {};
  56. opts.uri = this.uri();
  57. opts.xd = this.xd;
  58. opts.xs = this.xs;
  59. opts.agent = this.agent || false;
  60. opts.supportsBinary = this.supportsBinary;
  61. opts.enablesXDR = this.enablesXDR;
  62. // SSL options for Node.js client
  63. opts.pfx = this.pfx;
  64. opts.key = this.key;
  65. opts.passphrase = this.passphrase;
  66. opts.cert = this.cert;
  67. opts.ca = this.ca;
  68. opts.ciphers = this.ciphers;
  69. opts.rejectUnauthorized = this.rejectUnauthorized;
  70. opts.requestTimeout = this.requestTimeout;
  71. // other options for Node.js client
  72. opts.extraHeaders = this.extraHeaders;
  73. return new Request(opts);
  74. };
  75. /**
  76. * Sends data.
  77. *
  78. * @param {String} data to send.
  79. * @param {Function} called upon flush.
  80. * @api private
  81. */
  82. XHR.prototype.doWrite = function (data, fn) {
  83. var isBinary = typeof data !== 'string' && data !== undefined;
  84. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  85. var self = this;
  86. req.on('success', fn);
  87. req.on('error', function (err) {
  88. self.onError('xhr post error', err);
  89. });
  90. this.sendXhr = req;
  91. };
  92. /**
  93. * Starts a poll cycle.
  94. *
  95. * @api private
  96. */
  97. XHR.prototype.doPoll = function () {
  98. debug('xhr poll');
  99. var req = this.request();
  100. var self = this;
  101. req.on('data', function (data) {
  102. self.onData(data);
  103. });
  104. req.on('error', function (err) {
  105. self.onError('xhr poll error', err);
  106. });
  107. this.pollXhr = req;
  108. };
  109. /**
  110. * Request constructor
  111. *
  112. * @param {Object} options
  113. * @api public
  114. */
  115. function Request (opts) {
  116. this.method = opts.method || 'GET';
  117. this.uri = opts.uri;
  118. this.xd = !!opts.xd;
  119. this.xs = !!opts.xs;
  120. this.async = false !== opts.async;
  121. this.data = undefined !== opts.data ? opts.data : null;
  122. this.agent = opts.agent;
  123. this.isBinary = opts.isBinary;
  124. this.supportsBinary = opts.supportsBinary;
  125. this.enablesXDR = opts.enablesXDR;
  126. this.requestTimeout = opts.requestTimeout;
  127. // SSL options for Node.js client
  128. this.pfx = opts.pfx;
  129. this.key = opts.key;
  130. this.passphrase = opts.passphrase;
  131. this.cert = opts.cert;
  132. this.ca = opts.ca;
  133. this.ciphers = opts.ciphers;
  134. this.rejectUnauthorized = opts.rejectUnauthorized;
  135. // other options for Node.js client
  136. this.extraHeaders = opts.extraHeaders;
  137. this.create();
  138. }
  139. /**
  140. * Mix in `Emitter`.
  141. */
  142. Emitter(Request.prototype);
  143. /**
  144. * Creates the XHR object and sends the request.
  145. *
  146. * @api private
  147. */
  148. Request.prototype.create = function () {
  149. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  150. // SSL options for Node.js client
  151. opts.pfx = this.pfx;
  152. opts.key = this.key;
  153. opts.passphrase = this.passphrase;
  154. opts.cert = this.cert;
  155. opts.ca = this.ca;
  156. opts.ciphers = this.ciphers;
  157. opts.rejectUnauthorized = this.rejectUnauthorized;
  158. var xhr = this.xhr = new XMLHttpRequest(opts);
  159. var self = this;
  160. try {
  161. debug('xhr open %s: %s', this.method, this.uri);
  162. xhr.open(this.method, this.uri, this.async);
  163. try {
  164. if (this.extraHeaders) {
  165. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  166. for (var i in this.extraHeaders) {
  167. if (this.extraHeaders.hasOwnProperty(i)) {
  168. xhr.setRequestHeader(i, this.extraHeaders[i]);
  169. }
  170. }
  171. }
  172. } catch (e) {}
  173. if ('POST' === this.method) {
  174. try {
  175. if (this.isBinary) {
  176. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  177. } else {
  178. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  179. }
  180. } catch (e) {}
  181. }
  182. try {
  183. xhr.setRequestHeader('Accept', '*/*');
  184. } catch (e) {}
  185. // ie6 check
  186. if ('withCredentials' in xhr) {
  187. xhr.withCredentials = true;
  188. }
  189. if (this.requestTimeout) {
  190. xhr.timeout = this.requestTimeout;
  191. }
  192. if (this.hasXDR()) {
  193. xhr.onload = function () {
  194. self.onLoad();
  195. };
  196. xhr.onerror = function () {
  197. self.onError(xhr.responseText);
  198. };
  199. } else {
  200. xhr.onreadystatechange = function () {
  201. if (xhr.readyState === 2) {
  202. var contentType;
  203. try {
  204. contentType = xhr.getResponseHeader('Content-Type');
  205. } catch (e) {}
  206. if (contentType === 'application/octet-stream') {
  207. xhr.responseType = 'arraybuffer';
  208. }
  209. }
  210. if (4 !== xhr.readyState) return;
  211. if (200 === xhr.status || 1223 === xhr.status) {
  212. self.onLoad();
  213. } else {
  214. // make sure the `error` event handler that's user-set
  215. // does not throw in the same tick and gets caught here
  216. setTimeout(function () {
  217. self.onError(xhr.status);
  218. }, 0);
  219. }
  220. };
  221. }
  222. debug('xhr data %s', this.data);
  223. xhr.send(this.data);
  224. } catch (e) {
  225. // Need to defer since .create() is called directly fhrom the constructor
  226. // and thus the 'error' event can only be only bound *after* this exception
  227. // occurs. Therefore, also, we cannot throw here at all.
  228. setTimeout(function () {
  229. self.onError(e);
  230. }, 0);
  231. return;
  232. }
  233. if (global.document) {
  234. this.index = Request.requestsCount++;
  235. Request.requests[this.index] = this;
  236. }
  237. };
  238. /**
  239. * Called upon successful response.
  240. *
  241. * @api private
  242. */
  243. Request.prototype.onSuccess = function () {
  244. this.emit('success');
  245. this.cleanup();
  246. };
  247. /**
  248. * Called if we have data.
  249. *
  250. * @api private
  251. */
  252. Request.prototype.onData = function (data) {
  253. this.emit('data', data);
  254. this.onSuccess();
  255. };
  256. /**
  257. * Called upon error.
  258. *
  259. * @api private
  260. */
  261. Request.prototype.onError = function (err) {
  262. this.emit('error', err);
  263. this.cleanup(true);
  264. };
  265. /**
  266. * Cleans up house.
  267. *
  268. * @api private
  269. */
  270. Request.prototype.cleanup = function (fromError) {
  271. if ('undefined' === typeof this.xhr || null === this.xhr) {
  272. return;
  273. }
  274. // xmlhttprequest
  275. if (this.hasXDR()) {
  276. this.xhr.onload = this.xhr.onerror = empty;
  277. } else {
  278. this.xhr.onreadystatechange = empty;
  279. }
  280. if (fromError) {
  281. try {
  282. this.xhr.abort();
  283. } catch (e) {}
  284. }
  285. if (global.document) {
  286. delete Request.requests[this.index];
  287. }
  288. this.xhr = null;
  289. };
  290. /**
  291. * Called upon load.
  292. *
  293. * @api private
  294. */
  295. Request.prototype.onLoad = function () {
  296. var data;
  297. try {
  298. var contentType;
  299. try {
  300. contentType = this.xhr.getResponseHeader('Content-Type');
  301. } catch (e) {}
  302. if (contentType === 'application/octet-stream') {
  303. data = this.xhr.response || this.xhr.responseText;
  304. } else {
  305. data = this.xhr.responseText;
  306. }
  307. } catch (e) {
  308. this.onError(e);
  309. }
  310. if (null != data) {
  311. this.onData(data);
  312. }
  313. };
  314. /**
  315. * Check if it has XDomainRequest.
  316. *
  317. * @api private
  318. */
  319. Request.prototype.hasXDR = function () {
  320. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  321. };
  322. /**
  323. * Aborts the request.
  324. *
  325. * @api public
  326. */
  327. Request.prototype.abort = function () {
  328. this.cleanup();
  329. };
  330. /**
  331. * Aborts pending requests when unloading the window. This is needed to prevent
  332. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  333. * emitted.
  334. */
  335. Request.requestsCount = 0;
  336. Request.requests = {};
  337. if (global.document) {
  338. if (global.attachEvent) {
  339. global.attachEvent('onunload', unloadHandler);
  340. } else if (global.addEventListener) {
  341. global.addEventListener('beforeunload', unloadHandler, false);
  342. }
  343. }
  344. function unloadHandler () {
  345. for (var i in Request.requests) {
  346. if (Request.requests.hasOwnProperty(i)) {
  347. Request.requests[i].abort();
  348. }
  349. }
  350. }