简体   繁体   中英

How to reliably run code on page close (e.g. “disconnected” message on site chat)

I have a 2-person site chat (us and any questioning clients) and I'd like to display " $client has disconnected" when they disconnect through any way, including:

  • Pressing back on the browser
  • Closing the window
  • Closing browser through task manager

I've yet to find a reliable way (attempting with JavaScript's onunload and onbeforeunload properties) to handle this, especially if the task manager was used.

What I'm thinking of doing is having the user keep calling an AJAX script where they increment some server-side value; this incrementation will stop when their page is closed. On our side, keep running a script that checks if that value has changed. If it hasn't changed after some arbitrary number of checks (eg 3), then the user has probably disconnected and it will display the message.

But there's no elegance in that, and "probably disconnected" isn't a really assuring conclusion.

How would you go about doing this, to ensure that the disconnect message occurs only when the user has disconnected.

actually, you can't really implement this on HTML/JS/CSS where once the user goes away, they're disconnected - well.. not efficiently that is.

you could try lowering the interval between polls but this has the negative effect of eating away bandwidth as well as degrading performance (constant polling like a forever-loop)

There is what they call comet which is a term that encompasses methods of "constant connection" - one of which is polling. also in the article are "middle-man" methods, where you can use plugins like flash and their streaming capabilities.

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