Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernize window.crypto access constants #4169

Merged
merged 12 commits into from
Apr 22, 2024
15 changes: 15 additions & 0 deletions src/crypto/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,21 @@ if (!TextEncoder) {
}
/* eslint-enable @typescript-eslint/no-var-requires */

// Service workers don't have a useful `window` instance to pull these details off of, and in at least Chrome when
// `window.$thing` is accessed, `$thing` will be non-null but complain about being undefined when accessed further.
// To avoid spurious errors, we just override the crypto bits explicitly.
if (isServiceWorker(globalThis)) {
crypto = globalThis.crypto;
subtleCrypto = globalThis.crypto.subtle ?? globalThis.crypto.webkitSubtle;
TextEncoder = globalThis.TextEncoder;
}

// Window is a close enough approximation for what we need it for.
function isServiceWorker(globalThis: any): globalThis is Window {
// Note: `skipWaiting` is a function exclusive to service workers.
return typeof globalThis["skipWaiting"] === "function";
}

export function setCrypto(_crypto: Crypto): void {
crypto = _crypto;
subtleCrypto = _crypto.subtle ?? _crypto.webkitSubtle;
Expand Down
Loading