Currently, I am working on incorporating a feature into my Angular module that will prompt an event to save any changes made on the page. There are multiple ways in which a user can navigate away from the page:
- Clicking on a link that directs to a new template.
- Using the back button in the browser.
- Closing the browser tab or window.
For handling scenario #1, I have utilized the following code snippet:
.directive('confirmOnExit', function() {
return {
link: function($scope, elem, attrs) {
window.onbeforeunload = function(){
return "If you leave this page, you will exit the practice session. You will be able to view your score report for the completed session but will have to start a new one if you want to continue practicing.";
}
$scope.$on('$locationChangeStart', function(event, next, current) {
if($scope.$dirty & confirm("Are you sure you want to leave this practice session?")) {
console.log("Will end session!");
end_session();
}
});
}
};
});
However, it seems like when encountering situations #2 and #3, although the popup dialog appears, the end_session()
function is not being triggered as expected.
I am open to suggestions and insights on how to address the issue of dealing with the back button and closing the tab/window effectively.