skos
skos

Reputation: 4212

'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

Upvotes: 20

Views: 57576

Answers (6)

miro
miro

Reputation: 780

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.

Upvotes: 1

Abhishek Salgaonkar
Abhishek Salgaonkar

Reputation: 146

Try this for all Browsers:-

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

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

});

Upvotes: 7

Marcelo Noronha
Marcelo Noronha

Reputation: 815

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.

Upvotes: 2

user1703776
user1703776

Reputation: 61

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>

Upvotes: 6

xdazz
xdazz

Reputation: 160833

Try below:

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

Upvotes: 6

Sampson
Sampson

Reputation: 268344

Return a string instead:

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

Upvotes: 18

Related Questions