Search code examples
javascriptjquerynotificationsonbeforeunloadonunload

Don't have time to send get request on window unload


I want to notify the server on user closes browser window.

I tried all of the

$(window).bind("beforeunload", function() {
    $.get("${contextPath}/notify?direction=logout");
});

and

$(window).unload( function() {
    $.get("${contextPath}/notify?direction=logout");
});

and

$(window).unload(function() {
    $.ajax({
      url: "${contextPath}/notify?direction=logout"
    });
});

but neither work well, despite the fact, that it is said in manual that it probably should.

In Firefox I have no notifications only on window close, but have ones on page refresh. In Chrome I have neither.

I tried to trace this script in Firebug or Chrome Developer Tools and found, that it is starting to work if traced! So I think it does not work normally because it has no time to send request before window closed or navigated.

Is this true? How to accomplish my task?


Solution

  • It is very tricky because the browser will not wait untill the response comes so the ajax request might get aborted.

    You can try something like this in beforeunload event.

    $(window).bind("beforeunload", function() {
        $.ajax({
            async: false,//This will make sure the browser waits until request completes
            url: "${contextPath}/notify?direction=logout"
        });
    });