A generic onbeforeunload handler. Will check a condition, or a list of supplied conditions, to determine if it is safe to unload.
Take a look at the examples.
Install it from npm:
$ npm install before-unload
In the following example, the user will be prompted on the beforeunload event, if the ViewModel.hasChanges method returns a truthy value.
new BeforeUnload('Are you sure you want to leave?', function () {
return ViewModel.hasChanges();
});
In the following example, the user will be prompted on the beforeunload event, if the ViewModel.hasChanges method or the Storage.unsavedChanges method returns a truthy value.
new BeforeUnload('Are you sure you want to leave?', [
function () {
return ViewModel.hasChanges();
},
function () {
return Storage.unsavedChanges();
}
]);
In the following example, a different warning is shown for one of the conditions.
new BeforeUnload('Are you sure you want to leave?', [
function () {
return ViewModel.hasChanges();
},
function () {
return Storage.unsavedChanges();
},
function () {
return SomeObject.isItOkayToLeave() ? false : 'A custom error message';
}
]);
If you store a reference to the BeforeUnload object, you can unregister the event listener.
If a user attempts to leave the page after the unregister call, she will not be prompted.
var beforeUnload = new BeforeUnload(
'Are you sure you want to leave?',
function () {}
);
beforeUnload.unregister();