-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnet-hook.js
More file actions
81 lines (69 loc) · 2.09 KB
/
net-hook.js
File metadata and controls
81 lines (69 loc) · 2.09 KB
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
// * ------------------------------------------------ fetch hook
/**
* @typedef {(url: RequestInfo | URL, response: Response) => void} FetchHandler
*/
if (!globalThis.fetchHook) {
globalThis.fetchHook = (() => {
/** @type {Set<FetchHandler>} */
const handlers = new Set();
const originalFetch = globalThis.fetch;
globalThis.fetch = (url, options) => {
return originalFetch(url, options).then(async (response) => {
handlers.forEach((h) => {
try {
h(url, response.clone());
} catch (err) {
console.error(err);
}
});
return response;
});
};
return {
/** @param {FetchHandler} handler */
add: (handler) => handlers.add(handler),
/** @param {FetchHandler} handler */
remove: (handler) => handlers.delete(handler),
};
})();
}
/**
* fetch response 中间件
* @type {{ add: (handler: FetchHandler) => void, remove: (handler: FetchHandler) => void }}
*/
var fetchHook = globalThis.fetchHook;
// * ------------------------------------------------ xhr hook
/**
* @typedef {(xhr: XMLHttpRequest) => void} XhrHandler
*/
if (!globalThis.xhrHook) {
globalThis.xhrHook = (() => {
if (!globalThis.XMLHttpRequest) return { add: () => {}, remove: () => {} };
/** @type {Set<XhrHandler>} */
const handlers = new Set();
const originalSend = globalThis.XMLHttpRequest.prototype.send;
globalThis.XMLHttpRequest.prototype.send = function () {
this.addEventListener("load", () => {
handlers.forEach((h) => {
try {
h(this);
} catch (err) {
console.error(err);
}
});
});
return originalSend.apply(this, arguments);
};
return {
/** @param {XhrHandler} handler */
add: (handler) => handlers.add(handler),
/** @param {XhrHandler} handler */
remove: (handler) => handlers.delete(handler),
};
})();
}
/**
* xhr response 中间件
* @type {{ add: (handler: XhrHandler) => void, remove: (handler: XhrHandler) => void }}
*/
var xhrHook = globalThis.xhrHook;