I tried some suggestions, such as navigator.onLine, but even in flight mode, my app "thinks" its online.
I found some suggestions with ajax too, but I just want to check if I'm online to open an external web page. If not, I intend to show a message such as "Your device seems to be offline. Check your connection!".
The best approach is to use cordova network information plugin
which does the job for you seamlessly. This plugin provides information about the device's cellular and wifi connection, and whether the device has an internet connection.
You check out the official github page of this plugin for more info on the same. Hope it helps.
Download the plugin: https://www.npmjs.com/package/cordova-plugin-network-information
And Try This.
document.addEventListener("deviceready", function(e){
console.log(navigator.connection.type);
document.addEventListener("offline", function(e){
alert("NO_NETWORK");
}, false);
}, false);
offline
The event fires when an application goes offline, and the device is not connected to the Internet.
document.addEventListener("offline", yourCallbackFunction, false);
you can use this plugin
then you can use it everywhere in your App without to import it
if(navigator.connection.type === 'none') {
alert('there is no internet')
}
and you can add it into setInterval to check for internet connection every 5 seconds
setInterval(() => {
if(navigator.connection.type === 'none') {
alert('there is no internet')
} }, 5000);
there are another values for "avigator.connection.type" for example when there is internet then the value of "avigator.connection.type" is the type of connection (wifi, 4g, 3g, ethernet on windows .... )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With