简体   繁体   English

在用户离开页面时提醒用户

[英]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: 我想提醒用户何时离开页面,无论是通过关闭选项卡或窗口,还是通过链接进入新的URL等方式。目前,我有以下代码:

$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. 这是什么,当我离开带有'fairs /'(URI)的页面时,它会弹出确认框。 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 ) 您可以在角路由中使用'resolve'运行函数( 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. 您还可以在事件$routeChangeStart上放置一个侦听$routeChangeStart ,并根据情况进行中断。 See the solution here it might help you. 请在此处查看解决方案它可能会对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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