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

Intercept nav.pop()

Open mhartington opened this issue 10 years ago • 33 comments

Situation

You're on a form page, and the user accidentally hits the back button (either the generated back button, or hardware back button). In stead of just going back and destroying that page, it would be great to create some sort of page hook that could run and prevent the page from navigating back.

Might even be good to extend onPageWillLeave

onPageWillLeave(){
  if(!this.form.value){
   console.log("form is empty")
  } else{
    this.nav.pop();
  }
  return false;
}

mhartington avatar May 23 '16 14:05 mhartington

👍

keithdmoore avatar May 23 '16 19:05 keithdmoore

I searched through all of the documentation and much of the Navigation code today and there really is no official way to do this. I wanted to popup an Alert before leaving the Page, but creating Alerts using nav.present() within onPageWillLeave() doesn't work (navigation continues while Alert is up). You could maybe nav.insert() a Page, but I didn't want to actually leave the current Page.

Here's a solution that works for now. Just add an onPop() method to any Page and return false if you don't want to pop. Also, I verified that clicking the hardware back button calls pop().

Stick this code at the top of app.ts after you import NavController.

let originalNavPop = NavController.prototype.pop;
(<any> NavController).prototype.pop = function() {
  // this refers to the NavController instance
  let page = (<NavController> this).getActive().instance;
  if (page.onPop) {
    console.log('Calling onPop() on active page', page);
    if (page.onPop() === false) {
      console.log('onPop() returned false, aborting pop()');
      return;
    }
  }
  return originalNavPop.apply(this, arguments);
};

JavaScript version for those unfamiliar with TypeScript. (put in app.js)

var originalNavPop = NavController.prototype.pop;
NavController.prototype.pop = function() {
  // this refers to the NavController instance
  var page = this.getActive().instance;
  if (page.onPop) {
    console.log('Calling onPop() on active page', page);
    if (page.onPop() === false) {
      console.log('onPop() returned false, aborting pop()');
      return;
    }
  }
  return originalNavPop.apply(this, arguments);
};

EDIT: Forgot return statements.

The return statement in the === false case should return a Promise to conform to the API. Maybe a rejected Promise? return Promise.reject('Page stopped pop()'); But will rejecting the Promise cause issues with the Ionic code calling this method? Needs to be tested...

arlowhite avatar May 27 '16 23:05 arlowhite

Ionic2 Beta7, you can't throw an Error from onPageWillLeave to abort pop() because:

    ViewController.prototype.willLeave = function () {
        ctrlFn(this, 'onPageWillLeave');
    };
function ctrlFn(viewCtrl, fnName) {
    if (viewCtrl.instance && viewCtrl.instance[fnName]) {
        try {
            viewCtrl.instance[fnName]();
        }
        catch (e) {
            void 0;
        }
    }
}

I think just enhancing onPageWillLeave is a good solution for this issue. Either return a boolean or a special value to cancel pop. Or maybe throw a special CancelPop error object?

Unfortunately, modifying nav-controller.ts to support this isn't straightforward because fireWillLeave() is called in 3 different places. But maybe someone more familiar with the code would have a clean solution for adding the feature.

Otherwise, something like my onPop() hack could actually be added officially.

arlowhite avatar May 28 '16 00:05 arlowhite

In my application,return false it still doesn't work.why?

DarrenHou1993 avatar Jun 03 '16 09:06 DarrenHou1993

@DarrenHou1993 Assuming you copied my code above, you should see "Calling onPop() on active page" in the log (if you added an onPop method to the current page) regardless of the return value from onPop(). If not, there's something wrong with the code that overrides NavController.pop (or where it's being executed) Try adding a log statement first thing in the pop function to make sure the new function is actually being executed.

I haven't actually tested the JavaScript version I posted above, I just remove TypeScript notation. So maybe the JavaScript example needs to be setup differently though I don't think so.

Also, note that the code is using triple-equal ===, so if you want falseish things to stop pop (like zero), just change it to ==

arlowhite avatar Jun 03 '16 23:06 arlowhite

@arlowhite Thank you very much. It works.

DarrenHou1993 avatar Jun 06 '16 02:06 DarrenHou1993

Are there any chances that this feature is integrated in beta 10? Thank you very much.

manueltaber avatar Jun 20 '16 08:06 manueltaber

@manueltaber,

Good question :) . Not sure. I'll let you know when we start working on this.

Thanks, Dan

danbucholtz avatar Jun 20 '16 14:06 danbucholtz

@mhartington @arlowhite @jgw96

For me return false on ionViewWillLeave works like expected also open an Alert in ionViewWillLeave will work.

Here is a working Plunkr http://plnkr.co/edit/SQqbtdrYpN8s0apmP66o?p=preview

DavidWiesner avatar Jun 29 '16 11:06 DavidWiesner

@DavidWiesner Was this feature introduced in beta 10? I can not find any changelog...

manueltaber avatar Jun 29 '16 12:06 manueltaber

@manueltaber this will work for a long time at minimum since beta 4. Only onPageWillLeave was renamed to ionViewWillLeave in beta 8 (see https://github.com/driftyco/ionic/blob/2.0/CHANGELOG.md#ionic-lifecycle-events-renamed)

DavidWiesner avatar Jun 29 '16 12:06 DavidWiesner

This is a very important feature!

stefanhuber avatar Jul 04 '16 12:07 stefanhuber

I still don't get it running on my project... The event ionViewWillLeave is called but the result is ignored.

manueltaber avatar Jul 04 '16 15:07 manueltaber

@DavidWiesner you are hitting an edge case bug with:

    ionViewWillLeave(){
      let leave = this.dismissChanges || !this.hasUnsavedChanges();
      if(!leave){
        this.showConfirmDismissChangesAlert();
      }
      return false;
    }

The return value is always completely ignored like @manueltaber points, it is not going back because you are showing an Alert, and that mess up with the ongoing go back procedure. Please don't depend on this buggy behaviour as a feature, in fact "your workaround" will not longer work in beta11 since we refactored the whole overlay system (Alert, ActionSheet, etc.).

I am going to propose a new ionCanGoBack(): boolean callback, I don't want to overload the behaviour of ionViewWillLeave since it is also called when pushing pages in the navigation stack.

Also, ionViewWillLeave should continue indicating that there is an ongoing page change, that it's already too late to be cancelled.

We need to continue discussing though.

manucorporat avatar Jul 04 '16 17:07 manucorporat

@manucorporat thank you for your clearification. A new ionCanGoBack(): boolean callback would be a great solution!

manueltaber avatar Jul 05 '16 08:07 manueltaber

@manucorporat ok you are right it's just and workaround that accidentally works

:+1: for a ionCanGoBack(): boolean solution

DavidWiesner avatar Jul 05 '16 22:07 DavidWiesner

@arlowhite Thanks for the workaround. This will only work, if swipeBackEnabled is disabled on iOS

DavidWiesner avatar Jul 11 '16 14:07 DavidWiesner

@DavidWiesner @manueltaber @stefanhuber @DarrenHou1993 @arlowhite @keithdmoore @mhartington pending PR that implements this feature: https://github.com/driftyco/ionic/pull/7305

Please share your thoughts before this becomes part of ionic!

I will try to push this feature for beta11, no promises ;)

manucorporat avatar Jul 14 '16 00:07 manucorporat

@manucorporat The API is great, but I'd like to see the logic behind ionViewCanLeave integrated into NavController, and not just the back button. Additionally, we should come up with a way to allow the method to be async.

adamdbradley avatar Jul 14 '16 04:07 adamdbradley

Goals:

  • ionViewCanLeave method, on the users component, that can prevent a nav pop or push
  • Can return a boolean (synchronous)
  • Can return an Observable<boolean> (async)
  • NavController performs these tests on the hierarchy of navs, from the deepest child up to the root
  • Able to prevent/handle URL changes from the browser (browser back button, url bar change)
  • Support ionViewCanEnter in a later commit

adamdbradley avatar Jul 14 '16 04:07 adamdbradley