简体   繁体   中英

Alert user when they are leaving a page

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?

 <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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM