[SOLVED] canDeactivate() not called when routing to external URL

Hello there,

in our application, we use the router with child routers to navigate, which works fine.
We have a page containing a form. When the user wants to leave the form (for instance by clicking a navigation link), a warning message should be displayed asking the user whether he really wants to navigate away.
I implemented this successfully by using the canDeactivate() lifecycle hook.

Additionally, in our navigation bar, there is a link which points to an external URL.
This link is called by using the router in the following way.
Create the route:

const config = { route: 'myRoute', name: 'myRoute', redirect: 'https://discourse.aurelia.io/' };
this.router.addRoute(config);

Call the route:

this.router.navigateToRoute('myRoute');

The routing to the external URL works fine.
However, the problem is that the canDeactivate() is not called.

Additionally, I listen to the router:navigation:processing event.
This event is fired, so I suppose the router is working fine. However, pipeline steps are not called…

Why is the canDeactivate() hook not called and what can be done in order to make this work?

Thanks for any help!

Does it work if you just put a normal link?

Do you mean like this?

<a href="https://discourse.aurelia.io/"></a>

No, this does not work either, the hook is never called.

As a workaround, can’t you route to a local route which then calls the external url?

Yeah, that’s what I ended up doing and it works.

Thank you for the help!

clarification from @EisenbergEffect:

There’s no way to hook the external nav other than by wiring to the browser’s unloaded event. That’s not guaranteed to fire and it requires a synchronous true/false response to stop the navigation, so it won’t work with the async lifecyle ;(
Becuase of the caveats we didn’t implement anything in the framework. I think that app devs could work up an app-specific solution for their specific scenarios though.

1 Like

Nice to know, thank you for the clarification :+1:

1 Like

Can you explain how did you manage to do it? May be point me in the right direction.