Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Web] Checking window before accessing #646

Merged
merged 9 commits into from
Nov 28, 2022
38 changes: 22 additions & 16 deletions src/internal/nativeModule.web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@
*/

import {
NetInfoNativeModule,
DEVICE_CONNECTIVITY_EVENT,
NetInfoNativeModule,
NetInfoNativeModuleState,
} from './privateTypes';
import {
NetInfoBluetoothState,
NetInfoCellularGeneration,
NetInfoCellularState,
NetInfoEthernetState,
NetInfoNoConnectionState,
NetInfoOtherState,
mikehardy marked this conversation as resolved.
Show resolved Hide resolved
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,14 @@ declare global {
webkitConnection?: Connection;
}
}
const isWindowPresent = typeof window !== 'undefined';
bombillazo marked this conversation as resolved.
Show resolved Hide resolved

// 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;
mikehardy marked this conversation as resolved.
Show resolved Hide resolved

// Map browser types to native types
const typeMapping: Record<ConnectionType, NetInfoStateType> = {
Expand Down Expand Up @@ -249,8 +251,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 +276,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