netsignal
Version:
Instant network detection for React Native and Web - Turbo Module enabled
99 lines (97 loc) • 2.58 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WebNetSignal = void 0;
var _base = require("./base");
/**
* Web-only implementation of NetSignal
* Tree-shakable - no React Native dependencies
*/
class WebNetSignal extends _base.BaseNetSignal {
listeners = new Map();
state = {
isConnected: typeof navigator !== 'undefined' ? navigator.onLine : true,
type: 'unknown'
};
constructor() {
super();
if (typeof window !== 'undefined') {
this.initWeb();
}
}
isConnected() {
return this.state.isConnected;
}
getType() {
return this.state.type;
}
async probe(url, timeoutMs = 5000) {
const start = Date.now();
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
const response = await fetch(url, {
method: 'HEAD',
mode: 'cors',
cache: 'no-cache',
signal: controller.signal
});
clearTimeout(timeoutId);
return {
reachable: response.ok,
responseTime: Date.now() - start
};
} catch (error) {
return {
reachable: false,
responseTime: -1,
error: error.message
};
}
}
onChange(callback) {
const id = Math.random().toString(36);
const handler = () => {
this.updateState();
callback({
isConnected: this.state.isConnected,
type: this.state.type
});
};
window.addEventListener('online', handler);
window.addEventListener('offline', handler);
this.listeners.set(id, handler);
return () => {
window.removeEventListener('online', handler);
window.removeEventListener('offline', handler);
this.listeners.delete(id);
};
}
initWeb() {
this.updateState();
window.addEventListener('online', () => this.updateState());
window.addEventListener('offline', () => this.updateState());
const conn = navigator.connection;
if (conn) {
conn.addEventListener('change', () => this.updateState());
}
}
updateState() {
this.state.isConnected = navigator.onLine;
if (!navigator.onLine) {
this.state.type = 'none';
return;
}
const conn = navigator.connection;
if (conn?.type) {
this.state.type = conn.type;
} else if (conn?.effectiveType) {
this.state.type = conn.effectiveType.includes('g') ? 'cellular' : 'wifi';
} else {
this.state.type = 'unknown';
}
}
}
exports.WebNetSignal = WebNetSignal;
//# sourceMappingURL=web.js.map
;