diff --git a/src/core/focusManager.ts b/src/core/focusManager.ts index 2ffb62eaaf..7bd68b6781 100644 --- a/src/core/focusManager.ts +++ b/src/core/focusManager.ts @@ -14,7 +14,9 @@ export class FocusManager extends Subscribable { constructor() { super() this.setup = onFocus => { - if (!isServer) { + // addEventListener does not exist in React Native, but window does + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!isServer && window.addEventListener) { const listener = () => onFocus() // Listen to visibillitychange and focus window.addEventListener('visibilitychange', listener, false) diff --git a/src/core/onlineManager.ts b/src/core/onlineManager.ts index 7c3d832b63..844e232e03 100644 --- a/src/core/onlineManager.ts +++ b/src/core/onlineManager.ts @@ -14,7 +14,9 @@ export class OnlineManager extends Subscribable { constructor() { super() this.setup = onOnline => { - if (!isServer) { + // addEventListener does not exist in React Native, but window does + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!isServer && window.addEventListener) { const listener = () => onOnline() // Listen to online window.addEventListener('online', listener, false) diff --git a/src/core/tests/focusManager.test.tsx b/src/core/tests/focusManager.test.tsx index b3086179ce..3089abfc94 100644 --- a/src/core/tests/focusManager.test.tsx +++ b/src/core/tests/focusManager.test.tsx @@ -73,6 +73,19 @@ describe('focusManager', () => { restoreIsServer() }) + test('cleanup should still be undefined if window.addEventListener is not defined', async () => { + const { addEventListener } = globalThis.window + + // @ts-expect-error + globalThis.window.addEventListener = undefined + + const unsubscribe = focusManager.subscribe(() => undefined) + expect(focusManager['cleanup']).toBeUndefined() + + unsubscribe() + globalThis.window.addEventListener = addEventListener + }) + it('should replace default window listener when a new event listener is set', async () => { const addEventListenerSpy = jest.spyOn( globalThis.window, diff --git a/src/core/tests/onlineManager.test.tsx b/src/core/tests/onlineManager.test.tsx index 78def64c60..cdf6a0ce54 100644 --- a/src/core/tests/onlineManager.test.tsx +++ b/src/core/tests/onlineManager.test.tsx @@ -67,6 +67,19 @@ describe('onlineManager', () => { restoreIsServer() }) + test('cleanup should still be undefined if window.addEventListener is not defined', async () => { + const { addEventListener } = globalThis.window + + // @ts-expect-error + globalThis.window.addEventListener = undefined + + const unsubscribe = onlineManager.subscribe(() => undefined) + expect(onlineManager['cleanup']).toBeUndefined() + + unsubscribe() + globalThis.window.addEventListener = addEventListener + }) + test('it should replace default window listener when a new event listener is set', async () => { const addEventListenerSpy = jest.spyOn( globalThis.window,