Created
December 31, 2024 11:32
-
-
Save kinngh/7689906aedd030397effe4b3c76169dd to your computer and use it in GitHub Desktop.
Make a `fetch` even if it's being overwritten
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by Axel's post where an app is overwriting native
fetch
.