Jquery prevent window closing

前端 未结 2 901
旧时难觅i
旧时难觅i 2020-12-08 11:15

I want to ask user whether he really want to leave the page or not, when he clicks the close button just like it done in google docs. How to do that using jquery?

相关标签:
2条回答
  • 2020-12-08 11:32

    Following worked for me;

     $(window).unload(function() {
                    if(event.clientY < 0) {
                        //do whatever you want when closing the window..
                    }
                });
    
    0 讨论(0)
  • 2020-12-08 11:38

    You set the window's onbeforeunload property to a function.

    This post has a good example on how to do it.

    Or another example:

    <script language="JavaScript">
      var needToConfirm = true;
    
      window.onbeforeunload = confirmExit;
      function confirmExit()
      {
        if (needToConfirm)
          //return message to display in dialog box;
      }
    </script>
    
    ...
    
    <input type="Submit" value="Save" onclick="needToConfirm = false;" />
    


    And to set needToConfirm for your form you can:

    $(document).ready(function() { 
        $(':input', document.myForm).bind("change", function() { needToConfirm = true; }); // Prevent accidental navigation away
    });
    
    0 讨论(0)
提交回复
热议问题