Skip to content

Commit

Permalink
fix(web): check window is defined before accessing (#646)
Browse files Browse the repository at this point in the history
  • Loading branch information
bombillazo committed Nov 28, 2022
1 parent 52058a1 commit ba5c22c
Showing 1 changed file with 24 additions and 16 deletions.
40 changes: 24 additions & 16 deletions src/internal/nativeModule.web.ts
Expand Up @@ -8,22 +8,22 @@
*/

import {
NetInfoNativeModule,
DEVICE_CONNECTIVITY_EVENT,
NetInfoNativeModule,
NetInfoNativeModuleState,
} from './privateTypes';
import {
NetInfoBluetoothState,
NetInfoCellularGeneration,
NetInfoCellularState,
NetInfoEthernetState,
NetInfoNoConnectionState,
NetInfoOtherState,
NetInfoState,
NetInfoStateType,
NetInfoUnknownState,
NetInfoNoConnectionState,
NetInfoCellularState,
NetInfoBluetoothState,
NetInfoEthernetState,
NetInfoWifiState,
NetInfoWimaxState,
NetInfoOtherState,
NetInfoCellularGeneration,
} from './types';

// See https://wicg.github.io/netinfo/#dom-connectiontype
Expand Down Expand Up @@ -70,12 +70,16 @@ declare global {
webkitConnection?: Connection;
}
}
// Use a constant test of this form because in SSR on next.js, optional chaining is not sufficient,
// but this test correctly detects that window is not available and allows for conditionals before access
const isWindowPresent = typeof window !== 'undefined';

// Check if the browser supports the connection API
const connection =
window.navigator.connection ||
window.navigator.mozConnection ||
window.navigator.webkitConnection;
// Check if window exists and if the browser supports the connection API
const connection = isWindowPresent
? window.navigator.connection ||
window.navigator.mozConnection ||
window.navigator.webkitConnection
: undefined;

// Map browser types to native types
const typeMapping: Record<ConnectionType, NetInfoStateType> = {
Expand Down Expand Up @@ -249,8 +253,10 @@ const RNCNetInfo: NetInfoNativeModule = {
if (connection) {
connection.addEventListener('change', nativeHandler);
} else {
window.addEventListener('online', nativeHandler, false);
window.addEventListener('offline', nativeHandler, false);
if (isWindowPresent) {
window.addEventListener('online', nativeHandler, false);
window.addEventListener('offline', nativeHandler, false);
}
}

// Remember handlers
Expand All @@ -272,8 +278,10 @@ const RNCNetInfo: NetInfoNativeModule = {
if (connection) {
connection.removeEventListener('change', nativeHandler);
} else {
window.removeEventListener('online', nativeHandler);
window.removeEventListener('offline', nativeHandler);
if (isWindowPresent) {
window.removeEventListener('online', nativeHandler);
window.removeEventListener('offline', nativeHandler);
}
}

// Remove handlers
Expand Down

0 comments on commit ba5c22c

Please sign in to comment.