Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Handling Apache Cordova Events With Ionic Framework

TwitterFacebookRedditLinkedInHacker News

There will often come a scenario where you need to determine when your application enters the device background and comes back into the foreground. For example, let’s say we wanted to require a password every time the application is shown. We would need to listen for when the application enters the foreground.

Lucky for us, we can make use of the Apache Cordova event listeners to accomplish this task.

Apache Cordova events require no additional plugin installation for Ionic Framework. To register an event we must do so in our $ionicPlatform.ready() method. For example, we might have register something that looks like this:

var exampleApp = angular.module('example', ['ionic'])
    .run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
            document.addEventListener("resume", function() {
                console.log("The application is resuming from the background");
            }, false);
        });
    });

In the above example, a resume listener is registered. Every time the application regains focus, the callback function will run printing information to the log.

There are many different listeners that can be registered, but according to the Cordova documentation only the following work for Android and iOS. At the time of writing this article, Ionic Framework 1.0.0 beta 11 only supports Android and iOS.

ListenerDescription
resumeThe resume event fires when the native platform pulls the application out from the background.
pauseThe event fires when an application is put into the background.
onlineThis event fires when an application goes online, and the device becomes connected to the Internet.
offlineThe event fires when an application goes offline, and the device is not connected to the Internet.

It is important to note that this can only be tested from a device or simulator. The web browser will not recognize these listeners.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.