`Fetch` API Overridden. How do I access the original function?

Viewed 540

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?

3 Answers

I 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');

        window._restoredFetch = iframe.contentWindow.fetch;
    }

    return window._restoredFetch;
}

The we can use the fetch API:

const f = restoreFetch();

const result = await f('https://stackoverflow.com');

Once you delete from window object it won't be available any more... but You can use pollyfill to import fetch https://github.com/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 recommend 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.

Related