Trying to detect browser close event

后端 未结 11 607
广开言路
广开言路 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:16

    Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.

    The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').

    $(window).on('mouseover', (function () {
        window.onbeforeunload = null;
    }));
    $(window).on('mouseout', (function () {
        window.onbeforeunload = ConfirmLeave;
    }));
    function ConfirmLeave() {
        return "";
    }
    var prevKey="";
    $(document).keydown(function (e) {            
        if (e.key=="F5") {
            window.onbeforeunload = ConfirmLeave;
        }
        else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
            window.onbeforeunload = ConfirmLeave;   
        }
        else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
            window.onbeforeunload = ConfirmLeave;
        }
        else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
            window.onbeforeunload = ConfirmLeave;
        }
        prevKey = e.key.toUpperCase();
    });
    

    The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().

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

    As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,

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

    more details can be found at : developer.mozilla.org

    0 讨论(0)
  • 2020-11-22 06:22
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    
    <script type="text/javascript" language="javascript">
    
    var validNavigation = false;
    
    function endSession() {
    // Browser or broswer tab is closed
    // Do sth here ...
    alert("bye");
    }
    
    function wireUpEvents() {
    /*
    * For a list of events that triggers onbeforeunload on IE
    * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
    */
    window.onbeforeunload = function() {
      if (!validNavigation) {
    
                var ref="load";
          $.ajax({
                type: 'get',
                async: false,
                url: 'logout.php',
     data:
                {
                    ref:ref               
                },
                 success:function(data)
                {
                    console.log(data);
                }
                });
         endSession();
      }
     }
    
    // Attach the event keypress to exclude the F5 refresh
    $(document).bind('keypress', function(e) {
    if (e.keyCode == 116){
      validNavigation = true;
    }
    });
    
    // Attach the event click for all links in the page
    $("a").bind("click", function() {
    validNavigation = true;
    });
    
     // Attach the event submit for all forms in the page
     $("form").bind("submit", function() {
     validNavigation = true;
     });
    
     // Attach the event click for all inputs in the page
     $("input[type=submit]").bind("click", function() {
     validNavigation = true;
     });
    
    }
    
    // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
    wireUpEvents();  
    }); 
    </script> 
    

    This is used for when logged in user close the browser or browser tab it will automatically logout the user account...

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

    Have you tried this code?

    window.onbeforeunload = function (event) {
        var message = 'Important: Please click on \'Save\' button to leave this page.';
        if (typeof event == 'undefined') {
            event = window.event;
        }
        if (event) {
            event.returnValue = message;
        }
        return message;
    };
    
    $(function () {
        $("a").not('#lnkLogOut').click(function () {
            window.onbeforeunload = null;
        });
        $(".btn").click(function () {
            window.onbeforeunload = null;
    });
    });
    

    The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.

    One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.

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

    You can try something like this.

    <html>
    <head>
        <title>test</title>
        <script>
            function openChecking(){
                // alert("open");
                var width = Number(screen.width-(screen.width*0.25));  
                var height = Number(screen.height-(screen.height*0.25));
                var leftscr = Number((screen.width/2)-(width/2)); // center the window
                var topscr = Number((screen.height/2)-(height/2));
                var url = "";
                var title = 'popup';
                var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
                var popup = window.open(url, title, properties);
                var crono = window.setInterval(function() {
                    if (popup.closed !== false) { // !== opera compatibility reasons
                        window.clearInterval(crono);
                        checkClosed();
                    }
                }, 250); //we check if the window is closed every 1/4 second
            }   
            function checkClosed(){
                alert("closed!!");
                // do something
            }
        </script>    
    </head>
    <body>
        <button onclick="openChecking()">Click Me</button>
    </body>
    </html>
    

    When the user closes the window, the callback will be fired.

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

    jQuery .bind() has been deprecated. Use .on() instead

    $(window).on("beforeunload", function() {
        runBeforeClose();
    });
    
    0 讨论(0)
提交回复
热议问题