1

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?

Noble Mushtak
  • 1,784
  • 10
  • 22

2 Answers2

0

<script type="text/javascript">
     var popit = true;
     window.onbeforeunload = function() { 
          if(popit == true) {
               popit = false;
               return "Are you sure you want to leave?"; 
          }
     }
</script>

Try the above

Bill
  • 21
  • 3
  • That is only working if I reload a page, I want it to pop up if i change from a specific page to anything else. Meaning I want a pop up if the user tries to close the tab/window, url change, or refresh. – Colleen Caffey Apr 20 '15 at 14:21
  • The above code excecutes onbeforeunload, this is the very last thing, are you placing this code above any other? – Bill Apr 20 '15 at 14:23
  • Ok now I placed it at the end of my html and it works but it is still redirecting before the window pops up – Colleen Caffey Apr 20 '15 at 14:25
0

you can run a function using 'resolve' in angular-routing (docs router)

Something like that should work I think:

$routeProvider.when('/myPage', { templateUrl: 'myPage.html',
        resolve: {
            myFunction: function ($route) { 
               if (myCondition) {
                   $location.url('/myPage');
                   return;
               } 
            }
        }
    });

You can also put a listener on the event $routeChangeStart, and interrupt depending on your condition. See the solution here it might help you.

Community
  • 1
  • 1
tanou
  • 1,083
  • 2
  • 13
  • 33