Search code examples
jqueryonbeforeunload

Query for window.onbeforeunload


window.onbeforeunload( function() { 
      return "Are you sure?" ;
});

I want to perform an an AJAX call before the page being unloaded, Is there any other way to achieve this, coz this doesn't work? Awaiting, thankss :)


Solution

  • If you want to run a function as the page is unloading, you can try $(window).unload(), but it can't stop the page from unloading or redirect the user. Also, some browsers block alerts in unload.

    $(window).unload(function(){
      $.ajax({url:"http://localhost:80/ajax.php?", async:false});
      alert('Bye.');
    });
    

    But your best bet is to do something like:

    $(window).bind('beforeunload', function(){
       $.ajax({url:"http://localhost:80/ajax.php?", async:false});
      return 'Are you sure you want to leave?';
    });
    

    //I tested this in IE9, Chrome, and Firefox and the ajax call fired successfully each time.

    JSFiddle example

    Also if you're doing an ajax request on page unload try setting async to false:

    $.ajax({url:"http://localhost:80/ajax.php?", async:false});