In some special case, our developers should know if our request failed because of Network. And if we can do some things when Network reverts the connections.
naviagtor.onLine
`naviagtor.onLine` is the best solution for us to know the current status of the Browser Network. And it has been supported by many modern browsers.
But in old browser IE8, you should use the `online` event.
document.addEventListenner(‘online’, () => {
// todo
});document.addEventListenner(‘offline’, () => {
// todo
})
Network heartbeat check
Some years ago, many browsers cannot support naviagtor.onLine. So people try to use xhr or image to send a heartbeat to check if Network could get a response.
const pingUrl = ‘https://ipv4.icanhazip.com';
fetch(`${pingUrl}?_t=` + parseInt(Math.random() * 10000)).then((result) => {
// todo online
}).catch((err) => {
// console.log(err);
if (err.message.indexOf(‘Failed to fetch’) !== -1 ) {
// todo offline
}
})
This could be a good solution when a browser cannot support the API above or the code is running in Node.js.
## navigator.connection
And navigator.connection help us get some basic connection information like speed or other metrics.
const networkType = navigator.connection.effectiveType
// return ‘3g’, ‘4g’, ‘2g’
😿 But it only works in Chrome.
Maybe there is another solution 《Estimates bandwidth》, we can calculate the bandwidth and check its value.
const start = Date.now();fetch(url, {}).then((result) => {
const end = Date.now();
const bw = length / (end — start) * 8000;
// check the bw
})
Network-heart-service
So I write a Javascript library (network-heart-service) to handle the network change.
😀 So let’s see how it work.
$ npm install network-heart-service -save
// es6
import NetworkHeartService from 'network-heart-service';
this.networkHeartService = new NetworkHeartService({
heartMode: 'auto',
reconnect() {
console.log(‘TODO …’)
}
});
this.networkHeartService.start();
Config
- heartMode { number } 2000
if it is undefined, it means use `auto` mode. It will check the network in an increasing timeout.
But it is set with a number, it will check the network in specified time. - lowSpeedNetwork { function }
A function will be fire when your network could work but in low network bandwidth
- reconnect { function }
A function will be fire when your network could work.
- offline { function }
A function will be fire when your network go to offline
API
- isOnline()
Check if your network could work.
const isOnline = await NetworkHeartService.isOnline();
- start() and stop()
Start or Stop the network check service.
Wish it did help you. And your issues are so important for me.