JavaScript Beforeunload Detect Refresh Versus Close

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



Leave a reply



Submit