Skip to content

Commit 034d9de

Browse files
authored
fix: Add a wrapper around performance for React Native (getsentry#2915)
* fix: Add a unique wrapper around performance for React Native * ref: Use getGlobalObject
1 parent 1912867 commit 034d9de

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

packages/utils/src/misc.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,13 @@ export function getGlobalObject<T>(): T & SentryGlobal {
3838
: fallbackGlobalObject) as T & SentryGlobal;
3939
}
4040

41+
/**
42+
* Determines if running in react native
43+
*/
44+
export function isReactNative(): boolean {
45+
return getGlobalObject<Window>().navigator?.product === 'ReactNative';
46+
}
47+
4148
/**
4249
* Extended Window interface that allows for Crypto API usage in IE browsers
4350
*/
@@ -260,7 +267,26 @@ const performanceFallback: CrossPlatformPerformance = {
260267
timeOrigin: INITIAL_TIME,
261268
};
262269

270+
/**
271+
* Performance wrapper for react native as performance.now() has been found to start off with an unusual offset.
272+
*/
273+
function getReactNativePerformanceWrapper(): CrossPlatformPerformance {
274+
const INITIAL_OFFSET = performance.now();
275+
276+
return {
277+
now(): number {
278+
return performance.now() - INITIAL_OFFSET;
279+
},
280+
timeOrigin: INITIAL_TIME,
281+
};
282+
}
283+
263284
export const crossPlatformPerformance: CrossPlatformPerformance = ((): CrossPlatformPerformance => {
285+
// React Native's performance.now() starts with a gigantic offset, so we need to wrap it.
286+
if (isReactNative()) {
287+
return getReactNativePerformanceWrapper();
288+
}
289+
264290
if (isNodeEnv()) {
265291
try {
266292
const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: CrossPlatformPerformance };

0 commit comments

Comments
 (0)