Skip to content

Commit 73ca138

Browse files
authored
fix(browser): Avoid showing browser extension error message in non-window global scopes (#13156)
Relax our browser extension detection check to avoid showing the error message and blocking `Sentry.init` if the SDK is not initialized in a `window` global scope. For instance, this will allow `Sentry.init` to be executed in (service) workers. We likely don't need to worry about multiple SDK instance collisions in non-`window` global scopes.
1 parent 8a55ab2 commit 73ca138

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

packages/browser/src/sdk.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,12 @@ type Runtime = {
7272
};
7373

7474
function shouldShowBrowserExtensionError(): boolean {
75-
const windowWithMaybeExtension = WINDOW as typeof WINDOW & ExtensionProperties;
75+
const windowWithMaybeExtension =
76+
typeof WINDOW.window !== 'undefined' && (WINDOW as typeof WINDOW & ExtensionProperties);
77+
if (!windowWithMaybeExtension) {
78+
// No need to show the error if we're not in a browser window environment (e.g. service workers)
79+
return false;
80+
}
7681

7782
const extensionKey = windowWithMaybeExtension.chrome ? 'chrome' : 'browser';
7883
const extensionObject = windowWithMaybeExtension[extensionKey];

packages/browser/test/sdk.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ describe('init', () => {
149149
Object.defineProperty(WINDOW, 'chrome', { value: undefined, writable: true });
150150
Object.defineProperty(WINDOW, 'browser', { value: undefined, writable: true });
151151
Object.defineProperty(WINDOW, 'nw', { value: undefined, writable: true });
152+
Object.defineProperty(WINDOW, 'window', { value: WINDOW, writable: true });
152153
});
153154

154155
it('logs a browser extension error if executed inside a Chrome extension', () => {
@@ -229,6 +230,18 @@ describe('init', () => {
229230
consoleErrorSpy.mockRestore();
230231
});
231232

233+
it("doesn't log a browser extension error if the `window` object isn't defined", () => {
234+
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
235+
236+
Object.defineProperty(WINDOW, 'window', { value: undefined });
237+
238+
init(options);
239+
240+
expect(consoleErrorSpy).not.toHaveBeenCalled();
241+
242+
consoleErrorSpy.mockRestore();
243+
});
244+
232245
it("doesn't return a client on initialization error", () => {
233246
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
234247

0 commit comments

Comments
 (0)