How to detect when the user leaves the app (temporarily)?

Is there a way using javascript/cordova to detect when the user has pressed the home button, and is temporarily out of the app (pause mode).

In the Ionic framework, you have the ionicview.leave, but this also holds when the user leaves the view and goes to another one.

Context:
I am building an app that is protected, meaning that you can only view the content when:

  • you enter the correct access code
  • your session has not timed out

But when you go to Home, then I want somehow to record that the session is over and that the user needs to authenticate when he comes back in the app.

I am curious if browser Page Visibility API will work in this case?

You can also use these events;

$document.addEventListener('resume', function() {
    $rootScope.$broadcast('onResume');
  });
  $document.addEventListener('pause', function() {
    $rootScope.$broadcast('onPause');
  });

Just to add on to @yurinondual you can use the $ionicPlatform events to add the cordova event listeners:

$ionicPlatform.on('resume', function() {
    $rootScope.$broadcast('onResume');
});

$ionicPlatform.on('pause', function() {
    $rootScope.$broadcast('onPause');
});
2 Likes

Thanks for the comments everyone. Just where do I put these event listeners?

I put them in the app’s run function:

app.run(function($ionicPlatform) {
    $ionicPlatform.on('resume', function() {
        // code for resuming the app
    });
});
3 Likes

Hello,

I have biometric authentication enabled in my ionic cordova android app. I wish to call the biometric authentication everytime user pause and then resumes the app. but I am facing a small issue, the app is considering the biometric auth as a pause event and it is asking to reauth even when I am routing from Login to Home page

are you using resume and pause event from platform?