Why navigator.onLine is inconsistent? Is there any

2019-09-16 01:48发布

问题:

I am facing an issue on connectivity check. Using navigator.onLine to test the same in my ionic app. Its pretty inconsistent across devices. Its a cross platform app.

Is there any possible and reliable replacement for connectivity check?

回答1:

If the browser supports navigator.onLine (typeof navigator.onLine === "boolean") the connectivity check is reliable.

If the browser doesn't support navigator.onLine (typeof navigator.onLine !== "boolean") you need some kind of hack.

One possible hack is to check for the presence of an online resource (i.e. image)

var imgCheck = new Image();
imgCheck.onerror = function(){ console.log('offline');};
imgCheck.onload = function(){ console.log('online');};
imgCheck.src = <URL_OF_IMAGE> + '?' +new Date().getTime();