Is there a way in javascript to detect if the unload event is caused via a refresh, the back button, or closing the browser?
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.
Detect browser or tab closing
If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in JavaScript to detect that is to use either onunload
or onbeforeunload
events.
Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close
in JavaScript. Correct me if I'm wrong here.
Logout on tab closed
As per here Is there a way in javascript to detect if the unload event is caused via a refresh, the back button, or closing the browser? there is no way to detect the difference. Even if you could there would be other circumstances where it wouldn't work.
Related Topics
How to Detect If JavaScript Files Are Loaded
Differencebetween Settimeout(Fn, 0) and Settimeout(Fn, 1)
Properties of JavaScript Function Objects
Why Do People Put Code Like "Throw 1; <Dont Be Evil>" and "For(;;);" in Front of JSON Responses
How to Sign into Google with Selenium Automation Because of "This Browser or App May Not Be Secure."
JavaScript Property with Three Dots (...)
Regular Expression for Url Validation (In JavaScript)
Unexpected Token Illegal in Webkit
JavaScript Curry: What Are the Practical Applications
Escaping Backslash in String - JavaScript
Prevent JavaScript Keydown Event from Being Handled Multiple Times While Held Down
Passing Data to a Jquery UI Dialog
Single Quote Escape in JavaScript Function Parameters
How Does Internationalization Work in JavaScript