Skip to content

Instantly share code, notes, and snippets.

@kinngh
Created December 31, 2024 11:32
Show Gist options
  • Save kinngh/7689906aedd030397effe4b3c76169dd to your computer and use it in GitHub Desktop.
Save kinngh/7689906aedd030397effe4b3c76169dd to your computer and use it in GitHub Desktop.
Make a `fetch` even if it's being overwritten
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Overwritten Fetch Example</title>
</head>
<body>
<script>
// Overwrite fetch to emulate a broken or hijacked fetch
function fetch() {
console.log("I am overwriting fetch!");
}
</script>
<script type="module" src="myscript.js"></script>
</body>
</html>
(async function () {
//Create a fallback fetch that uses XHR under the assumption that fetch is being overwriten
function fallbackFetch(url, options = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(options.method || "GET", url);
if (options.headers) {
Object.entries(options.headers).forEach(([key, value]) => {
xhr.setRequestHeader(key, value);
});
}
xhr.onload = () => {
resolve(new Response(xhr.response, { status: xhr.status }));
};
xhr.onerror = reject;
xhr.send(options.body || null);
});
}
//Check if native fetch is messed with, else use fallbackFetch
const isNative =
typeof window.fetch === "function" &&
window.fetch.toString().includes("[native code]");
const realFetch = isNative ? window.fetch : fallbackFetch;
try {
const response = await realFetch("https://example.com/api");
const data = await response.json();
console.log(data);
} catch (err) {
console.error("Error:", err);
}
})();
@kinngh
Copy link
Author

kinngh commented Dec 31, 2024

Inspired by Axel's post where an app is overwriting native fetch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment