1

I am trying to know if user closes the page, not clicking back button or write another website in url bar to leave. I have tried this,

$(window).bind('beforeunload', function () {

logout();

});

It works, but it fires also when user clicks back button or write another url and go. My question is, is it possible to know if user closes the page ?

user198989
  • 4,574
  • 19
  • 66
  • 95
  • Why are you trying to exclude the other forms of navigation? Wouldn't you still need to logout in those cases? – nnnnnn Jul 06 '13 at 05:55
  • Look at this que.. http://stackoverflow.com/questions/15769514/window-onclose-function This may suggest you something. – hriziya Jul 06 '13 at 05:58
  • Do you really mean "know if the user leaves the website?" because you said pressing back was OK. – Paul Jul 06 '13 at 05:59
  • I mean "How to know if user closes the page" – user198989 Jul 06 '13 at 06:01
  • 3
    I think you mean "...closes the browser" or "...closes the current browser tab", because navigating to another website _does_ close the current page - for all intents and purposes except yours, I guess... – nnnnnn Jul 06 '13 at 06:02

1 Answers1

2

There's an alternative but it's expensive and also really depends on the user case. It works wonders for me at a simple chat we did. You can have the javascript to constantly (every few seconds) call a page with the user id, example.com/misc/alive/456457, where 456457 is the id of the user. You introduce then that call in a database table as a new row. If the user doesn't call back in more than X seconds, you assume he's gone.

Of course, you don't get an action just when the user 'is gone', you just get a database that then you've got to analyse to know when the user 'probably' left. For the chat example, it was as easy as calling it every 2 seconds and then checking if there was any user online in the last 5 seconds and delete duplicate ids (to give it some threshold).

Francisco Presencia
  • 8,732
  • 6
  • 46
  • 90
  • But that method still doesn't do what the OP is asking, i.e., it doesn't distinguish between the browser closing versus navigating to some other site. – nnnnnn Jul 06 '13 at 06:19
  • Thanks for the information but it really doesnt what I need. It also tracks if users click back button or type another website and go. – user198989 Jul 06 '13 at 06:19