当用户意外离开ASP.Net页面时如何捕获

当用户意外离开我的ASP.Net页面时,我需要提示用户询问他们是否确定要离开。 回发或单击保存按钮时不应触发警告。 有很多文章涵盖了这一点,但我对此全新,似乎已经让我的电线交叉。

推荐的方法似乎是使用window.onbeforeunload事件但对我来说意外行为。 在页面加载时触发此操作,而不是在页面卸载时触发。

 window.onbeforeunload = confirmExit; function confirmExit() { return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?"; }  

如果我使用JQuery实现,它会在页面卸载时触发,但问题是在执行代码之后它会触发。 所以我不能在客户端上设置一个变量,说这次不会触发事件,因为它是回发或保存。

 $(window).bind('beforeunload', function () { return 'Are you sure you want to leave?'; }); 

任何人都可以指出我正确的方向,因为我知道我正在犯错误/错过理解吗?

编辑:

所以我快到了:

var prompt = true;

 $('a').live('click', function () { //if click does not require a prompt set to false prompt = false; }); $(window).bind("beforeunload", function () { if (prompt) { //reset our prompt variable prompt = false; //prompt return true; } }) 

除了问题在上面的代码中我需要能够区分点击,但我还没有能够解决这个问题,即我在这里错过了一个条件“//如果点击不需要将提示设置为false ”。

有任何想法吗?

谢谢,迈克尔

您可以尝试使用此:

 $(window).unload(function(){ alert('Message'); }); 

如果人们感兴趣,这是解决我问题的迂回解决方案。 如何判断ASP中的页面卸载是否为PostBack