区分浏览器刷新和浏览器关闭 [英] Differentiate browser refresh and browser close

查看:121
本文介绍了区分浏览器刷新和浏览器关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

页面上的访问者关闭浏览器时,我想设置一个cookie.我使用了像这样的onbeforeunload方法

 <脚本语言="JavaScript" type ="text/javascript">window.onbeforeunload =确认退出;函数confirmExit(){返回您试图离开此页面.如果您在未单击保存"按钮的情况下对字段进行了任何更改,则您的更改将丢失.确定要退出此页面吗?";}</script> 

遵循此链接

但是发现即使刷新页面或单击页面上的任何超级链接,也会弹出警报.

我只需要在访问者单击浏览器的交叉按钮而不是页面刷新时设置cookie.

我遵循了上面的链接和另一个这里.从帖子中发现,我们无法区分关闭和刷新.但是这些帖子是3-4年以前的.

是否可以使用JavaScript或Jquery区分这些事件?

解决方案

嗯,那呢:

  1. 在beforeunload上设置一个cookie
  2. 在全球范围内加载,检查cookie的时间戳以查看它是链接还是新会话
  3. 如果时间戳差异只有几秒钟,请删除cookie

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?

解决方案

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

这篇关于区分浏览器刷新和浏览器关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆