I want to alert the user when they are going to leave the page, whether by closing the tab or window, going to a new URL through a link, etc. Currently, I have the following code:
$scope.$on('$locationChangeStart', function (event, next, current) {
if (current.match("fairs/")){
var answer = confirm("Are you sure you want to leave this page?");
if (!answer) {
event.preventDefault();
}
}
}
What this does is it pops up the confirmation box when leaving a page with 'fairs/' (a URI) which is what I want. However, it pops up after the page is redirected, so if you click Cancel and it tries to prevent the the default event, it stays on the redirected page. Then, if you try and leave that page, the confirmation box will pop up again because the browser still thinks it's on the 'fairs/' page.
I got my solution from another question but that's not working for me. How do I get it so the confirmation box pops up before the page is redirected?