And WHERE are you calling that code FROM?
If it is from window.onbeforeunload it will never work.
And quite frankly, window.onbeforeunload is the only reliable place to put a "now leaving the page" trap. But the most you can do there is allow the user to cancel his request to leave the page.
(I have wondered if you could make a synchronous HTTP request at that point. I think you could, but that's beginning to get pretty complex.)
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.