Skip to content

Commit 67f7ef4

Browse files
committed
native JS fetch proxy
1 parent d6e1bd9 commit 67f7ef4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

webroot/js/inject-iframe.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,49 @@ if (elem) {
9393
};
9494
};
9595

96+
const proxyFetch = () => {
97+
if (!window.fetch) return; // in case browser doesn’t support fetch
98+
const proxied = window.fetch;
99+
100+
window.fetch = async function (...args) {
101+
const [input, init = {}] = args;
102+
const method = (init.method || 'GET').toUpperCase();
103+
const url = typeof input === 'string' ? input : input.url;
104+
105+
let response;
106+
try {
107+
response = await proxied.apply(this, args);
108+
109+
const debugId = response.headers.get('X-DEBUGKIT-ID');
110+
if (debugId) {
111+
const params = {
112+
requestId: debugId,
113+
status: response.status,
114+
date: new Date(),
115+
method,
116+
url,
117+
type: response.headers.get('Content-Type'),
118+
};
119+
iframe.contentWindow.postMessage(`ajax-completed$$${JSON.stringify(params)}`, window.location.origin);
120+
}
121+
return response;
122+
} catch (error) {
123+
// still notify iframe of a failed fetch if needed
124+
const params = {
125+
requestId: null,
126+
status: 0,
127+
date: new Date(),
128+
method,
129+
url,
130+
type: null,
131+
error: error.message,
132+
};
133+
iframe.contentWindow.postMessage(`ajax-completed$$${JSON.stringify(params)}`, window.location.origin);
134+
throw error;
135+
}
136+
};
137+
};
138+
96139
// Bind on ready callbacks to DOMContentLoaded (native js)
97140
// Since the body is already loaded (DOMContentLoaded), the event is not triggered.
98141
if (doc.addEventListener) {
@@ -104,6 +147,7 @@ if (elem) {
104147
doc.addEventListener(loadedEvent, onReady, false);
105148
doc.addEventListener(loadedEvent, proxyAjaxOpen, false);
106149
doc.addEventListener(loadedEvent, proxyAjaxSend, false);
150+
doc.addEventListener(loadedEvent, proxyFetch, false);
107151
win.debugKitListenersApplied = true;
108152
}
109153
} else {

0 commit comments

Comments
 (0)