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:

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:

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

+3


source to share


2 answers


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!

0


source


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.

-1


source







All Articles