问题
I have an urge to detect when a user leaves my site in order to record accurately the session length of the user in question. I have thought of a couple possible solutions for this:
I first thought I could use onbeforeunload and send a simple ajax to record the last activity but what practice has shown me is that onbeforeunload is unreliable for now and it's a bad idea to use it since it's not cross browser.
Then I thought I could use cookies to record the user's session length, respectively increase the cookie value every time a user has shown activity. The problem here is that I cannot detect which would be the user's last activity and the only possible way I can safely insert the session length and know it's accurate is when the user hasn't logged in for quite some time and the cookie's value would be the last session length. This wouldn't be suitable for me because many users may just open the site once and never visit it again ( for example ), then none of those users would be recorded.
Does anyone have a solution for this issue? I seem to have searched but none of the answers I found were satisfying.
Thank you in advance!
回答1:
You could poll using Javascript. For instance if you have a ticker text or image scroller that loads new information using Ajax, you can use the times of those requests to guess the last activity. You could also do dedicated requests for it, but to the visitor that is a waste of bandwidth, and they might not like the idea of such strict monitoring.
You could also measure times between page views, and leave the last page view (the exit-page) out of the equasion.
回答2:
You can't tell when a user leaves your site, this is fundamentally unsupported by the underlying technology of the Internet. All you can do is tell the time of the last request made before the session expired.
回答3:
If you need to do this for specific users then the best bet is to do an Ajax request, say, every 60 seconds, and record the timestamp against their session in your database. When you're measuring the responses you can classify anything beyond a reasonable cut-off as having 'left' (for example 20 minutes for a typical browser session).
If you don't need this data for individual users and just want an average metric for your visitors, you may as well just use Google Analytics.
回答4:
Alright, judging by the given answers in order to reduce bandwidth waste to the minimum here's what I decided to do:
if('onbeforeunload' in window){
window.onbeforeunload = function(){ Send last activity ajax call }
}else{
setInterval(Send activity update, 30000);
}
Thank you for your responses!
来源:https://stackoverflow.com/questions/16885544/detect-user-exit-site