polling-xhr.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /* global attachEvent */
  2. /**
  3. * Module requirements.
  4. */
  5. var XMLHttpRequest = require('xmlhttprequest-ssl');
  6. var Polling = require('./polling');
  7. var Emitter = require('component-emitter');
  8. var inherit = require('component-inherit');
  9. var debug = require('debug')('engine.io-client:polling-xhr');
  10. /**
  11. * Module exports.
  12. */
  13. module.exports = XHR;
  14. module.exports.Request = Request;
  15. /**
  16. * Empty function
  17. */
  18. function empty () {}
  19. /**
  20. * XHR Polling constructor.
  21. *
  22. * @param {Object} opts
  23. * @api public
  24. */
  25. function XHR (opts) {
  26. Polling.call(this, opts);
  27. this.requestTimeout = opts.requestTimeout;
  28. this.extraHeaders = opts.extraHeaders;
  29. if (typeof location !== 'undefined') {
  30. var isSSL = 'https:' === location.protocol;
  31. var port = location.port;
  32. // some user agents have empty `location.port`
  33. if (!port) {
  34. port = isSSL ? 443 : 80;
  35. }
  36. this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
  37. port !== opts.port;
  38. this.xs = opts.secure !== isSSL;
  39. }
  40. }
  41. /**
  42. * Inherits from Polling.
  43. */
  44. inherit(XHR, Polling);
  45. /**
  46. * XHR supports binary
  47. */
  48. XHR.prototype.supportsBinary = true;
  49. /**
  50. * Creates a request.
  51. *
  52. * @param {String} method
  53. * @api private
  54. */
  55. XHR.prototype.request = function (opts) {
  56. opts = opts || {};
  57. opts.uri = this.uri();
  58. opts.xd = this.xd;
  59. opts.xs = this.xs;
  60. opts.agent = this.agent || false;
  61. opts.supportsBinary = this.supportsBinary;
  62. opts.enablesXDR = this.enablesXDR;
  63. // SSL options for Node.js client
  64. opts.pfx = this.pfx;
  65. opts.key = this.key;
  66. opts.passphrase = this.passphrase;
  67. opts.cert = this.cert;
  68. opts.ca = this.ca;
  69. opts.ciphers = this.ciphers;
  70. opts.rejectUnauthorized = this.rejectUnauthorized;
  71. opts.requestTimeout = this.requestTimeout;
  72. // other options for Node.js client
  73. opts.extraHeaders = this.extraHeaders;
  74. return new Request(opts);
  75. };
  76. /**
  77. * Sends data.
  78. *
  79. * @param {String} data to send.
  80. * @param {Function} called upon flush.
  81. * @api private
  82. */
  83. XHR.prototype.doWrite = function (data, fn) {
  84. var isBinary = typeof data !== 'string' && data !== undefined;
  85. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  86. var self = this;
  87. req.on('success', fn);
  88. req.on('error', function (err) {
  89. self.onError('xhr post error', err);
  90. });
  91. this.sendXhr = req;
  92. };
  93. /**
  94. * Starts a poll cycle.
  95. *
  96. * @api private
  97. */
  98. XHR.prototype.doPoll = function () {
  99. debug('xhr poll');
  100. var req = this.request();
  101. var self = this;
  102. req.on('data', function (data) {
  103. self.onData(data);
  104. });
  105. req.on('error', function (err) {
  106. self.onError('xhr poll error', err);
  107. });
  108. this.pollXhr = req;
  109. };
  110. /**
  111. * Request constructor
  112. *
  113. * @param {Object} options
  114. * @api public
  115. */
  116. function Request (opts) {
  117. this.method = opts.method || 'GET';
  118. this.uri = opts.uri;
  119. this.xd = !!opts.xd;
  120. this.xs = !!opts.xs;
  121. this.async = false !== opts.async;
  122. this.data = undefined !== opts.data ? opts.data : null;
  123. this.agent = opts.agent;
  124. this.isBinary = opts.isBinary;
  125. this.supportsBinary = opts.supportsBinary;
  126. this.enablesXDR = opts.enablesXDR;
  127. this.requestTimeout = opts.requestTimeout;
  128. // SSL options for Node.js client
  129. this.pfx = opts.pfx;
  130. this.key = opts.key;
  131. this.passphrase = opts.passphrase;
  132. this.cert = opts.cert;
  133. this.ca = opts.ca;
  134. this.ciphers = opts.ciphers;
  135. this.rejectUnauthorized = opts.rejectUnauthorized;
  136. // other options for Node.js client
  137. this.extraHeaders = opts.extraHeaders;
  138. this.create();
  139. }
  140. /**
  141. * Mix in `Emitter`.
  142. */
  143. Emitter(Request.prototype);
  144. /**
  145. * Creates the XHR object and sends the request.
  146. *
  147. * @api private
  148. */
  149. Request.prototype.create = function () {
  150. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  151. // SSL options for Node.js client
  152. opts.pfx = this.pfx;
  153. opts.key = this.key;
  154. opts.passphrase = this.passphrase;
  155. opts.cert = this.cert;
  156. opts.ca = this.ca;
  157. opts.ciphers = this.ciphers;
  158. opts.rejectUnauthorized = this.rejectUnauthorized;
  159. var xhr = this.xhr = new XMLHttpRequest(opts);
  160. var self = this;
  161. try {
  162. debug('xhr open %s: %s', this.method, this.uri);
  163. xhr.open(this.method, this.uri, this.async);
  164. try {
  165. if (this.extraHeaders) {
  166. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  167. for (var i in this.extraHeaders) {
  168. if (this.extraHeaders.hasOwnProperty(i)) {
  169. xhr.setRequestHeader(i, this.extraHeaders[i]);
  170. }
  171. }
  172. }
  173. } catch (e) {}
  174. if ('POST' === this.method) {
  175. try {
  176. if (this.isBinary) {
  177. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  178. } else {
  179. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  180. }
  181. } catch (e) {}
  182. }
  183. try {
  184. xhr.setRequestHeader('Accept', '*/*');
  185. } catch (e) {}
  186. // ie6 check
  187. if ('withCredentials' in xhr) {
  188. xhr.withCredentials = true;
  189. }
  190. if (this.requestTimeout) {
  191. xhr.timeout = this.requestTimeout;
  192. }
  193. if (this.hasXDR()) {
  194. xhr.onload = function () {
  195. self.onLoad();
  196. };
  197. xhr.onerror = function () {
  198. self.onError(xhr.responseText);
  199. };
  200. } else {
  201. xhr.onreadystatechange = function () {
  202. if (xhr.readyState === 2) {
  203. try {
  204. var contentType = xhr.getResponseHeader('Content-Type');
  205. if (self.supportsBinary && contentType === 'application/octet-stream') {
  206. xhr.responseType = 'arraybuffer';
  207. }
  208. } catch (e) {}
  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 (typeof document !== 'undefined') {
  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 (typeof document !== 'undefined') {
  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 typeof XDomainRequest !== 'undefined' && !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 (typeof document !== 'undefined') {
  338. if (typeof attachEvent === 'function') {
  339. attachEvent('onunload', unloadHandler);
  340. } else if (typeof addEventListener === 'function') {
  341. var terminationEvent = 'onpagehide' in self ? 'pagehide' : 'unload';
  342. addEventListener(terminationEvent, unloadHandler, false);
  343. }
  344. }
  345. function unloadHandler () {
  346. for (var i in Request.requests) {
  347. if (Request.requests.hasOwnProperty(i)) {
  348. Request.requests[i].abort();
  349. }
  350. }
  351. }