Last Updated: January 20, 2020
· tellez12

Confirmation on Leaving the Current Page in an Angular.js App

Sometimes when you have a big form, you want to make sure that a user who is leaving the page and loosing some changes knows about it and its not doing it by mistake.

Previously we would manage it with something like this:

window.onbeforeunload = function (e) {
   return "Are you sure you want to navigate away from this page";      

This approach does work but does not take into considerations SPA (Single Page Applications), when you navigate in a SPA the onbeforeuload event its not fired, so if you only use this approach you would be missing the confirmation when navigate to other page inside your application.

In order to solve that problem with Angular you can use the Event $locationChangeStart.

 $scope.$on('$locationChangeStart', function (event, next, current) {
     if (check(next+current)) {
         var answer = confirm(Are you sure you want to navigate away from this page);
       if (!answer) {

In here we receive the event plus the URL where you are trying to go (next) and the current URL, in this case in the check we do some validations that according to where we are going and were we are sometimes we don't want to show the confirmation.

Other important thing is in the first option you need to make sure that if you have a condition to decide if you show or not the confirmation, when you don't want to show it you have to return undefined this fix a problem with IE that without it, it never show the confirmation.

 window.onbeforeunload = function (e) {
   return check(document.URL);      
 return undefined;

4 Responses
Add your response

Thanks, I was looking for a way to do this.

over 1 year ago ·

Pardon my possible oversight but In your example you are not using the message variable anywhere. Is there a specific place that you are going to use this? Thanks for the article.

over 1 year ago ·

Hey thanks for pointing it out, I use it in my application but for simplicity I'm not using it in this example and that line there was a copy mistake :)

over 1 year ago ·

You forgot ' tags on confirm message

over 1 year ago ·