1

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?

Community
  • 1
  • 1
Sinha
  • 773
  • 2
  • 16
  • 34

3 Answers3

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

Maresh
  • 4,644
  • 25
  • 30
1

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
landons
  • 9,502
  • 3
  • 33
  • 46
  • Well, ye it's a bit dirty but you don't have much choice... You could combined that with my answer. – Maresh Jun 10 '13 at 14:44
  • @Maresh No argument here; dirty indeed. There's probably a better way to solve the problem, but this is the only solution I could think of for the *question* ;) – landons Jun 10 '13 at 14:48
  • No, as I said he doesn't have much choice. I'm sorry you took it the wrong way, this is a good solution. – Maresh Jun 10 '13 at 14:49
  • Didn't take it wrong--you had a point about its lack of cleanliness. – landons Jun 10 '13 at 14:50
  • Good then :) And I think you deserve a +1 ;) – Maresh Jun 10 '13 at 14:56
0

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