Trying to detect browser close event

后端 未结 11 608
广开言路
广开言路 2020-11-22 05:56

I have tried many methods to detect browser close event through jQuery or JavaScript. But, unfortunately, I have not been able to detect the close. The onbeforeunload<

相关标签:
11条回答
  • 2020-11-22 06:31

    Following script will give message on Chrome and IE:

    <script>
    window.onbeforeunload = function (e) {
    // Your logic to prepare for 'Stay on this Page' goes here 
    
        return "Please click 'Stay on this Page' and we will give you candy";
    };
    </script>
    

    Chrome
    enter image description here

    IE
    enter image description here

    on Firefox you will get generic message

    enter image description here

    Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.

    Response to question in comment

    F5 will fire event again, so will Atl+F4.

    0 讨论(0)
  • 2020-11-22 06:33

    Hi i got a tricky solution, which works only on new browsers:

    just open a websocket to your server, when the user closes the window, the onclose event will be fired

    0 讨论(0)
  • 2020-11-22 06:33

    Maybe it's better to use the path detecting mouse.

    In BrowserClosureNotice you have a demo example and pure javascript library to do it.

    It isn't perfect, but avoid problems of document or mouse events...

    0 讨论(0)
  • 2020-11-22 06:39

    Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.

    $(document).ready(function()
    {
        $(window).bind("beforeunload", function() { 
            return confirm("Do you really want to close?"); 
        });
    });
    

    For simple follow following steps:

    1. open http://jsfiddle.net/
    2. enter something into html, css or javascript box
    3. try to close tab in chrome

    It should show following picture:

    enter image description here

    0 讨论(0)
  • 2020-11-22 06:42
    <script type="text/javascript">
    window.addEventListener("beforeunload", function (e) {
    
      var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
      (e || window.event).returnValue = confirmationMessage;
      return confirmationMessage;
    
    });
    </script>
    

    Please try this code, this is working fine for me. This custom message is coming into Chrome browser but in Mozilla this message is not showing.

    0 讨论(0)
提交回复
热议问题