简体   繁体   中英

How to know if user closes the page?

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 ?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM