Prevent accidental user data loss by conditionally guarding route transitions and url navigation.
Here is a demo app.
- Ember.js v3.28 or above
- Ember CLI v3.28 or above
- Node.js v14 or above
ember install ember-navigation-guard
This addon consists of 1 component and 1 service.
NavigationGuard
component
The NavigationGuard
component takes a boolean @shouldGuard
and an optional string @message
.
By default, enabling @shouldGuard
will set the onbeforeunload
browser hook to prompt on URL changes or window/tab close. This message is not configurable.
navigation-guard
service
To control route transitions within your Ember app, you will need to consume the service in your Router, or elsewhere in your app.
The navigation-guard
service has a preventNav
property that will be true when navigation should be prevented.
It also has a getMessage()
method to retrieve the first message that triggered preventNav
. If you want the last message instead, you can use getMessage({last: true})
.
// app/router.js
import EmberRouter from '@ember/routing/router';
import { inject as service } from '@ember/service';
export default class Router extends EmberRouter {
@service navigationGuard;
@service router;
...
constructor() {
super(...arguments);
this.router.on('routeWillChange', async (transition) => {
if (
this.navigationGuard.preventNav &&
!window.confirm(this.navigationGuard.getMessage())
) {
transition.abort();
}
});
}
}
...
See the Contributing guide for details.
This project is licensed under the MIT License.