How to distinguish between refresh (by F5/refresh button) and close browser?

六月ゝ 毕业季﹏ 提交于 2021-02-07 19:44:24

问题


I have requirement to handle events on browser like back, refresh and close on cross browser. The problem is my customer want a different logic for each of those events. For back button, this solution is quite fine:

  • https://stackoverflow.com/a/36786695/3462243

but Now it's hard to distinguish between refresh and close, all solutions i found is about using of "beforeunload" event:

  • How to know whether refresh button or browser back button is clicked in firefox
  • Handle refresh page event with javascript
  • https://forums.asp.net/t/1829278.aspx?Detect+Browser+refresh+reload+button+click+in+all+browsers (this one does not 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 refreshing by F5, i can catch event on keyboard, but when user press refresh button on browser, i can't. If i use "beforeunload", it is the same with close browser event.

I also found a workaround solution:

  • Identifying Between Refresh And Close Browser Actions
  • How do I detect a page refresh using jquery?

but unfortunately, what i want to do is showing message before page unload (show when browser is close but not when refreshing)

Does anyone know a solution for it (cross browser)

Thanks


回答1:


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 !



来源:https://stackoverflow.com/questions/45451578/how-to-distinguish-between-refresh-by-f5-refresh-button-and-close-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!