THEK THEK - 1 year ago 160
Javascript Question

Detect window closed

I'm creating a chat client which uses a database to check the status of a session 0-waiting, 1-running, 2-closed.

I have a close button which will change the status to 2 but I was wondering, how do I detect if the browser is closed just by pressing x?

The main reason for this is I don't want the session showing up as running when one of the participants has closed their browser.

Answer Source

use the unload and onbeforeunload events:

window.onunload = window.onbeforeunload = function (){...};

It's better to register to both of the events to be sure the callback will fire.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download