ionic-team / capacitor

Build cross-platform Native Progressive Web Apps for iOS, Android, and the Web ⚡️
https://capacitorjs.com
MIT License
12.26k stars 1.01k forks source link

[Feature]: Expose capacitor fetch without clobbering window.fetch #7746

Open aeharding opened 2 weeks ago

aeharding commented 2 weeks ago

Description

Expose Capacitor fetch-compatible shim without overriding window.fetch

Platforms

Request or proposed solution

Right now, the only way to allow my libs to use Capacitor's fetch is enabling a native shim that clobbers fetch on the window. This can cause issues because the developer cannot control which libraries use the capacitor fetch shim, vs browser fetch.

I would like to see capactor's fetch shim exposed on window.Capacitor.fetch (or similar) so that the developer has more fine grained control over calling Capacitor's fetch, vs browser fetch.

Alternatives

A hacky workaround is saving native window.fetch, waiting for Capacitor to setup, and then saving Capacitor's window.fetch and resetting the original browser fetch. But its hacky and doesn't account for side effects like patching XHR.

Another alternative is using CapacitorHttp directly and building (and maintaining) custom shims. However this can be cumbersome to maintain and account for all the intricacies of fetching (also, some libs only allow passing a custom fetch and don't support custom adapters, like https://github.com/LemmyNet/lemmy-js-client).

Additional Information

I've experienced many bugs by enabling capacitor's clobbering of fetch and XMLHttpRequest on window, so I've turned it off.

However, I still want to access to the Capacitor fetch shim (without clobbering window.fetch) so I can use it when I want. So, in my project, I have to copy Capacitor's implementation to my codebase. This is not ideal because I have to keep it up to date:

https://github.com/aeharding/voyager/blob/2725f478526f0dab7827c303f4f8922ad377a3be/src/services/nativeFetch.ts#L13