Device backbutton (platform.registerBackButtonAction) is not working. it always exit from the application

467 Views Asked by At

Device backbutton (platform.registerBackButtonAction) is not working for Application back button and it's not working for Device back button.

Can some one help me please?

How can I solve my problem?

code:-

  ionViewDidLoad() {
    this.navBar.backButtonClick = (e: UIEvent) => {
      const alert = this.alertCtrl.create({
        title: 'App termination',
        message: 'Do you want to close the app?',
        buttons: [{
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            console.log('Application exit prevented!');
          }
        }, {
          text: 'Close App',
          handler: () => {
            this.platform.exitApp(); // Close this application
          }
        }]
      });
      alert.present();
    }
  }
1

There are 1 best solutions below

0
Mangesh Daundkar On

Modify your app.component.ts file in following way,

  import { Platform, IonicApp } from 'ionic-angular';

  constructor(public platform: Platform, private ionicApp: IonicApp){}

  initializeApp() {
    this.platform.ready().then(() => {
      //back button handle
      this.platform.registerBackButtonAction(() => {
        let activePortal = this.ionicApp._loadingPortal.getActive() ||
          this.ionicApp._modalPortal.getActive() ||
          this.ionicApp._toastPortal.getActive() ||
          this.ionicApp._overlayPortal.getActive();

        if (activePortal) {
          activePortal.dismiss();
        }
        else {
          if (this.nav.canGoBack()) {
            this.nav.pop();
          } else {
            this.showAlert();
          }
        }
      });
    });
  }

  showAlert() {
    let confirm = this.alertCtrl.create({
      title: 'Exit Application?',
      message: 'Do you want to exit this application?',
      buttons: [
        {
          text: 'No',
          handler: () => {}
        },
        {
          text: 'Yes',
          handler: () => {
            navigator['app'].exitApp();
          }
        }
      ]
    });
    confirm.present();
  }