the Fetch API is totally mutable and can be replaced or removed by doing
window.fetch = null;
or,
var fetch = null;
or, the fetch property can be removed as well.
delete window.fetch;
This means, if a legacy code defines a global variable named fetch
, the fetch API cannot be used.
Is there any way to access the original fetch
function in JavaScript?
the Fetch API is totally mutable and can be replaced or removed by doing
window.fetch = null;
or,
var fetch = null;
or, the fetch property can be removed as well.
delete window.fetch;
This means, if a legacy code defines a global variable named fetch
, the fetch API cannot be used.
Is there any way to access the original fetch
function in JavaScript?
- maybe by somehow assigning fetch to your own reference before the nasty lib messes up with window ? – 36ve Commented Apr 16, 2021 at 8:53
- const fetch = window.fetch // window.fetch = null // use your own fetch – 36ve Commented Apr 16, 2021 at 8:53
3 Answers
Reset to default 7I appreciate your answers but none of you answered the question properly. The fetch
function is already erased and we have no way to access it. In this case we can use the following simple hack.
This will hand us the original fetch function.
function restoreFetch() {
if (!window._restoredFetch) {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe); // add element
window._restoredFetch = iframe.contentWindow.fetch;
}
return window._restoredFetch;
}
Then, we can use the fetch API:
const f = restoreFetch();
const result = await f('https://stackoverflow.');
Once you delete from window object it won't be available any more... but You can use pollyfill to import fetch https://github./github/fetch#importing
import {fetch as fetchPolyfill} from 'whatwg-fetch'
window.fetch(...) // use native browser version
fetchPolyfill(...) // use polyfill implementation
If you're not using packages then I can only remend one thing. As a first script tag you can do something like:
<script>
window.MYFETCH = window.fetch;
</script>
I know it's not perfect but then you can just use MYFETCH wherever you need it.