拦截页面退出事件

时间:2009-11-09 22:56:53

标签: javascript javascript-events internet-explorer

在我的系统中编辑页面时,用户可能决定导航到另一个网站,这样做可能会丢失他们尚未保存的所有编辑内容。

我想拦截任何转到另一个页面的尝试,并提示用户确保他们希望这样做,因为他们可能会失去当前的工作。

Gmail以非常类似的方式执行此操作。例如,撰写新电子邮件,开始在邮件正文中输入并在地址栏中输入新位置(比如twitter.com或其他内容)。它会提示“你确定吗?”

想法如何复制这个?我的目标是IE8,但希望兼容FF& Chrome也是。

4 个答案:

答案 0 :(得分:139)

与Ghommey的答案类似,但这也支持旧版本的IE和Firefox。

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

答案 1 :(得分:23)

请参阅此文章。 您正在寻找的功能是onbeforeunload

示例代码:

  <script language="JavaScript">
  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?";
  }
</script>

答案 2 :(得分:5)

不是一个讨厌的确认弹出窗口,而是延迟稍微(毫秒)管理成功将未保存的数据发布到服务器,这是我很好的使用我为我的网站管理的将虚拟文本写入控制台,如下所示:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

修改 另请参阅Synchronous_AJAX以及如何使用jquery

执行此操作

答案 3 :(得分:0)

我的用户还没有完成所有必需的数据。

<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
    <cfset unloadCheck=1>
    $("#myInput").change(function(){
        verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
        if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
        else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
    });
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
    verify();
    window.onbeforeunload = confirmExit;
    function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>