Skip to content

Commit

Permalink
fix(browser): Avoid showing browser extension error message in non-`w…
Browse files Browse the repository at this point in the history
…indow` 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.
  • Loading branch information
Lms24 authored Aug 2, 2024
1 parent 8a55ab2 commit 73ca138
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/browser/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
13 changes: 13 additions & 0 deletions packages/browser/test/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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(() => {});

Expand Down

0 comments on commit 73ca138

Please sign in to comment.