I have been trying to bind beforeunload
event by calling the following script so that I can go to the specified URL through AJAX
. The problem is that the AJAX
is not working the first time as the URL does not get called when the first time I do the page refresh. The second time ajax works. This problem gets fixed when I set async
to false
but then the alert popup inside success
doesn't show up. I need alert box to also show up in success
block.
<script type="text/javascript">
$( document ).ready(function() {
// this method will be invoked when user leaves the page, via F5/refresh, Back button, Window close
$(window).bind('beforeunload', function(event){
// invoke the servlet, to logout the user
$.ajax({
cache: false,
type: "GET",
url: "LogoutController" ,
success: function (data) {
alert("You have been logged out");
}
});
});
});
</script>
beforeunload
will wait for the event handler to finish its execution before closing the page. Since an ajax call is asynchronousbeforeunload
is not going to wait for it to finish (your server however should still get the request). This is the expected behaviour and I don't think they is a way around it.This behaviour can be reproduces using the following code:
Also, you should note that, according to MDN the specs states that alert() can be ignored:
When this happens on chrome (only browser I checked) you will get the following message in the console: