Is there a way in javascript to detect if the unload event is caused via a refresh, the back button, or closing the browser? [duplicate]

No, and if there was it would be browser dependent.
What kind of code are you trying to run when the user closes the page?
Is it to logout the user?
Then the user would not be logged out if the browser crashes or the network connection breaks (and probably not if the computer goes to sleep/hibernation mode).

If it is for logout-purposes you should probably use a timestamp variable at the server that gets updated with every request (or use a ajax-ping), and logout the user if it hasn’t been seen for a specified time.

Update: Found this answer here at stackoverflow.

Leave a Comment