And what about when the user just types a new URL into the address bar? Or selects a URL from his/her Favorites? Or or or...
The best you can do--and it's not easy but it is possible--is to find out if the user is going to another page (or even the same page) on your site or is leaving your site.
And the way you have to do that is keep track of EVERY SINGLE WAY on the current page that they *CAN* go to another page (or reload same page) on YOUR site.
So what you can do is set a JS
variable to false:
var stayingOnMySite = false;
And then EVERY PLACE where the user might (for example) submit a <FORM> or click on an <A HREF> that will keep them on your site, you must CHANGE the flag to true
Then, finally, in the onunload or onbeforeunload code, you can check that flag and act accordingly.
Now... There are *STILL* some things you can't possibly catch. For example, if the user hits F5 (refresh) or hits the BACK button, you can't "see" those and so you will think the user *IS* leaving your site, even though he/she may not be.
But this is about as close as you can come.
You have to think long and hard about whether this very imperfect level of detectability is worth the effort.