From 4ba63acc107fdd0a6d6ef3e27349e65edb007447 Mon Sep 17 00:00:00 2001 From: Richard Moore Date: Fri, 24 Dec 2021 02:05:10 -0500 Subject: [PATCH] Fix browser random in WebWorkers (#2405). --- packages/random/src.ts/browser-random.ts | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/packages/random/src.ts/browser-random.ts b/packages/random/src.ts/browser-random.ts index d169f78d4..fe58a287c 100644 --- a/packages/random/src.ts/browser-random.ts +++ b/packages/random/src.ts/browser-random.ts @@ -9,18 +9,15 @@ const logger = new Logger(version); // Debugging line for testing browser lib in node //const window = { crypto: { getRandomValues: () => { } } }; -let anyGlobal: any = null; -try { - anyGlobal = (window as any); - if (anyGlobal == null) { throw new Error("try next"); } -} catch (error) { - try { - anyGlobal = (global as any); - if (anyGlobal == null) { throw new Error("try next"); } - } catch (error) { - anyGlobal = { }; - } -} +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis +function getGlobal(): any { + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +}; + +const anyGlobal = getGlobal(); let crypto: any = anyGlobal.crypto || anyGlobal.msCrypto; if (!crypto || !crypto.getRandomValues) {