问题
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:
- Set a cookie onbeforeunload
- Globally onload, check the timestamp of the cookie to see whether this was a link, or a new session
- 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