Initial commit of template
This commit is contained in:
51
scripts/network-interceptor.ts
Normal file
51
scripts/network-interceptor.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
if (typeof window !== 'undefined') {
|
||||
const _origFetch = window.fetch;
|
||||
if (typeof _origFetch === 'function' && !(window as any).__noahNetworkPatched) {
|
||||
(window as any).__noahNetworkPatched = true;
|
||||
(window as any).__noahOrigFetch = _origFetch;
|
||||
window.fetch = function (input: any, init?: any) {
|
||||
let url = 'unknown';
|
||||
try { url = input instanceof Request ? input.url : String(input); } catch (_) {}
|
||||
const method = ((input instanceof Request ? input.method : init?.method) || 'GET').toUpperCase();
|
||||
const start = Date.now();
|
||||
const post = (status: number, statusText: string, error: string | null) => {
|
||||
try {
|
||||
window.parent?.postMessage(
|
||||
{type: 'iframe-network', data: {method, url, status, statusText, duration: Date.now() - start, requestBody: null, responseBody: null, error, timestamp: Date.now()}},
|
||||
'*'
|
||||
);
|
||||
} catch (_) {}
|
||||
};
|
||||
let promise: Promise<Response>;
|
||||
try { promise = _origFetch.apply(this, arguments as any); }
|
||||
catch (e: any) { post(0, '', e?.message || String(e)); throw e; }
|
||||
return promise.then(
|
||||
(resp) => { post(resp.status, resp.statusText, null); return resp; },
|
||||
(err: any) => { post(0, '', err?.message || String(err)); throw err; }
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof XMLHttpRequest !== 'undefined' && !(window as any).__noahXHRPatched) {
|
||||
(window as any).__noahXHRPatched = true;
|
||||
const _open = XMLHttpRequest.prototype.open;
|
||||
const _send = XMLHttpRequest.prototype.send;
|
||||
XMLHttpRequest.prototype.open = function (method: string, url: string) {
|
||||
(this as any)._noahMethod = method;
|
||||
(this as any)._noahUrl = url;
|
||||
(this as any)._noahStart = Date.now();
|
||||
return _open.apply(this, arguments as any);
|
||||
};
|
||||
XMLHttpRequest.prototype.send = function () {
|
||||
this.addEventListener('loadend', () => {
|
||||
try {
|
||||
window.parent?.postMessage(
|
||||
{type: 'iframe-network', data: {method: (this as any)._noahMethod || 'GET', url: (this as any)._noahUrl || '', status: this.status, statusText: this.statusText, duration: Date.now() - ((this as any)._noahStart || Date.now()), requestBody: null, responseBody: null, error: this.status === 0 ? 'Network error' : null, timestamp: Date.now()}},
|
||||
'*'
|
||||
);
|
||||
} catch (_) {}
|
||||
});
|
||||
return _send.apply(this, arguments as any);
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user