Skip to content

Commit 18a12ba

Browse files
authored
fix(utils): Better native fetch detection via iframes (#2103)
Fixes #1601
1 parent 9af6477 commit 18a12ba

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
- [integrations] fix: Tracing integration fetch headers bug.
66
- [node] fix: Force agent-base to be at version 4.3.0 to fix various issues. Fix #1762, fix #2085
7+
- [utils] fix: Better native `fetch` detection via iframes. Fix #1601
78

89
## 5.4.0
910

packages/utils/src/supports.ts

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { getGlobalObject } from './misc';
2+
import { logger } from './logger';
23

34
/**
45
* Tells whether current environment supports ErrorEvent objects
@@ -80,14 +81,38 @@ export function supportsFetch(): boolean {
8081
* Tells whether current environment supports Fetch API natively
8182
* {@link supportsNativeFetch}.
8283
*
83-
* @returns Answer to the given question.
84+
* @returns true if `window.fetch` is natively implemented, false otherwise
8485
*/
8586
export function supportsNativeFetch(): boolean {
8687
if (!supportsFetch()) {
8788
return false;
8889
}
90+
91+
const isNativeFunc = (func: Function) => func.toString().indexOf('native') !== -1;
8992
const global = getGlobalObject<Window>();
90-
return global.fetch.toString().indexOf('native') !== -1;
93+
let result = null;
94+
const doc = global.document;
95+
if (doc) {
96+
const sandbox = doc.createElement('iframe');
97+
sandbox.hidden = true;
98+
try {
99+
doc.head.appendChild(sandbox);
100+
if (sandbox.contentWindow && sandbox.contentWindow.fetch) {
101+
// tslint:disable-next-line no-unbound-method
102+
result = isNativeFunc(sandbox.contentWindow.fetch);
103+
}
104+
doc.head.removeChild(sandbox);
105+
} catch (err) {
106+
logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);
107+
}
108+
}
109+
110+
if (result === null) {
111+
// tslint:disable-next-line no-unbound-method
112+
result = isNativeFunc(global.fetch);
113+
}
114+
115+
return result;
91116
}
92117

93118
/**

0 commit comments

Comments
 (0)