javascript中有没有办法检测卸载事件是通过刷新、后退按钮还是关闭浏览器引起的? [英] Is there a way in javascript to detect if the unload event is caused via a refresh, the back button, or closing the browser?

查看:31
本文介绍了javascript中有没有办法检测卸载事件是通过刷新、后退按钮还是关闭浏览器引起的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在查看窗口的卸载"事件,以尝试确定卸载"事件是如何触发的,但收效甚微.有没有办法确定javascript事件是如何触发的?

I am currently looking at the "unload" event of a window to try to determine how the "unload" event was triggered, but am having little success. Is there a way to determine how the javascript event was triggered?

  • 页面刷新
  • 返回按钮(或离开页面)
  • 关闭浏览器

本质上,我只需要在浏览器窗口关闭时执行一些代码,而不是刷新或导航离开.

Essentially I need to execute some code only when the browser window is being closed, not refreshed or navigated away from.

目的:当客户更新我们的软件时,更新会将他们的第一个 Internet 请求重定向到优惠页面.有一个请勿打扰"选项的按钮,但有些用户只需关闭浏览器即可.关闭浏览器后,我需要复制请勿打扰"功能,以便用户不再被重定向到优惠页面.由于离开页面的方式不同,简单地附加到卸载"事件是行不通的.

Purpose: When a customer does an update of our software, the update will redirect their first Internet request to an offer page. There is a button for a "Do Not Bother" option, but some users will simply close their browser. Upon closing the browser, I need to duplicate the "Do Not Bother" functionality so the user no longer gets redirected to the offer page. Simply attaching to the "unload" event will not work due to the different ways of leaving a page.

推荐答案

否,如果存在,则取决于浏览器.当用户关闭页面时,您尝试运行什么样的代码?是要注销用户吗?然后,如果浏览器崩溃或网络连接中断,用户将不会被注销(如果计算机进入睡眠/休眠模式,则可能不会).

No, and if there was it would be browser dependent. What kind of code are you trying to run when the user closes the page? Is it to logout the user? Then the user would not be logged out if the browser crashes or the network connection breaks (and probably not if the computer goes to sleep/hibernation mode).

如果是出于注销目的,您可能应该在服务器上使用时间戳变量,该变量随每个请求更新(或使用 ajax-ping),如果在指定时间内没有看到用户,则注销用户.

If it is for logout-purposes you should probably use a timestamp variable at the server that gets updated with every request (or use a ajax-ping), and logout the user if it hasn't been seen for a specified time.

更新:发现 这个答案 在 stackoverflow 上.

Update: Found this answer here at stackoverflow.

这篇关于javascript中有没有办法检测卸载事件是通过刷新、后退按钮还是关闭浏览器引起的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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