Is There a Way in JavaScript to Detect If the Unload Event Is Caused via a Refresh, the Back Button, or Closing the Browser

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



Leave a reply



Submit