简体   繁体   中英

Differentiate browser refresh and browser close

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?

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...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM