Please explain what you want to do when the browser closes, to see if there perhaps is another way to do so.
A web server sends its response to the browser, and then (usually) closes the connection. You'd have to do something in Javascript, but that won't catch all conditions. You certainly can't detect it serverside.
It can be detected using the Javascript onbeforeunload
or onunload
functions, but that is absolutely not accurately, since it won't detect:
- a browser crash
- a browser exit
- a computer shutdown
- a link click on the page
- when going Back in the browser
Also see this answer.
So for example when you want to log out users when they close the browser, you'd better use a "keepalive" mechanism instead of a "say goodbye" one. You can then log those users off on the server (e.g. using cron
) whose sessions have not been active (i.e. who haven't sent a "keepalive") for more than X minutes.