简体   繁体   中英

'beforeunload' Chrome Issue

I have this simple piece of code -

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

Works great with Firefox, IE8 but not in Chrome. Is it a known problem or is there any alternative for that ?

Actually what I am trying to do is to log details whenever user tries to close the browser.

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

$(window).bind('beforeunload', function(){
    LogTime();
});

This works well in Firefox, but not in Chrome

Return a string instead:

$(window).on('beforeunload', function(){
    return "Good bye";
});​

Try below:

$(window).on('beforeunload', function(){
  return "Good Bye";
});

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>

Try this for all Browsers:-

window.addEventListener("beforeunload", function (e) {

  var confirmationMessage = "\o/";     
  e.returnValue = confirmationMessage;           
  return confirmationMessage;       

});

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM