Differentiate browser refresh and browser close

一笑奈何 提交于 2021-02-08 09:09:27

问题


I want to set a cookie when a visitor on the page closes the browser. I used onbeforeunload method like this

<script language="JavaScript" type="text/javascript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

followed this link

But found out that even refresh of page or click on any hyper link on the page,pops up an alert.

I need to set cookie only when visitor clicks cross button of browser and not on page refresh.

I followed some of the links like the one above and another here. And found from the post that we can not differentiate between close and refresh. But those posts were 3-4 years back.

Is there is any way to differentiate these events using JavaScript or Jquery?


回答1:


I'm afraid you have no way to tell.

The only thing you can do is overload clicks on links and set a flag. But you can never know if it is a refresh or a close...




回答2:


Hmm, what about this:

  1. Set a cookie onbeforeunload
  2. Globally onload, check the timestamp of the cookie to see whether this was a link, or a new session
  3. If the timestamp difference is only a few seconds, delete the cookie



回答3:


Well, unload is called when browser is closed and onload is called when you try to reload. You can use these properties and set flags , and fire events accordingly

Browser close and reload Check this link for more details



来源:https://stackoverflow.com/questions/17026464/differentiate-browser-refresh-and-browser-close

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