Confirm Exit with device back button in ionic


In my app i have 2 pages home.ts and page2.ts, home page has a button to open the page2,


and in page 2 i have another button that will open a model that is page3 like below

presentModal() {
    let modal = this.modalCtrl.create(page3 );

so far ok, if i opened the modal, pressing device back button will close the modal,and pressing again will pop the page2 and home page wil be now the active page, it will quit the app if i press the device backbutton again.

i want to use a confirm alert box in home page before quit the app, but device backbutton should work normally in other pages (page2, page3) ,

can someone please help me how to do this,?


use lifecycle event ionViewWillLeave() or ionViewWillUnload()


ionViewWillLeave in home.ts will fire when i open the page2


yeah so use WillUnload()


you mean WillUnload fires only when user quit the app ?


ionViewWillUnload Runs when the page is about to be destroyed and have its elements removed.


It is not working

ionViewWillLeave() {

  ionViewWillUnload() {

it shows alert leave when i open page2, but when i press back button nothing happens, it quits the app,


it is never get called


Here’s what I use: How to hold back twice to exit
Just strip it of things you don’t want :slight_smile:


what i am looking is to show a ad just before the app quit, without much headache with registerbackbutton,and it is very easy with ionic1. i dont understand your code how it works for my need


i hope this helps:


Hi,here i have given my sample coding,refer this coding and where you want use this coding,please use it.

app.component_ file_**
//Import of AlertController in top.
import { AlertController } from ‘ionic-angular’;

templateUrl: ‘app.html’
export class MyApp {
//Alert shown variavle.
public alertShown:boolean=false;
//parameters passed for platform and AlertController.
constructor(public platform: Platform, public alertCtrl: AlertController) {
platform.registerBackButtonAction(() => {
if (this.alertShown==false) {
}, 0)
presentConfirm() {
let alert = this.alertCtrl.create({
title: ‘Confirm you want to Exit’,
message: ‘Do you want Exit?’,
buttons: [
text: ‘Cancel’,
role: ‘cancel’,
handler: () => {
console.log(‘Cancel clicked’);
text: ‘Yes’,
handler: () => {
console.log(‘Yes clicked’);

That is it,simply one function in Exit alert controller in ionic v3,Maybe its work correctly,try it


This might Help. Registerbackbuttonaction