forked from slorber/ajax-interceptor
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
52 lines (40 loc) · 1.28 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
'use strict';
const XMLHttpRequestSend = XMLHttpRequest.prototype.send;
var reqCallbacks = [];
var resCallbacks = [];
var wired = false;
export function isWired() {
return wired;
};
export function addRequestCallback(callback) {
reqCallbacks.push(callback);
};
export function addResponseCallback(callback) {
resCallbacks.push(callback);
};
export function removeRequestCallback(callback) {
reqCallbacks = reqCallbacks.filter(item => item !== callback);
};
export function removeResponseCallback(callback) {
resCallbacks = resCallbacks.filter(item => item !== callback);
};
export function wire() {
if (wired) { throw new Error('Ajax interceptor already wired'); }
XMLHttpRequest.prototype.send = function() {
var reqCallbacksRes = reqCallbacks.map(callback => callback(this, arguments));
var onreadystatechange = this.onreadystatechange;
this.onreadystatechange = () => {
resCallbacks.forEach(callback => {callback(this)});
onreadystatechange(this);
};
if (reqCallbacksRes.indexOf(false) === -1) {
XMLHttpRequestSend.apply(this, arguments);
}
};
wired = true;
};
export function unwire() {
if (!wired) { throw new Error('Ajax interceptor not currently wired'); }
XMLHttpRequest.prototype.send = XMLHttpRequestSend;
wired = false;
};