ember-navigation-guard
v1.0.0
Published
An add-on to prevent accidental data loss on navigation
Downloads
10
Readme
ember-navigation-guard
Prevent accidental user data loss by conditionally guarding route transitions and url navigation.
Here is a demo app.
Compatibility
- Ember.js v3.28 or above
- Ember CLI v3.28 or above
- Node.js v14 or above
Installation
ember install ember-navigation-guard
Usage
This addon consists of 1 component and 1 service.
The NavigationGuard
component takes a boolean @shouldGuard
and an optional string @message
.
{{!-- app/components/my-component.hbs --}}
<NavigationGuard
@shouldGuard={{true}}
@message="This component is preventing navigation"
/>
By default, enabling @shouldGuard
will set the onbeforeunload
browser hook to prompt on URL changes or window/tab close. This message is not configurable.
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();
}
});
}
}
...
Contributing
See the Contributing guide for details.
License
This project is licensed under the MIT License.