最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - `Fetch` API Overridden. How do I access the original function? - Stack Overflow

programmeradmin3浏览0评论

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?

Share Improve this question asked Apr 16, 2021 at 8:45 MicrotributeMicrotribute 1,06213 silver badges25 bronze badges 2
  • 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
Add a ment  | 

3 Answers 3

Reset to default 7

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); // 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.

发布评论

评论列表(0)

  1. 暂无评论