代码之家  ›  专栏  ›  技术社区  ›  Chris Ballance

拦截页面退出事件

  •  123
  • Chris Ballance  · 技术社区  · 16 年前

    4 回复  |  直到 5 年前
        1
  •  156
  •   Eli Grey    9 年前

    与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;
    };
    
        2
  •  26
  •   jantimon    16 年前

    看这篇文章。 您正在寻找的功能是 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>
    
        3
  •  6
  •   Community Mohan Dere    9 年前

    与其出现烦人的确认弹出窗口,不如 延迟离开 只需一点时间(几毫秒)就可以成功地将未保存的数据发布到服务器,我使用向控制台写入虚拟文本来管理我的网站,如下所示:

    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

        4
  •  0
  •   gordon    11 年前

    <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>