From b09414285d5c27cf76a9ff72cbb5ffe8ecec3981 Mon Sep 17 00:00:00 2001 From: hibrandonevans <112993120+hibrandonevans@users.noreply.github.com> Date: Wed, 22 Nov 2023 15:26:56 +0800 Subject: [PATCH] fix: improve environment detection in is-browser utility (#1744) --- src/lib/is-browser.ts | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/lib/is-browser.ts b/src/lib/is-browser.ts index 6252d810d..f4e32d20e 100644 --- a/src/lib/is-browser.ts +++ b/src/lib/is-browser.ts @@ -1,11 +1,18 @@ -const isBrowser = - (typeof window !== 'undefined' && typeof window.document !== 'undefined') || - // eslint-disable-next-line no-restricted-globals - (typeof self === 'object' && - // eslint-disable-next-line no-restricted-globals - self.constructor && +const isStandardBrowserEnv = () => + typeof window !== 'undefined' && typeof window.document !== 'undefined' + +const isWebWorkerEnv = () => + Boolean( // eslint-disable-next-line no-restricted-globals - self.constructor.name === 'DedicatedWorkerGlobalScope') || // is web worker - (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') // while navigator.product is deprecated + typeof self === 'object' && + // eslint-disable-next-line no-restricted-globals + self?.constructor?.name?.includes('WorkerGlobalScope'), + ) + +const isReactNativeEnv = () => + typeof navigator !== 'undefined' && navigator.product === 'ReactNative' + +const isBrowser = + isStandardBrowserEnv() || isWebWorkerEnv() || isReactNativeEnv() export default isBrowser