如何在javascript中改变beforeunload事件

时间:2012-08-18 12:44:32

标签: javascript onbeforeunload

在某人决定离开页面之前调用ajax函数是否可行。我的意思是我可以询问用户是否想要离开或留下。但是当用户点击“是离开页面”按钮时,我不知道如何改变行为。

我有这个代码工作..

<head>
<script type="text/javascript">
    function catchExit() {
        return "All your data is going to be lost. Are you sure??";
    }
</script>
</head>
<body onbeforeunload="return catchExit()">
<p>
    Dont leave the page.
</p>
</body>

2 个答案:

答案 0 :(得分:1)

以下是使用confirm的替代方法:

function catchExit(){
  var exit = confirm("Are you sure?");
  if (exit){
  }
}

但请记住,AJAX无法阻止线程。这意味着无法保证通话​​:

  1. 制作
  2. 成功
  3. 返回结果
  4. 在AJAX甚至可能完成之前,窗口将显示提示和/或退出。为了更好地说明它:

    function catchExit(){
      $.ajax({
        success: function(){
          // this is an entirely new thread and returning a result
          // has ZERO effect on the original catchExit function
          // (And chances are it's already executed and is long gone)
        }
      });
      // this (99.99% of the time) will be called long before
      // 'success' above is called, therefore making 'success' and its
      // outcome moot.
      return "There are unsaved changes, are you sure you want to exit?";
    }
    

答案 1 :(得分:0)

实际上,我找到了一种让$.ajax()通话工作的方法。将async参数设置为false适用于firefox,chrome,iexplorer和safari。它只适用于歌剧。

相关问题