1

In one of my Ionic application, I need to check Network connection is available or not on the Device. If not I need to display an alert that, "Network connection is not available". So I've installed the Cordova's network connection plugin and used the following code. But the Offline event is firing twice I think. Because the alert message is displaying twice, while the app is in Offline mode.

.run(function($ionicPlatform, $ionicPopup) {
    $ionicPlatform.ready(function() {

        document.addEventListener("offline", displayofflineAlert, false);

        function displayofflineAlert() {
            $ionicPopup.alert({
                title: "No Internet",
                content: "No Internet Connection available."
            })
            .then(function(result) {
                ionic.Platform.exitApp();
            });
        }
    });
})

Not sure why it is firing twice. I need it to fire once.

Rajesh Manilal
  • 1,104
  • 9
  • 20

2 Answers2

0

One possible reason is that somewhere in your project, you've pulled in the plugin's js file twice (Cordova should do this automatically for you, but it's still possible due to misconfiguration) Check for that.

If you just want a quick fix, just.add underscore.js to your project and use:

document.addEventListener("offline", _.throttle(displayofflineAlert, 100), false);
Kevin
  • 2,775
  • 4
  • 16
  • 27
0

Do not use document. User angular $window service. That worked for me

app.run('$window', [function($window){

   $window.addEventListener('online', onOnline, false);

   function onOnline() {
                // do something
        }
 }])
Irving r
  • 108
  • 1
  • 7