/    /  Javascript Network Handling

Javascript Network Handling

 

In some special cases, developers should know if our request failed because of Network issues. And if we can do some things(times) when Network reverts the connections.

 

Naviagtor.onLine:

 

`naviagtor.onLine` is a good solution for us to know the current status of the Browser Network. And it has been supported by many(all) modern browsers.

 

Javascript Network Handling

 

use the `online` event:

 

document.addEventListenner(‘online’, () => {
// todo
});
document.addEventListenner(‘offline’, () => {
// todo 
})

 

Network heartbeat check

 

Use xhr or image to send a heartbeat to check if Network

 

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
}
})

 

Network-heart-service:

 

handle the network change:

 

$ 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
⦁ lowSpeedNetwork { function }

 

API:

 

isOnline():

 

Check if your network could work.

const isOnline = await NetworkHeartService.isOnline();

 

start() and stop()

 

Start or Stop the network check service.