ionic-framework icon indicating copy to clipboard operation
ionic-framework copied to clipboard

Ionic 2: Modal window doesn't dismiss when overriding back button on Android device.

Open daveshirman opened this issue 10 years ago • 44 comments

Short description of the problem:

If you override the back button e.g.:

  registerBackButtonListener() {
    this.platform.registerBackButtonAction(() => {
      var nav = this.getNav();
      if (nav.canGoBack()) {
        nav.pop();
      }
      else {
        //... do something else...
      }
    });
  }

If a modal window is open, it is not closed and instead the page in the background will navigate back.

What behavior are you expecting?

The line: nav.canGoBack() should pop a modal view, not the page underneath.

Which Ionic Version? 1.x or 2.x 2

Run ionic info from terminal/cmd prompt: (paste output below) Your system information:

Cordova CLI: 6.1.1 Ionic Framework Version: 2.0.0-beta.9 Ionic CLI Version: 2.0.0-beta.25 Ionic App Lib Version: 2.0.0-beta.15 ios-deploy version: 1.8.6 ios-sim version: 5.0.8 OS: Mac OS X El Capitan Node Version: v4.3.0 Xcode version: Xcode 7.2.1 Build version 7C1002

daveshirman avatar Jun 20 '16 23:06 daveshirman

Hi guys, can someone tell me if I'm the problem here or if it's the framework? I just want to override the back button to catch app exiting, so if I'm doing something wrong, please tell me.

daveshirman avatar Jun 23 '16 11:06 daveshirman

Hello @daveshirman ! Thanks for opening an issue with us. A modal is actually an instance of viewController and not navController, so something like this should work for you:

this.platform.registerBackButtonAction(() => {
      this.viewController.dismiss()
      else {
        //... do something else...
      }
    });

Thanks for using Ionic and sorry for the delay on this!

jgw96 avatar Jun 23 '16 16:06 jgw96

Hi, thanks for your reply. But how does this actually solve the problem? I mean, how do I know programmatically whether I need to dismiss()a viewController OR check nav.canGoBack()?

This seems like something the platform should supply (already does?).

daveshirman avatar Jun 23 '16 19:06 daveshirman

Sorry for the misunderstanding! If you would like to catch a user closing your app you can simply listen for the pause cordova event. Hope that explains things better!

jgw96 avatar Jun 24 '16 15:06 jgw96

Hello, i am currently discussing this with my team. Also sorry for misunderstanding your issue, i understood the issue to be about catching an app exiting, my mistake.

jgw96 avatar Jun 24 '16 15:06 jgw96

Hi, what was the result of the discussion with your team? Is there a consensus on how to override the back button without losing basic page back, modal dismissing and alert dismissing functionality?

daveshirman avatar Jun 27 '16 07:06 daveshirman

Hi, can someone please reply to me from the Ionic team? Thanks.

daveshirman avatar Jul 05 '16 09:07 daveshirman

Hello @daveshirman ! Sorry for the delay on this issue, with the release of beta.10 last week i have been very busy with things related to the release. I plan on taking another look at this issue today. Thanks!

jgw96 avatar Jul 05 '16 15:07 jgw96

Hey @daveshirman at this time there is not a good, clean way to programatically detect if their is an overlay component (like modals or alerts) open (although it is something we are considering). For a workaround i would try something like

this.platform.registerBackButtonAction(() => {
  try {
    this.viewController.dismiss()
  }
  catch(e) {
    ... no overlay component open
  }
})

Sorry for any hassle this causes, i will be closing this issue for now as it is not something that we plan on implementing soon, but will reopen this issue if something changes. Thanks for using Ionic, and again, sorry for the delay on this.

jgw96 avatar Jul 06 '16 18:07 jgw96

@daveshirman Did you ever find a good solution to this issue? We have been running into this issue too. Very annoying.

Chuckv01 avatar Sep 10 '16 01:09 Chuckv01

Hi, unfortunately not. My "solution"was to abandon overriding the back button as it doesn't work reliably.

Don't know when/whether the guys at Ionic are intending to fix it either.

On 10 Sep 2016 2:02 a.m., "Chuckv01" [email protected] wrote:

@daveshirman https://github.com/daveshirman Did you ever find a good solution to this issue? We have been running into this issue too. Very annoying.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/driftyco/ionic/issues/6982#issuecomment-246077352, or mute the thread https://github.com/notifications/unsubscribe-auth/ANnlXmIsXWVvJwZnMuSUFD0Em2pSvBt2ks5qogGZgaJpZM4I6Pdr .

daveshirman avatar Sep 10 '16 10:09 daveshirman

I had the same problem. My "solution" was: if their is an overlay component, the ion-app element has the class "disable-scroll", so i can check if the class if present or not to prevent go back.

Something like this:

this.platform.registerBackButtonAction(() => {

          //https://github.com/driftyco/ionic/issues/6982
          let element = document.getElementsByTagName('ion-app')[0];
          let existOverlay = element.classList.contains('disable-scroll');

          if(! existOverlay) {
            let nav = app.getRootNav();

            if(nav.canGoBack()) 
            {
                nav.pop();
            }
            else
            {
              this.confirmExit();
              return false;
            }
          }
        }, 100)

I know that is not a beautiful solution but it works. In the confirm method I show the confirm modal. Also I used a flag to prevent that users press back repeatedly and multiples modal appear.

imcosta avatar Sep 29 '16 23:09 imcosta

OK, I needed it and have a workaround:

Just dismiss portals yourself:

import { Component, ViewChild } from '@angular/core';
import { Platform, Events, App, MenuController, AlertController, Nav, IonicApp } from 'ionic-angular';
import { StatusBar } from 'ionic-native';

import { TabsPage } from '../pages/tabs/tabs';


@Component({
  template: `<ion-nav id="nav" #content [root]="rootPage"></ion-nav>`
})
export class MyApp {
  rootPage = TabsPage;
  @ViewChild(Nav) nav: Nav;

  constructor(private platform: Platform, private alertCtrl: AlertController,
    public events: Events, private app: App, private ionicApp: IonicApp,
    private menuCtrl: MenuController) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();


      let ready = true;
      document.onkeypress = (event) => {
        if (!event) return;

        if (event.keyCode >= 48 && event.keyCode <= 57) {

          console.log(this.app);
          console.log(this.ionicApp);
          console.log(this.nav);

          let activePortal = this.ionicApp._loadingPortal.getActive() ||
            this.ionicApp._modalPortal.getActive() ||
            this.ionicApp._toastPortal.getActive() ||
            this.ionicApp._overlayPortal.getActive();

          if (activePortal) {
            ready = false;
            activePortal.dismiss();
            activePortal.onDidDismiss(() => { ready = true; });
          }
          else { .... your default code here }
        }
      };
    });
  }
}

For testing I used html windows and keypress event, but you can define this function for registering back button. There is ready param, which do not try to dismiss portal if we in process of dismiss...

laserus avatar Oct 18 '16 14:10 laserus

@laserus that looks promising. I will have to try it out.

@jgw96 This is still an issue for us as of RC1. I don't think the issue should be closed. We've been forced to stop overriding the android back button as modals and dialogues still do not behave properly when it is overridden and the hardware back button is pressed.

Chuckv01 avatar Oct 18 '16 15:10 Chuckv01

Hi, I find a way to solve it in ionic2. I learn it from Ionic Source. I check if having overlay is showing like this:

const portal = app._appRoot._getPortal();
if(portal.length() > 0){
    //have overlay
    portal.pop();
}

So, I override the back button to catch app exiting like this:

platform.registerBackButtonAction(() => {
        let activeVC = this.nav.getActive();
        let page = activeVC.instance;
        if (page instanceof TabsPage) {
          try {
            const portal = app._appRoot._getPortal();
            if (portal.length() == 0) {
                // no overlay
                // do something  you want
                showExitingConfirm();
            }
          } catch (e) {
              console.log("back action listener error :" + e);
          }
        }
        //  the default handler
        app.navPop();
      });

My english is pool. Hope it can help you.

lazy-ape avatar Oct 19 '16 03:10 lazy-ape

@lazy-ape I think currently there is a bug https://github.com/driftyco/ionic/issues/8692 that modal is not closing. So you should treat it outside of app.navPop(), but otherwise it is good.

Simplest way is to do this.ionicApp._modalPortal.getActive() and dismiss it yourself.

I have a similar approach (without modals yet) but instead of if (page instanceof TabsPage) { I put on pages confirmation variable "needConfirmationOnExit" (but more appropriate approach is to use some base class and extend).

if( page && page.needConfirmationOnExit) { /* special treatment */ }
else {....}

laserus avatar Oct 19 '16 07:10 laserus

@lazy-ape sorry your approach does not work, as you using const portal = app._appRoot._getPortal(); calling this function without parameters returns OverlayPortal only, which is the same as this.ionicApp._overlayPortal.getActive();

laserus avatar Oct 19 '16 07:10 laserus

In the end I have this for my back button:

   constructor(private platform: Platform, private config: ConfigService, private nfc: NfcService, private alertCtrl: AlertController,
      public events: Events, private translate: TranslateService, private fetch: ConfigFetchService, private menuList: MenuList, private ionicApp: IonicApp,
      private menuCtrl: MenuController
   ) {
      platform.ready().then(() => {
         this.config.pullVersion();
         let ready = true;

         platform.registerBackButtonAction(() => {
            Logger.log("Back button action called");

            let activePortal = ionicApp._loadingPortal.getActive() ||
               ionicApp._modalPortal.getActive() ||
               ionicApp._toastPortal.getActive() ||
               ionicApp._overlayPortal.getActive();

            if (activePortal) {
               ready = false;
               activePortal.dismiss();
               activePortal.onDidDismiss(() => { ready = true; });

               Logger.log("handled with portal");
               return;
            }

            if (menuCtrl.isOpen()) {
               menuCtrl.close();

               Logger.log("closing menu");
               return;
            }

            let view = this.nav.getActive();
            let page = view ? this.nav.getActive().instance : null;

            if (page && page.isRootPage) {
               Logger.log("Handling back button on a home page");
               this.alertCtrl.create({
                  title: translate.instant('Confirmation'),
                  message: translate.instant('Do you want to exit?'),
                  buttons: [
                     {
                        text: translate.instant('Cancel'),
                        handler: () => {
                        }
                     },
                     {
                        text: translate.instant('OK'),
                        handler: () => {
                           platform.exitApp();
                        }
                     }
                  ]
               }).present();
            }
            else if (this.nav.canGoBack() || view && view.isOverlay
            ) {
               Logger.log("popping back");
               this.nav.pop();
            }
            else if (localStorage.getItem('is_logged_in')
            ) {
               Logger.log("Returning to home page");
               this.nav.setRoot(HomePage);
            }
            else if (!localStorage.getItem('is_logged_in')) {
               Logger.log("Not yet logged in... exiting");
               platform.exitApp();
            }
            else {
               Logger.log("ERROR with back button handling");
            }

         }, 1);
....

laserus avatar Oct 19 '16 07:10 laserus

@laserus thanks for posting your workaround. The activePortal part solved my issues with modals.

jrierab avatar Oct 28 '16 06:10 jrierab

@laserus thanks. works fine for me!

xggaxlc avatar Nov 08 '16 07:11 xggaxlc