Skip to content

Commit

Permalink
fix(browser): Avoid showing browser extension error message in non-wi…
Browse files Browse the repository at this point in the history
…ndow browser environments
  • Loading branch information
Lms24 committed Aug 2, 2024
1 parent 964d050 commit c4f7e47
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 = jest.spyOn(console, 'error').mockImplementation(() => {});

Check failure on line 234 in packages/browser/test/sdk.test.ts

View workflow job for this annotation

GitHub Actions / Browser Unit Tests

test/sdk.test.ts > init > initialization error in browser extension > doesn't log a browser extension error if the `window` object isn't defined

ReferenceError: jest is not defined ❯ test/sdk.test.ts:234:31

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 c4f7e47

Please sign in to comment.