Ionic 3 | Handle Back Press Button in Ionic 3 Application without Any Plugin

In Android application we generally press/ tap back to go back view or page but in root activity or root page in Ionic application this back press operation closes or minimize the application to the recent list.

In some application, it may have noticed a confirm pops up to confirm if you really want to close? to answer yes cancel. The ionic application also supports this feature when we can override android’s native back press event with ours.

After overriding we can tell then “Please press again to close/ exit application” or just show up an annoying prompt with yes/ cancel options.

We can implement in app’s main component or any single page or view. But the method will remain the same where ever you apply.

Let’s get started!

First to demonstrate we will create a new Ionic 3 application using below command

Now we will add Platform module’s method registerBackButtonAction which overrides the native back press event after that we can implement our own logic when the user presses back.

You can add above back press event listener in a specific view component or in app’s main component file app.component.ts as follows

Implementation in a specific view like home.ts

In the above code, we are subscribing to Back button action on view load and keeping the instance in a property using which we will unsubscribe when user lease that view.

Implementation in app.component.ts

Also Read: Ionic Lazy Loading Issue | Get Current Component/ Page/ View name in Production Release

This back press event will have a priority of 100 by default. We have added an confirm box to exit.

So by using the above methods, we can easily handle back press event in Ionic application to give more usability to users.



Leave a Reply

Notify of