Search code examples
javascriptajaxcross-browserfire-and-forget

How can I increase the success of "window.OnBeforeUnload" to send an Ajax ping?


I've read dozens of questions and answers on S.O., and none of them answer my particular question... most of them center around popping up a "Oooh, you need to save" message... that is not my need.

I am building an application for internal use at my office (not a public website), and one "page" in particular we would like to log the 'exiting' by the user.

So, I have this simple statement:

window.onbeforeunload = function () {
    $.post('LogExit.aspx');
}

Now, this post will fail most of the time due to the browser not "wanting" to start a new request since it knows that the page is going away... but, if I add an annoying alert box, then it will send the ping 100% of the time!!!

Example:

window.onbeforeunload = function () {
    $.post('LogExit.aspx');
    alert("Ha ha ha, I can delay the browser!");
}

So, my question is... how do I ensure (or at least increase the chances of having) the "LogExit.aspx" ping going through?


Solution

  • Unfortunately there is no 100%, or even 10% "guaranteed" way of achieving this... so, I was able to solve my particular needs by having an every-10-seconds-send-a-ping function.

    Since my need was to log how long a person was viewing a particular page, this work-around above helps to at least get it down to a 10 second window of accuracy.

    I really hope a better solution comes down the pipe in the future.