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.
How to distinguish between refresh (by F5/refresh button) and close browser?
You might want to use Cookies/window.sessionStorage.
You can set a cookie without an explicit expiration date so that it is available only for the current session (which is valid till user closes the browser window).
You can also use sessionStorage object, it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
You can follow this appraoch :
1.Create a cookie when user first visits the page document.cookie = "userloggedin=true";
OR set sessionStorage.userLoggedIn = true;
2.Cookie will be available after refresh/closing and reopening tab , if cookie is not present then it means user closed the window and re-opened it.
Similarly sessionStorage data will be deleted after user closes browser tab
Hope this helps !
Related Topics
JavaScript Change Background Color on Click
"Status Code:200 Ok (From Serviceworker)" in Chrome Network Devtools
Jquery Add Class Based on Page Url
How to Dynamically Remove a Stylesheet from the Current Page
Jqgrid Viewgridrow Dialog Big Span and Icon
Draw a Circle Around Nodes Groups
Why Is String Concatenation Faster Than Array Join
How to Get Get and Post Variables with Jquery
Angular Ie Caching Issue for $Http
Chrome 65 Blocks Cross-Origin <A Download>. Client-Side Workaround to Force Download
Making Sure at Least One Checkbox Is Checked
How to Access Styles from React
React - Prevent Event Trigger on Parent from Child
Remove/Reset Inherited CSS from an Element
JavaScript Equivalent of Ruby's String#Scan