A custom JavaScript prompt is triggered when a user clicks the back button on their browser by monitoring the $stateChangeStart event. Let's explore this scenario:
Imagine users moving through pages 1, 2, and finally reaching page 3. Upon trying to go back from page 3 using the back button, they encounter a confirmation box. If the user opts to click 'Cancel', event.preventDefault() is invoked, keeping them on the current page. However, if they proceed to click 'OK' upon attempting to go back again, they are taken all the way back to page 1. The whereabouts of page 2 seem baffling. Does event.preventDefault() erase the last history? How can one ensure that the browser does not skip over the preceding page?
$rootScope.$on('$stateChangeStart',
function (event, toState, toParams, fromState, fromParams) {
var retVal = confirm("You have unsaved changes. If you leave the page, these changes will be lost.");
if (retVal == false) {
// User has chosen to remain on the current page
event.preventDefault();
}
});