2

I am using the code below to fire a confirmExit() function when the user tries to leave the page:

window.onbeforeunload = confirmExit;
function confirmExit(){
    return "Are you sure you want to exit this page?";
}

Furthermore:

The page also fires AJAX functions to update a database 'on the fly'. As a result, when the user leaves the page, I need to delete all that 'on the fly' data.

Is it possible to call a javascript function when the user clicks the 'Leave Page' button?

proPhet
  • 1,188
  • 4
  • 16
  • 39
  • have you seen this discussion? http://stackoverflow.com/questions/821011/how-do-you-prevent-javascript-page-from-navigating-away – pistacchio Jan 31 '14 at 11:14

1 Answers1

5

You can try to use window.onunload:

window.onbeforeunload = function () {
    return "Are you sure?";
}
window.onunload = function () {
    console.log("Too bad. Goodbye.");
}

window.onunload will be fired only when user clicks "Leave this page" button.

If you want to do something if user clicks "Cancel" you can try the following approach:

window.onbeforeunload = function () {
    setTimeout(function () {
        setTimeout(function () {
            console.log("Great decision!");
        }, 200);
    }, 1);
    return "Are you sure?";
}

The first setTimeout puts your code to the event queue. It will be fired just after confirm box is closed. Second setTimeout will be fired after some time if page is not closed too soon.

For those who are doing some XHR onunload: make sure to use synchronous approach to complete your requests before the page is closed. E.g. use async: false in jQuery.ajax or XMLHttpRequest.open(method, url, false) in plain js.

vbo
  • 13,583
  • 1
  • 25
  • 33
  • @proPhet did you try what I am suggesting? Maybe I need to clarify this a bit more? – vbo Feb 03 '14 at 08:41