diff --git a/packages/browser/src/sdk.ts b/packages/browser/src/sdk.ts index 4dd323c6aa02..1421814ae9e5 100644 --- a/packages/browser/src/sdk.ts +++ b/packages/browser/src/sdk.ts @@ -72,7 +72,12 @@ type Runtime = { }; function shouldShowBrowserExtensionError(): boolean { - const windowWithMaybeExtension = WINDOW as typeof WINDOW & ExtensionProperties; + const windowWithMaybeExtension = + typeof WINDOW.window !== 'undefined' && (WINDOW as typeof WINDOW & ExtensionProperties); + if (!windowWithMaybeExtension) { + // No need to show the error if we're not in a browser window environment (e.g. service workers) + return false; + } const extensionKey = windowWithMaybeExtension.chrome ? 'chrome' : 'browser'; const extensionObject = windowWithMaybeExtension[extensionKey]; diff --git a/packages/browser/test/sdk.test.ts b/packages/browser/test/sdk.test.ts index 31178bc84423..80e54e3d49d2 100644 --- a/packages/browser/test/sdk.test.ts +++ b/packages/browser/test/sdk.test.ts @@ -149,6 +149,7 @@ describe('init', () => { Object.defineProperty(WINDOW, 'chrome', { value: undefined, writable: true }); Object.defineProperty(WINDOW, 'browser', { value: undefined, writable: true }); Object.defineProperty(WINDOW, 'nw', { value: undefined, writable: true }); + Object.defineProperty(WINDOW, 'window', { value: WINDOW, writable: true }); }); it('logs a browser extension error if executed inside a Chrome extension', () => { @@ -229,6 +230,18 @@ describe('init', () => { consoleErrorSpy.mockRestore(); }); + it("doesn't log a browser extension error if the `window` object isn't defined", () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + + Object.defineProperty(WINDOW, 'window', { value: undefined }); + + init(options); + + expect(consoleErrorSpy).not.toHaveBeenCalled(); + + consoleErrorSpy.mockRestore(); + }); + it("doesn't return a client on initialization error", () => { const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});