forked from ilinsky/xmlhttprequest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLHttpRequest.js
executable file
·531 lines (455 loc) · 15.4 KB
/
XMLHttpRequest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/**
* XMLHttpRequest.js Copyright (C) 2011 Sergey Ilinsky (http://www.ilinsky.com)
*
* This work is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This work is distributed in the hope that it will be useful,
* but without any warranty; without even the implied warranty of
* merchantability or fitness for a particular purpose. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
(function () {
// Save reference to earlier defined object implementation (if any)
var oXMLHttpRequest = window.XMLHttpRequest;
// Define on browser type
var bGecko = !!window.controllers;
var bIE = !!window.document.namespaces;
var bIE7 = bIE && window.navigator.userAgent.match(/MSIE 7.0/);
// Enables "XMLHttpRequest()" call next to "new XMLHttpRequest()"
function fXMLHttpRequest() {
this._object = oXMLHttpRequest && !bIE7 ? new oXMLHttpRequest : new window.ActiveXObject("Microsoft.XMLHTTP");
this._listeners = [];
}
// Constructor
function cXMLHttpRequest() {
return new fXMLHttpRequest;
}
cXMLHttpRequest.prototype = fXMLHttpRequest.prototype;
// BUGFIX: Firefox with Firebug installed would break pages if not executed
if (bGecko && oXMLHttpRequest.wrapped) {
cXMLHttpRequest.wrapped = oXMLHttpRequest.wrapped;
}
// Constants
cXMLHttpRequest.UNSENT = 0;
cXMLHttpRequest.OPENED = 1;
cXMLHttpRequest.HEADERS_RECEIVED = 2;
cXMLHttpRequest.LOADING = 3;
cXMLHttpRequest.DONE = 4;
// Interface level constants
cXMLHttpRequest.prototype.UNSENT = cXMLHttpRequest.UNSENT;
cXMLHttpRequest.prototype.OPENED = cXMLHttpRequest.OPENED;
cXMLHttpRequest.prototype.HEADERS_RECEIVED = cXMLHttpRequest.HEADERS_RECEIVED;
cXMLHttpRequest.prototype.LOADING = cXMLHttpRequest.LOADING;
cXMLHttpRequest.prototype.DONE = cXMLHttpRequest.DONE;
// Public Properties
cXMLHttpRequest.prototype.readyState = cXMLHttpRequest.UNSENT;
cXMLHttpRequest.prototype.responseText = '';
cXMLHttpRequest.prototype.responseXML = null;
cXMLHttpRequest.prototype.status = 0;
cXMLHttpRequest.prototype.statusText = '';
// Priority proposal
cXMLHttpRequest.prototype.priority = "NORMAL";
// Instance-level Events Handlers
cXMLHttpRequest.prototype.onreadystatechange = null;
// Class-level Events Handlers
cXMLHttpRequest.onreadystatechange = null;
cXMLHttpRequest.onopen = null;
cXMLHttpRequest.onsend = null;
cXMLHttpRequest.onabort = null;
// Public Methods
cXMLHttpRequest.prototype.open = function(sMethod, sUrl, bAsync, sUser, sPassword) {
// http://www.w3.org/TR/XMLHttpRequest/#the-open-method
var sLowerCaseMethod = sMethod.toLowerCase();
if (sLowerCaseMethod == "connect" || sLowerCaseMethod == "trace" || sLowerCaseMethod == "track") {
// Using a generic error and an int - not too sure all browsers support correctly
// http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#securityerror, so, this is safer
// XXX should do better than that, but this is OT to XHR.
throw new Error(18);
}
// Delete headers, required when object is reused
delete this._headers;
// When bAsync parameter value is omitted, use true as default
if (arguments.length < 3) {
bAsync = true;
}
// Save async parameter for fixing Gecko bug with missing readystatechange in synchronous requests
this._async = bAsync;
// Set the onreadystatechange handler
var oRequest = this;
var nState = this.readyState;
var fOnUnload = null;
// BUGFIX: IE - memory leak on page unload (inter-page leak)
if (bIE && bAsync) {
fOnUnload = function() {
if (nState != cXMLHttpRequest.DONE) {
fCleanTransport(oRequest);
// Safe to abort here since onreadystatechange handler removed
oRequest.abort();
}
};
window.attachEvent("onunload", fOnUnload);
}
// Add method sniffer
if (cXMLHttpRequest.onopen) {
cXMLHttpRequest.onopen.apply(this, arguments);
}
if (arguments.length > 4) {
this._object.open(sMethod, sUrl, bAsync, sUser, sPassword);
} else if (arguments.length > 3) {
this._object.open(sMethod, sUrl, bAsync, sUser);
} else {
this._object.open(sMethod, sUrl, bAsync);
}
this.readyState = cXMLHttpRequest.OPENED;
fReadyStateChange(this);
this._object.onreadystatechange = function() {
if (bGecko && !bAsync) {
return;
}
// Synchronize state
oRequest.readyState = oRequest._object.readyState;
fSynchronizeValues(oRequest);
// BUGFIX: Firefox fires unnecessary DONE when aborting
if (oRequest._aborted) {
// Reset readyState to UNSENT
oRequest.readyState = cXMLHttpRequest.UNSENT;
// Return now
return;
}
if (oRequest.readyState == cXMLHttpRequest.DONE) {
// Free up queue
delete oRequest._data;
// Uncomment these lines for bAsync
/**
* if (bAsync) {
* fQueue_remove(oRequest);
* }
*/
fCleanTransport(oRequest);
// Uncomment this block if you need a fix for IE cache
/**
* // BUGFIX: IE - cache issue
* if (!oRequest._object.getResponseHeader("Date")) {
* // Save object to cache
* oRequest._cached = oRequest._object;
*
* // Instantiate a new transport object
* cXMLHttpRequest.call(oRequest);
*
* // Re-send request
* if (sUser) {
* if (sPassword) {
* oRequest._object.open(sMethod, sUrl, bAsync, sUser, sPassword);
* } else {
* oRequest._object.open(sMethod, sUrl, bAsync);
* }
*
* oRequest._object.setRequestHeader("If-Modified-Since", oRequest._cached.getResponseHeader("Last-Modified") || new window.Date(0));
* // Copy headers set
* if (oRequest._headers) {
* for (var sHeader in oRequest._headers) {
* // Some frameworks prototype objects with functions
* if (typeof oRequest._headers[sHeader] == "string") {
* oRequest._object.setRequestHeader(sHeader, oRequest._headers[sHeader]);
* }
* }
* }
* oRequest._object.onreadystatechange = function() {
* // Synchronize state
* oRequest.readyState = oRequest._object.readyState;
*
* if (oRequest._aborted) {
* //
* oRequest.readyState = cXMLHttpRequest.UNSENT;
*
* // Return
* return;
* }
*
* if (oRequest.readyState == cXMLHttpRequest.DONE) {
* // Clean Object
* fCleanTransport(oRequest);
*
* // get cached request
* if (oRequest.status == 304) {
* oRequest._object = oRequest._cached;
* }
*
* //
* delete oRequest._cached;
*
* //
* fSynchronizeValues(oRequest);
*
* //
* fReadyStateChange(oRequest);
*
* // BUGFIX: IE - memory leak in interrupted
* if (bIE && bAsync) {
* window.detachEvent("onunload", fOnUnload);
* }
*
* }
* };
* oRequest._object.send(null);
*
* // Return now - wait until re-sent request is finished
* return;
* };
*/
// BUGFIX: IE - memory leak in interrupted
if (bIE && bAsync) {
window.detachEvent("onunload", fOnUnload);
}
// BUGFIX: Some browsers (Internet Explorer, Gecko) fire OPEN readystate twice
if (nState != oRequest.readyState) {
fReadyStateChange(oRequest);
}
nState = oRequest.readyState;
}
};
};
cXMLHttpRequest.prototype.send = function(vData) {
// Add method sniffer
if (cXMLHttpRequest.onsend) {
cXMLHttpRequest.onsend.apply(this, arguments);
}
if (!arguments.length) {
vData = null;
}
// BUGFIX: Safari - fails sending documents created/modified dynamically, so an explicit serialization required
// BUGFIX: IE - rewrites any custom mime-type to "text/xml" in case an XMLNode is sent
// BUGFIX: Gecko - fails sending Element (this is up to the implementation either to standard)
if (vData && vData.nodeType) {
vData = window.XMLSerializer ? new window.XMLSerializer().serializeToString(vData) : vData.xml;
if (!this._headers["Content-Type"]) {
this._object.setRequestHeader("Content-Type", "application/xml");
}
}
this._data = vData;
/**
* // Add to queue
* if (this._async) {
* fQueue_add(this);
* } else { */
fXMLHttpRequest_send(this);
/**
* }
*/
};
cXMLHttpRequest.prototype.abort = function() {
// Add method sniffer
if (cXMLHttpRequest.onabort) {
cXMLHttpRequest.onabort.apply(this, arguments);
}
// BUGFIX: Gecko - unnecessary DONE when aborting
if (this.readyState > cXMLHttpRequest.UNSENT) {
this._aborted = true;
}
this._object.abort();
// BUGFIX: IE - memory leak
fCleanTransport(this);
this.readyState = cXMLHttpRequest.UNSENT;
delete this._data;
/* if (this._async) {
* fQueue_remove(this);
* }
*/
};
cXMLHttpRequest.prototype.getAllResponseHeaders = function() {
return this._object.getAllResponseHeaders();
};
cXMLHttpRequest.prototype.getResponseHeader = function(sName) {
return this._object.getResponseHeader(sName);
};
cXMLHttpRequest.prototype.setRequestHeader = function(sName, sValue) {
// BUGFIX: IE - cache issue
if (!this._headers) {
this._headers = {};
}
this._headers[sName] = sValue;
return this._object.setRequestHeader(sName, sValue);
};
cXMLHttpRequest.prototype.overrideMimeType = function(sMimeType) {
if (this._object.overrideMimeType) {
return this._object.overrideMimeType(sMimeType);
}
};
// EventTarget interface implementation
cXMLHttpRequest.prototype.addEventListener = function(sName, fHandler, bUseCapture) {
for (var nIndex = 0, oListener; oListener = this._listeners[nIndex]; nIndex++) {
if (oListener[0] == sName && oListener[1] == fHandler && oListener[2] == bUseCapture) {
return;
}
}
// Add listener
this._listeners.push([sName, fHandler, bUseCapture]);
};
cXMLHttpRequest.prototype.removeEventListener = function(sName, fHandler, bUseCapture) {
for (var nIndex = 0, oListener; oListener = this._listeners[nIndex]; nIndex++) {
if (oListener[0] == sName && oListener[1] == fHandler && oListener[2] == bUseCapture) {
break;
}
}
// Remove listener
if (oListener) {
this._listeners.splice(nIndex, 1);
}
};
cXMLHttpRequest.prototype.dispatchEvent = function(oEvent) {
var oEventPseudo = {
'type': oEvent.type,
'target': this,
'currentTarget': this,
'eventPhase': 2,
'bubbles': oEvent.bubbles,
'cancelable': oEvent.cancelable,
'timeStamp': oEvent.timeStamp,
'stopPropagation': function() {}, // There is no flow
'preventDefault': function() {}, // There is no default action
'initEvent': function() {} // Original event object should be initialized
};
// Execute onreadystatechange
if (oEventPseudo.type == "readystatechange" && this.onreadystatechange) {
(this.onreadystatechange.handleEvent || this.onreadystatechange).apply(this, [oEventPseudo]);
}
// Execute listeners
for (var nIndex = 0, oListener; oListener = this._listeners[nIndex]; nIndex++) {
if (oListener[0] == oEventPseudo.type && !oListener[2]) {
(oListener[1].handleEvent || oListener[1]).apply(this, [oEventPseudo]);
}
}
};
//
cXMLHttpRequest.prototype.toString = function() {
return '[' + "object" + ' ' + "XMLHttpRequest" + ']';
};
cXMLHttpRequest.toString = function() {
return '[' + "XMLHttpRequest" + ']';
};
/**
* // Queue manager
* var oQueuePending = {"CRITICAL":[],"HIGH":[],"NORMAL":[],"LOW":[],"LOWEST":[]},
* aQueueRunning = [];
* function fQueue_add(oRequest) {
* oQueuePending[oRequest.priority in oQueuePending ? oRequest.priority : "NORMAL"].push(oRequest);
* //
* setTimeout(fQueue_process);
* };
*
* function fQueue_remove(oRequest) {
* for (var nIndex = 0, bFound = false; nIndex < aQueueRunning.length; nIndex++)
* if (bFound) {
* aQueueRunning[nIndex - 1] = aQueueRunning[nIndex];
* } else {
* if (aQueueRunning[nIndex] == oRequest) {
* bFound = true;
* }
* }
*
* if (bFound) {
* aQueueRunning.length--;
* }
*
*
* //
* setTimeout(fQueue_process);
* };
*
* function fQueue_process() {
* if (aQueueRunning.length < 6) {
* for (var sPriority in oQueuePending) {
* if (oQueuePending[sPriority].length) {
* var oRequest = oQueuePending[sPriority][0];
* oQueuePending[sPriority] = oQueuePending[sPriority].slice(1);
* //
* aQueueRunning.push(oRequest);
* // Send request
* fXMLHttpRequest_send(oRequest);
* break;
* }
* }
* }
* };
*/
// Helper function
function fXMLHttpRequest_send(oRequest) {
oRequest._object.send(oRequest._data);
// BUGFIX: Gecko - missing readystatechange calls in synchronous requests
if (bGecko && !oRequest._async) {
oRequest.readyState = cXMLHttpRequest.OPENED;
// Synchronize state
fSynchronizeValues(oRequest);
// Simulate missing states
while (oRequest.readyState < cXMLHttpRequest.DONE) {
oRequest.readyState++;
fReadyStateChange(oRequest);
// Check if we are aborted
if (oRequest._aborted) {
return;
}
}
}
}
function fReadyStateChange(oRequest) {
// Sniffing code
if (cXMLHttpRequest.onreadystatechange){
cXMLHttpRequest.onreadystatechange.apply(oRequest);
}
// Fake event
oRequest.dispatchEvent({
'type': "readystatechange",
'bubbles': false,
'cancelable': false,
'timeStamp': new Date + 0
});
}
function fGetDocument(oRequest) {
var oDocument = oRequest.responseXML;
var sResponse = oRequest.responseText;
// Try parsing responseText
if (bIE && sResponse && oDocument && !oDocument.documentElement && oRequest.getResponseHeader("Content-Type").match(/[^\/]+\/[^\+]+\+xml/)) {
oDocument = new window.ActiveXObject("Microsoft.XMLDOM");
oDocument.async = false;
oDocument.validateOnParse = false;
oDocument.loadXML(sResponse);
}
// Check if there is no error in document
if (oDocument){
if ((bIE && oDocument.parseError !== 0) || !oDocument.documentElement || (oDocument.documentElement && oDocument.documentElement.tagName == "parsererror")) {
return null;
}
}
return oDocument;
}
function fSynchronizeValues(oRequest) {
try { oRequest.responseText = oRequest._object.responseText; } catch (e) {}
try { oRequest.responseXML = fGetDocument(oRequest._object); } catch (e) {}
try { oRequest.status = oRequest._object.status; } catch (e) {}
try { oRequest.statusText = oRequest._object.statusText; } catch (e) {}
}
function fCleanTransport(oRequest) {
// BUGFIX: IE - memory leak (on-page leak)
oRequest._object.onreadystatechange = new window.Function;
}
// Internet Explorer 5.0 (missing apply)
if (!window.Function.prototype.apply) {
window.Function.prototype.apply = function(oRequest, oArguments) {
if (!oArguments) {
oArguments = [];
}
oRequest.__func = this;
oRequest.__func(oArguments[0], oArguments[1], oArguments[2], oArguments[3], oArguments[4]);
delete oRequest.__func;
};
}
// Register new object with window
window.XMLHttpRequest = cXMLHttpRequest;
})();