How to detect browser closing?

后端 未结 6 1581
故里飘歌
故里飘歌 2020-11-28 13:48

In my web app, when a user logs in, I add his Id to a vector of valid Ids in the servlet, when he logs out, I remove his Id from the vector, so I can see how many current us

6条回答
  •  悲&欢浪女
    2020-11-28 14:13

    I had to do that recently, and after some searches, I found some solutions on the Net... all of them non working universally!

    onbeforeclose and onclose events are used for this task. But there are two catches: they are fired when the user reload the page or even just change the current page. There are tricks to see if the event is actually a window/page/tab closing (looking at some Dom properties going haywire on closing event), but:

    • They are browser dependent
    • The tricks are undocumented, thus brittle
    • And actually they vary along the browser version/update...

    And worst of all, these events are now ignored by most modern browsers, because they have been abused by rogue ads popping out windows when browser was closing. They are not fired in Safari, Opera, IE7, etc.

    As pointed out, most Web applications with login destroy the user session after a while, eg. half an hour. I was asked to logout on browser closing to free faster a precious resource: licenses. Because users often forget to log out...

    The solution I gave was to ping with an Ajax request (sending the user ID) the server on regular intervals (say 1 minute). If the server receives no ping for, say, 3 minutes, it disconnect the user.

提交回复
热议问题