-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
99 lines (73 loc) · 2.24 KB
/
index.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
'use strict';
var COMPLETED_READY_STATE = 4;
var RealXHRSend = XMLHttpRequest.prototype.send;
var requestCallbacks = [];
var responseCallbacks = [];
var wired = false;
function arrayRemove(array,item) {
var index = array.indexOf(item);
if (index > -1) {
array.splice(index, 1);
} else {
throw new Error("Could not remove " + item + " from array");
}
}
function fireCallbacks(callbacks,xhr) {
for( var i = 0; i < callbacks.length; i++ ) {
callbacks[i](xhr);
}
}
exports.addRequestCallback = function(callback) {
requestCallbacks.push(callback);
};
exports.removeRequestCallback = function(callback) {
arrayRemove(requestCallbacks,callback);
};
exports.addResponseCallback = function(callback) {
responseCallbacks.push(callback);
};
exports.removeResponseCallback = function(callback) {
arrayRemove(responseCallbacks,callback);
};
function fireResponseCallbacksIfCompleted(xhr) {
if( xhr.readyState === COMPLETED_READY_STATE ) {
fireCallbacks(responseCallbacks,xhr);
}
}
function proxifyOnReadyStateChange(xhr) {
var realOnReadyStateChange = xhr.onreadystatechange;
if ( realOnReadyStateChange ) {
xhr.onreadystatechange = function() {
fireResponseCallbacksIfCompleted(xhr);
realOnReadyStateChange();
};
}
}
exports.isWired = function() {
return wired;
}
exports.wire = function() {
if ( wired ) throw new Error("Ajax interceptor already wired");
// Override send method of all XHR requests
XMLHttpRequest.prototype.send = function() {
// Fire request callbacks before sending the request
fireCallbacks(requestCallbacks,this);
// Wire response callbacks
if( this.addEventListener ) {
var self = this;
this.addEventListener("readystatechange", function() {
fireResponseCallbacksIfCompleted(self);
}, false);
}
else {
proxifyOnReadyStateChange(this);
}
RealXHRSend.apply(this, arguments);
};
wired = true;
};
exports.unwire = function() {
if ( !wired ) throw new Error("Ajax interceptor not currently wired");
XMLHttpRequest.prototype.send = RealXHRSend;
wired = false;
};