Abort transition in willTransition and Browser Back button

Hello everybody :smiley:

I noticed a strange behavior in Ember … I’m trying to cancel a transition in the willTransition hook. For example, I’m on “page2” and I’m from “page1”. When I click on the link “page1”, no problem: the transition is canceled and the url doesn’t change. On the other hand, when I use the back button of the browser, the url changes first (I see the url of page1 in the bar) then the transition is canceled. The problem: I’m still on page2 but I now have the url of page1 !!! Is this a bug?

My route2.js code to simulate this behavior (here I use confirm but in my prod code I use bootbox):

import Route from '@ember/routing/route';

export default Route.extend({
  actions: {
    willTransition(transition) {
      if (!transition.data.force) {
        const r = confirm("Do you want to cancel transition?");

        if (r === false) {
          transition.data.force = true;

Thanks for your help,

I’ve never used willTransition(...) to control flow like that. I guess that isn’t a bad place for this. I’ve instead used it to rollbackAttributes() on model state as someone leaves a route.

Something is triggering your transition…right? Like some user is choosing a new page; for example going from Page 1 to Page 2. Can you place this data.force logic from your will transition into the action code that turns the page instead? This action can transitionTo accordingly. Then there is no need to abort at the willTransition level.

I’m not saying this is the solution … but this might get you out of the thorny situation you’re in?


Thanks for your message.

I need a global solution because user can click on some linkTo (main menu, some links in the page, etc). willTransition is a good place to know if we want to transition or not. It’s a place where we ask user if they want to quit the page without save their model or not :slight_smile:

A better option, given that there are a wide variety of ways users could end up in that state, is probably to register a global event handler for beforeunload, which you can make be the same as your Ember-specific navigation. That will let you handle not only internal navigation away, but also closing a tab, navigating via the back button, or killing the browser entirely.

Yes but a bit too limited. We already use beforeunload to display a native browser popup.

But, we would like to display a custom popup with 3 choices : cancel, save model before transition, do not save model before transition. So we thinked about willTransition hook. But it works differently when we click on a link (LinkTo) v.s. browser back button. It works without problem when we click on a link. But when we use browser back button, the displayed url change (= transition.to) and if we cancel transition, this bad url stay.