Find out if alert over active view


#1

Hi everyone,

I’m working on a Ionic 2 app and currently I’m implementing an alert to ask if the user really indends to leave the app when the back button is pressed.

I check if it can go back, if not, I pop up the alert.

      this.platform.registerBackButtonAction(() => {
        if(this.nav.canGoBack()){
          // In here, check if there's an alert already open
          this.nav.pop();
        }else{
          if(this.alert) {
            this.alert.dismiss();
            this.alert = null;
          }else{
            this.closeApp();
          }
        }
      })

Altough it all works fine, when there is already an alert on screen and I press the back button, the page on top dismisses but the alert stays there and my “closing app alert” overlays it.

I`m looking for a way to find out if there’s a alert already over the top page so in this case I do not do anything.

I know I could have a global alert variable or go over all my pages adding an alert dismiss on ionViewWillLeave() but I wonder if there’s a better way to do that, with viewController for example.

Thanks!


#2

Hi,

With that code, you close any overlay (alert, popover, modal), any page if there is a previous page.and move the app in background if there is no previous page :

  constructor(public platform: Platform, public app: App) {

      platform.registerBackButtonAction(() => {
        let nav = app._appRoot._getActivePortal() || app.getActiveNav();
        let activeView = nav.getActive();

        if (activeView != null) {
          if (nav.canGoBack()) {
            nav.pop();
          } else if(activeView.isOverlay) {
            activeView.dismiss();
          } else {
            backgroundMode.moveToBackground();
            //this.closeApp();
          }
        }
      });
}

I do not use that code in production for the moment but I tested it with an Alert, modal page and popover and that did the job but I still have to test it with a loader (I fear it closes the loader even if you do not want to) and I will have to find a trick for that.

So check if it works for you and feel free to improve and share the code :slight_smile:


#3

Thanks, man! I will check it out.


#4

thank you very much, it was very helpful!!!


#5

Thank You iborik, it was helful