How to distinguish between refresh (with F5 / refresh button) and close the browser?
I have a requirement to handle events in the browser like back, refresh and close in cross browser. The problem is that my client wants different logic for each of these events. For the back button, this solution is pretty good:
but now it is difficult to distinguish between update and close, all solutions found are about using the "beforeunload" event:
- How to tell if the refresh button or the back button is clicked in Firefox .
- Handle page refresh event with javascript
- https://forums.asp.net/t/1829278.aspx?Detect+Browser+refresh+reload+button+click+in+all+browsers (this one doesn't work stably)
- https://www.quora.com/What-is-the-best-way-to-detect-refresh-event-in-jquery
- https://www.sitepoint.com/community/t/detect-refresh-button-in-the-browser/1119/22
For updating to F5, I can catch the keyboard event, but when the user presses the refresh button in the browser, I cannot. If I use "beforeunload" it happens when the browser is closed.
I also found a workaround:
- Determining between refreshing and closing browser actions
- How can I detect page refresh using jquery?
but unfortunately I want to show the message before the page is unloaded (show when the browser is close, but not when refreshing)
Does anyone know a solution for it (cross browser)
thank
source to share
You might want to use Cookies / window.sessionStorage.
You can set a cookie without an explicit expiration date so that it is only available for the current session (which is valid until the user closes the browser window).
You can also use sessionStorage object, it only stores data for one session. The data is deleted when the user closes a specific browser tab.
You can follow this score:
1. Create a cookie when the user first visits the page document.cookie = "userloggedin=true";
OR setssessionStorage.userLoggedIn = true;
2.The cookie will be available after refreshing / closing and reopening the tab, if there is no cookie, then the user closed the window and reopened it.
Likewise, sessionStorage data will be deleted after the user closes the browser tab
Hope this helps!
source to share
You can use a browser performance.navigation
to determine the type of navigation on your page.
var navigationType = performance.navigation.type;
if (navigationType === performance.navigation.TYPE_BACK_FORWARD) {
console.log("Back/Forward button");
} else if (navigationType === performance.navigation.TYPE_RELOAD) {
console.log("Reloaded");
} else if (navigationType === performance.navigation.TYPE_NAVIGATE) {
console.log("Normal navigation");
}
And the onbeforeunload
event can be used as usual to detect when the browser is closed. See this documentation to learn more about navigation constants.
source to share