'beforeunload' Chrome Issue

前端 未结 6 1937
不思量自难忘°
不思量自难忘° 2021-02-07 08:40

I have this simple piece of code -

$(window).bind(\'beforeunload\', function(){
    alert(\"Good Bye\")
});

Works great with Firefox, IE8 but

相关标签:
6条回答
  • 2021-02-07 08:47

    Try this for all Browsers:-

    window.addEventListener("beforeunload", function (e) {
    
      var confirmationMessage = "\o/";     
      e.returnValue = confirmationMessage;           
      return confirmationMessage;       
    
    });
    
    0 讨论(0)
  • 2021-02-07 08:50

    I had to include it in a jQuery(document).ready to get it working in chrome

    <script>
      jQuery(document).ready( 
        function () { 
          jQuery(window).bind('beforeunload',  
            function (e) {  
    
              [code here]
    
            } 
          );
    
        } 
      );
    </script>
    
    0 讨论(0)
  • 2021-02-07 08:56

    Return a string instead:

    $(window).on('beforeunload', function(){
        return "Good bye";
    });​
    
    0 讨论(0)
  • 2021-02-07 09:03

    If you need to send some analytical data just before unloading the document, choose navigator.sendBeacon() method instead of XMLHttpRequest.

    sendBeacon() method is designed to perform non-blocking sending of a small amount of data.

    But check canIuse report first, since the method is not supported globally yet.

    0 讨论(0)
  • 2021-02-07 09:04

    Try this:

    function LogTime(){
    
    jQuery.ajax({
      type: "POST",
      url: "log.php",
      data: "",
      cache: false,
      success: function(response){
    
      }
    });
    

    }

     $(window).bind('beforeunload', function(){
         LogTime();
         return "You're leaving?";
     });
    

    It seems that as long as you return a string for this event at the end of function body, you can run code before that string.

    0 讨论(0)
  • 2021-02-07 09:05

    Try below:

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