polling-xhr.js 8.6 KB

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