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

Dims picture Dims · Feb 10, 2012 · Viewed 7.8k times · Source

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

This worked:

$(window).bind("beforeunload",
    function() {
        $.ajax({
            async: false,
            url: 'notify'
        });
    }
);

Answer

mofojed picture mofojed · Jun 25, 2018

The other answers are out of date, and cause other issues, such as unreliable signalling or delaying the load of the next page.

The best solution is to use navigator.sendBeacon: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

window.addEventListener("unload", logData, false);

function logData() {
  navigator.sendBeacon("/log", analyticsData);
}

This method addresses the needs of analytics and diagnostics code that typically attempts to send data to a web server prior to the unloading of the document. Sending the data any sooner may result in a missed opportunity to gather data. However, ensuring that the data has been sent during the unloading of a document is something that has traditionally been difficult for developers, because user agents typically ignore asynchronous XMLHttpRequests made in an unload handler.

To solve this problem, analytics and diagnostics code have historically made a synchronous XMLHttpRequest call in an unload or beforeunload event handler to submit the data. The synchronous XMLHttpRequest blocks the process of unloading the document, which in turn causes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance, and the result is that the user perceives that the new web page is slow to load, even though the true issue is with the previous page.