-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitLogs.js
More file actions
73 lines (65 loc) · 2.74 KB
/
initLogs.js
File metadata and controls
73 lines (65 loc) · 2.74 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
/**
* @author: Chris Singendonk
* @description: Initializes the logging system for the application.
* - This function sets up interceptors for fetch and XMLHttpRequest to log and optionally block requests.
* - It also creates an `HttpInterceptor` instance and attaches it to the global `window.initLogs` function.
*/
function initLogs() {
console.log('Initializing logs...');
// Base Injector Class
class _Injector {
constructor() {
console.log('_Injector initialized.');
}
initFetchInterceptor() {
const originalFetch = window.fetch;
window.fetch = async (...args) => {
console.log('Intercepted Fetch Request:', args[0]);
const shouldProceed = confirm(`Allow fetch request to ${args[0]}?`);
if (!shouldProceed) {
console.log('Fetch request blocked.');
return new Response(null, { status: 403, statusText: 'Request blocked' });
}
return originalFetch(...args);
};
}
initXHRInterceptor() {
const originalXHR = window.XMLHttpRequest;
class InterceptedXHR extends originalXHR {
open(method, url, ...args) {
console.log(`Intercepted XHR Request: ${method} ${url}`);
const shouldProceed = confirm(`Allow XHR request to ${url}?`);
if (!shouldProceed) {
console.log('XHR request blocked.');
method = 'GET';
url = '/';
args = [];
}
return super.open(method, url, ...args);
}
}
window.XMLHttpRequest = InterceptedXHR;
}
}
// HTTP Interceptor Class that Extends _Injector
class HttpInterceptor extends _Injector {
constructor(serviceWorkerPath = './service-worker.js', options = {}) {
super(); // Initialize the parent class
this.serviceWorkerPath = serviceWorkerPath;
this.options = options;
this.initFetchInterceptor();
this.initXHRInterceptor();
}
}
// Attach the initLogs function to the global window object
window.initLogs = function () {
console.log('Calling initLogs from the global window object...');
const interceptor = new HttpInterceptor();
console.log('HTTP Interceptor initialized via window.initLogs.');
};
// Initialize the interceptor
const interceptor = new HttpInterceptor();
console.log('HTTP Interceptor initialized.');
}
// Run the initLogs function
initLogs();