AngularJS tips and tricks – broadcast online and offline status

In continuing my experiments with AngularJS, I often stumble upon new challenges, I haven’t met before. One of these challenges was to broadcast the online and offline status of the browser.

I wanted to be able to hide different parts of the gui, if the user wasn’t online. In order to do that, I had to create a centralized variable, that would notify the gui whenever changes occurred. I did this by applying the following code in my app:

    app.run(function($rootScope) {
      // console.log("online:" + navigator.onLine);

      $rootScope.online = navigator.onLine ? 'online' : 'offline';
      $rootScope.$apply();

      if (window.addEventListener) {
        window.addEventListener("online", function() {
          $rootScope.online = "online";
          $rootScope.$apply();
        }, true);
        window.addEventListener("offline", function() {
          $rootScope.online = "offline";
          $rootScope.$apply();
        }, true);
      } else {
        document.body.ononline = function() {
          $rootScope.online = "online";
          $rootScope.$apply();
        };
        document.body.onoffline = function() {
          $rootScope.online = "offline";
          $rootScope.$apply();
        };
      }
    });

As you can see, the function adds an event listener that will automatically update the $rootScope.online variable. Now, I can just use this variable in my HTML – like so:

<li ng-show="online == 'online'"><i class="icon-lock dark"></i><asp:LoginStatus ID="LoginStatus2" runat="server" LogoutText="Signout" LogoutPageUrl="~/Login.aspx" LoginText="Signout" LogoutAction="Redirect" /></li>

Works like a charm 🙂

Advertisements

6 thoughts on “AngularJS tips and tricks – broadcast online and offline status

  1. Actually listening for the window.navigator.onLine only gives you a status of your LAN / WIFI connection and doesn’t check for any internet connection (in order to achieve that, we have to make an additional ajax request when we think that we are online, depending on the navigator.online status).
    a nice library that can save us the hassle – https://github.com/HubSpot/offline
    docs about navigator.online – https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s