开发者

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

开发者 https://www.devze.com 2023-03-16 03:21 出处:网络
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'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?


Since you have to make some kind of request and don't really care about about the response, you can use an image in this case:

window.onbeforeunload = function () {
   var img= new Image();
   img.src = "LogExit.aspx";
   // you have to check on your server to see if it worked :)
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消