2012-02-21 39 views
12

我想在用户使用jQuery放弃特定页面时执行操作方法。

页具有下面的代码:

<script type="text/javascript"> 

     $(window).unload(function() { 
      alert("Handler for .unload() was called."); 
     }); 

    </script> 

当我导航离开该页面我从来没有看到预期的警告。

+1

你在其他浏览器中试过吗?你试过什么浏览器? jQuery网站上的文档很清楚,因为这个事件非常不稳定。 – anddoutoi 2012-02-21 22:08:11

+1

卸载已弃用,请检查:https://api.jquery.com/unload/ – 2017-05-10 13:09:51

回答

25

实际上,如果您尝试在窗口unload中尝试alert,则某些浏览器(如Google Chrome)可能会阻止。作为用户,我喜欢这个功能。警报每次你试着从一个页面吮吸导航离去:

enter image description here

console.log或者更少侵入到用户和事件的东西更换警报将被称为愉快。

您可能还想结算onbeforeunload活动。

+0

谢谢。我知道卸载事件是不稳定的,但我不知道铬(这是我使用的)的行为就像那样。 – 2012-02-22 19:52:18

+0

@Darin Dimitrov:使用console.log替换警报不会带来太多有用的效果,因为在刷新页面或导航到另一个控制台之后,控制台(至少在Chrome中)正在清除。你可以看到你的消息的痕迹,在它们真正消失之前的几个毫秒内写入,所以我宁愿觉得它没用。禁用卸载警报不是最好的主意。很难做一些严肃的测试,通过显示自己的“恼人的”消息,而不是使用警报(jQuery UI,某些div等),“糟糕”的页面可以轻松实现解决方法。 – trejder 2012-07-17 14:28:35

+7

@trejder如果你右键点击控制台中的chrome,有一个选项可以保存导航日志 – Luke 2013-03-21 14:39:03

0
window.onbeforeunload=navigationError; 

var dont_confirm_leave = 0; var leave_message = 'You sure you want to leave?'; 

function navigationError(e) 
    { 
    if(dont_confirm_leave!==1) 
    { 
     if(!e) e = window.event; 
     //e.cancelBubble is supported by IE - this will kill the bubbling process. 
     e.cancelBubble = true; 
     e.returnValue = leave_message; 
     //e.stopPropagation works in Firefox. 
     if (e.stopPropagation) 
     { 
     e.stopPropagation(); 
     e.preventDefault(); 
     } 

     //return works for Chrome and Safari 
     return leave_message; 
    } 
    } 
10

jquery .on('unload',..);对我来说并不可靠。我切换到beforeunload之前使用。只要确保你没有返回任何东西,否则用户会得到一个“你确定要离开页面” - popup。

<script type='text/javascript'> 
    $(window).on('beforeunload', function(){ 
     console.log("beforeUnload event!"); 
    }); 
</script> 
+0

虽然Darin的答案是正确的,但用户应该真的参考这个答案。使用“onbeforeunload”不仅可以让你触发警报,而且与卸载不同,它也是推荐和可靠的,至少对于Chrome而言,它是非常麻烦的。 – 2016-09-21 02:21:37

5

为bhelm说 beforeunload 作品对我来说也是如此。
回报这个事件false将调用浏览器的默认

你确定要离开这个页面?


$(window).on('beforeunload', function() 
    { 
     return false; 
    }); 
0

,如果你想提醒你离开这个页面,然后用户如果

/* $(window).unload(function() 
 
{ 
 
\t //alert("you leaving this page"); 
 
\t console.log("you leaving this page"); 
 
}); */

功能不是为你工作,然后更换你的代码与on(“beforeunload”,功能)像这样

$(window).on("beforeunload", function() 
 
{ 
 
\t alert("you leaving this page"); 
 
\t console.log("you leaving this page"); 
 
});

这个工作对我来说!你可以看到控制台日志中的输出 you leaving this page