Skip to content

Commit 2d6196b

Browse files
authored
ref: Add fast-path to fetchImpl and cleanup redundant iframe (#3341)
* ref: Add fast-path to fetchImpl * fix: Cleanup after fetch impl detection
1 parent bcac95d commit 2d6196b

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

packages/browser/src/transports/fetch.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';
22
import { Event, Response, SentryRequest, Session, TransportOptions } from '@sentry/types';
3-
import { getGlobalObject, logger, supportsReferrerPolicy, SyncPromise } from '@sentry/utils';
3+
import { getGlobalObject, isNativeFetch, logger, supportsReferrerPolicy, SyncPromise } from '@sentry/utils';
44

55
import { BaseTransport } from './base';
66

@@ -45,24 +45,33 @@ type FetchImpl = typeof fetch;
4545
* Safari: resource blocked by content blocker
4646
*/
4747
function getNativeFetchImplementation(): FetchImpl {
48-
// Make sure that the fetch we use is always the native one.
48+
/* eslint-disable @typescript-eslint/unbound-method */
49+
50+
// Fast path to avoid DOM I/O
4951
const global = getGlobalObject<Window>();
52+
if (isNativeFetch(global.fetch)) {
53+
return global.fetch.bind(global);
54+
}
55+
5056
const document = global.document;
57+
let fetchImpl = global.fetch;
5158
// eslint-disable-next-line deprecation/deprecation
5259
if (typeof document?.createElement === `function`) {
5360
try {
5461
const sandbox = document.createElement('iframe');
5562
sandbox.hidden = true;
5663
document.head.appendChild(sandbox);
5764
if (sandbox.contentWindow?.fetch) {
58-
return sandbox.contentWindow.fetch.bind(global);
65+
fetchImpl = sandbox.contentWindow.fetch;
5966
}
6067
document.head.removeChild(sandbox);
6168
} catch (e) {
6269
logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);
6370
}
6471
}
65-
return global.fetch.bind(global);
72+
73+
return fetchImpl.bind(global);
74+
/* eslint-enable @typescript-eslint/unbound-method */
6675
}
6776

6877
/** `fetch` based transport */

packages/utils/src/supports.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ export function supportsFetch(): boolean {
7373
* isNativeFetch checks if the given function is a native implementation of fetch()
7474
*/
7575
// eslint-disable-next-line @typescript-eslint/ban-types
76-
function isNativeFetch(func: Function): boolean {
76+
export function isNativeFetch(func: Function): boolean {
7777
return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
7878
}
7979

0 commit comments

Comments
 (0)