DonkeyKong
DonkeyKong

Reputation: 818

how to alter beforeunload event in javascript

Is calling an ajax function possible before someone's decide to leave the page. I mean i can ask the user if user wants to leave or stay. But i dont know how to alter behaviour when user click "yes leave the page" button.

I have this code working..

<head>
<script type="text/javascript">
    function catchExit() {
        return "All your data is going to be lost. Are you sure??";
    }
</script>
</head>
<body onbeforeunload="return catchExit()">
<p>
    Dont leave the page.
</p>
</body>

Upvotes: 0

Views: 574

Answers (2)

DonkeyKong
DonkeyKong

Reputation: 818

Actually, i found a way to get my $.ajax() call worked. Setting async parameter to false works in firefox, chrome, iexplorer and safari. It only doesn't work in opera.

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101604

Here's an alternative way using confirm:

function catchExit(){
  var exit = confirm("Are you sure?");
  if (exit){
  }
}

But keep in mind that AJAX can't stop the thread. That means that there's no guarantee the call:

  1. Makes it
  2. Is successful
  3. Returned a result

The window will have shown the prompt and/or exited before the AJAX may have even completed. To illustrate it better:

function catchExit(){
  $.ajax({
    success: function(){
      // this is an entirely new thread and returning a result
      // has ZERO effect on the original catchExit function
      // (And chances are it's already executed and is long gone)
    }
  });
  // this (99.99% of the time) will be called long before
  // 'success' above is called, therefore making 'success' and its
  // outcome moot.
  return "There are unsaved changes, are you sure you want to exit?";
}

Upvotes: 1

Related Questions