|Terry Young on Aug 14, 2009 at 2:36:08 AM|
What makes this question particularly hard to answer and hit the nail, is that you have not explained exactly what action you need to take when that event fires. But I'll try my best shot at it.
"Unload" simply refers to the document. So even going from page A to page B still means that you are unloading page A.
There is no way to detect this. But there are some ways to get a close estimation, IF your purpose is generally just for analysis.
In general, whenever a page is loaded, a flag is raised "onload", meaning, yeah, this guy previously is viewing page A, and is now viewing page B, which simply means he has left page A, but has not yet left the site.
If, however, your last record shows that he last visited page B, and there are no further visits to the other page, then it is generally safe to say that within certain minutes, that guy has left from page B (or, has closed the browser and never viewed another page since then).
I had to do this once, when I have to display the date and time the user has LOGGED OFF (not ON). And, obviously, I end up recording the date and time of the last page visited. So, the user MUST have left between that time and the time that session would eventually expire inevitably. It's moronic to say that there is another possibility the guy has been staring at the page for 24 hours straight and has not yet left the page. I can't think of another way so far.
For the case I was facing, I could have done it even better, and fire an AJAX onunload to say, yeah, this guy is LOGGED OFF, and when the next page loads, onload fires and says, oops, it's a bogus, he's NOT logged off, he's still here. That way, I might be able to get an even more accurate estimate of the log off time. But it was a past project, and I'm not in control of that now. Plus, it's not worth it when you think of the case when the guy simply closes the browser, where the AJAX process I mentioned simply could not exist anymore.
Another idea, which I haven't tried, and which I don't think it's good either, is to periodically poll the server with a timer after any document onload is fired. On each poll, it tells the server to wait for the next poll to come, and if it doesn't come, then boom, we assume the guy is gone or that his browser exploded and is currently burning in flames. This, of course, brings a lot of stress to the server, and is better for Intranet projects. Not really suitable for public sites I think.
So, I would still go for my initial solution. And anyway, eventually the users don't really care how accurate in milliseconds it is with regards to the logoff time. It's not worth it if you already know there's no way to achieve absolute accuracy of it.
On the other hand, if what you're doing is not just for analysis purpose, and if you actually want something to fire and do AT THE MOMENT the guy leaves page B explicitly matching any one of your two cases, then I can simply tell you there's no way.