Following the answer here, I have the code below:
.directive('confirmOnExit', function($window) {
return {
scope: {},
link: function(scope) {
var message = "Changes you made may not be saved.";
$window.onbeforeunload = function(){
return message;
};
scope.$on('$locationChangeStart', function(event) {
if(!$window.confirm("Do you want to leave this page? "+message))
event.preventDefault();
});
scope.$on('$destroy',function(){
$window.onbeforeunload = null;
});
}
};
})
On Chrome, everything is fine. However, on Firefox, almost every time I click the button of the confirm dialog, the error occurs:
Error: [$rootScope:inprog] $digest already in progress
The solutions I found online mostly suggest to use $timeout
. However, event.preventDefault()
inside a $timeout
function seems not preventing URL change. What should I do?