Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax inside onbeforeunload is not working the first time

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>
like image 922
user2918640 Avatar asked Nov 10 '22 10:11

user2918640


1 Answers

beforeunload will wait for the event handler to finish its execution before closing the page. Since an ajax call is asynchronous beforeunload 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:

window.onbeforeunload = function () {
    console.log("bye");
    setTimeout(function () {
        console.log("bye1");
    }, 200);
    console.log("bye2")
};

//bye
//bye2

Also, you should note that, according to MDN the specs states that alert() can be ignored:

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.

When this happens on chrome (only browser I checked) you will get the following message in the console:

Blocked alert('test') during beforeunload.
like image 200
Thomas Eschemann Avatar answered Nov 14 '22 22:11

Thomas Eschemann