Skip to content

Commit

Permalink
fix: browser detection (#8315)
Browse files Browse the repository at this point in the history
Update browser detection logic: Detect either window or web worker (WorkerGlobalScope).
This updates the implementation to `isBrowser()` and adds a new function `isWebWorker()`.

Fixes #8299 #8284
  • Loading branch information
JoseVSeb committed Jun 28, 2024
1 parent ecadbe3 commit 192561b
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilly-moons-play.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@firebase/util': patch
---

fix: browser detection (detect either window or web worker)
5 changes: 5 additions & 0 deletions .changeset/fifty-mayflies-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@firebase/app': patch
---

fix: server app should initialize in web workers
9 changes: 7 additions & 2 deletions packages/app/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,12 @@ import {
LogOptions,
setUserLogHandler
} from '@firebase/logger';
import { deepEqual, getDefaultAppConfig, isBrowser } from '@firebase/util';
import {
deepEqual,
getDefaultAppConfig,
isBrowser,
isWebWorker
} from '@firebase/util';

export { FirebaseError } from '@firebase/util';

Expand Down Expand Up @@ -230,7 +235,7 @@ export function initializeServerApp(
_options: FirebaseOptions | FirebaseApp,
_serverAppConfig: FirebaseServerAppSettings
): FirebaseServerApp {
if (isBrowser()) {
if (isBrowser() && !isWebWorker()) {
// FirebaseServerApp isn't designed to be run in browsers.
throw ERROR_FACTORY.create(AppError.INVALID_SERVER_APP_ENVIRONMENT);
}
Expand Down
18 changes: 17 additions & 1 deletion packages/util/src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
import { CONSTANTS } from './constants';
import { getDefaults } from './defaults';

/**
* Type placeholder for `WorkerGlobalScope` from `webworker`
*/
declare class WorkerGlobalScope {}

/**
* Returns navigator.userAgent string or '' if it's not defined.
* @return user agent string
Expand Down Expand Up @@ -77,7 +82,18 @@ export function isNode(): boolean {
* Detect Browser Environment
*/
export function isBrowser(): boolean {
return typeof self === 'object' && self.self === self;
return typeof window !== 'undefined' || isWebWorker();
}

/**
* Detect Web Worker context
*/
export function isWebWorker(): boolean {
return (
typeof WorkerGlobalScope !== 'undefined' &&
typeof self !== 'undefined' &&
self instanceof WorkerGlobalScope
);
}

/**
Expand Down

0 comments on commit 192561b

Please sign in to comment.