2

I am using jQuery bind:

$(window).bind('beforeunload', function() {
   //code
   return "";
   }

If I do not give return "", it works fine in mozilla firefox, IE8. It does not give an alert box saying "Are you sure you want to navigate away from this page?" However in google chrome, beforeunload event does not work without return "" statement.

And if I use return"", it gives an alert box in all broswers.

I do not want the dialog box and I want beforeunload event to work. Please help. Please suggest if there is any other alternative solution to this. Thanks.

Akshaya
  • 61
  • 5

1 Answers1

1

onbeforeunload has not a behaviour consistent across browser

You should set all your ajax calls to async false inside function you call in beforeunload event and then try this ugly hack:

$(window).on('beforeunload', function (e) {
    if (e.originalEvent) 
       //Call function for updating omniture site 
    else  //this is to provide enough time to all your other requests to be send
    $.get("", {
        async: false
    });
    $(this).trigger('beforeunload'); //will create kind of infinite loop
    //this is an ugly hack because many useless request will be send (but nowhere)
}

Test it and let me know.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • is `e` cross-browser compatible? I recon seeing errors in a few browser when using the variable `event` without adding it to the function declaration `$(window).on('beforeunload', function (e) {` – Jeff Noel Jul 31 '13 at 12:25
  • @JeffNoel sorry, forgot to add it – A. Wolff Jul 31 '13 at 12:27
  • No problem sir, I just wanted to make sure the OP wouldn't face another issue in 5 minutes (that was also an open question, it would be awesome if all browsers would have a common variable for the `event` object). – Jeff Noel Jul 31 '13 at 12:29
  • @roasted - Thanks. It works fine. Found alternative solution too. Binding beforeunload in ready. $(document).ready(function(){ //code $(window).bind('beforeunload', function(e) { //code }); }); – Akshaya Jul 31 '13 at 13:21