Ajax inside onbeforeunload doesn't work the first time

I am trying to bind an event beforeunload

by calling the following script to navigate to a specified url via AJAX

. The problem is that AJAX

doesn't work the first time as the url is not called on the first page refresh. Second time ajax works. This issue gets fixed when I install async

in false

, but then the warning popup inside is success

not shown. I need an alert box that is also displayed in the block success

.

 <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>

      

+3


source to share


1 answer


beforeunload

will wait for the event handler to complete until the page is closed. Since the ajax call is asynchronous beforeunload

, it won't wait for it to complete (your server should still receive the request). This is expected behavior and I don't think they are contributing to it.

This behavior can be reproduced using the following code:

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

//bye
//bye2

      

It should also be noted that according to MDN , the spec states that alert () can be ignored:



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

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

Blocked alert('test') during beforeunload.

      

+1


source







All Articles