JavaScript、浏览器、窗口关闭 - 在窗口关闭时发送 AJAX 请求或运行脚本 [英] JavaScript, browsers, window close - send an AJAX request or run a script on window closing

查看:21
本文介绍了JavaScript、浏览器、窗口关闭 - 在窗口关闭时发送 AJAX 请求或运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出用户何时离开指定页面.找出他何时使用页面内的链接导航离开没有问题,但我需要标记一些内容,例如他关闭窗口或键入另一个 URL 并按下 Enter 键.第二个不是那么重要,但第一个很重要.那么问题来了:

I'm trying to find out when a user left a specified page. There is no problem finding out when he used a link inside the page to navigate away but I kind of need to mark up something like when he closed the window or typed another URL and pressed enter. The second one is not so important but the first one is. So here is the question:

我如何才能看到用户何时关闭了我的页面(捕获 window.close 事件),然后...并不重要(我需要发送 AJAX 请求,但如果我可以让它运行警报,我可以做剩下的).

How can I see when a user closed my page (capture window.close event), and then... doesn't really matter (I need to send an AJAX request, but if I can get it to run an alert, I can do the rest).

推荐答案

unloadbeforeunload javascript 事件,但这些对于 Ajax 请求来说并不可靠(它不保证在这些事件之一中发起的请求会到达服务器).

There are unload and beforeunload javascript events, but these are not reliable for an Ajax request (it is not guaranteed that a request initiated in one of these events will reach the server).

因此,强烈推荐这样做,您应该寻找替代方法.

Therefore, doing this is highly not recommended, and you should look for an alternative.

如果您确实需要这个,请考虑ping"风格的解决方案.每分钟发送一个请求,基本上是告诉服务器我还在这里".然后,如果服务器超过两分钟没有收到这样的请求(你必须考虑延迟等),你认为客户端离线.

If you definitely need this, consider a "ping"-style solution. Send a request every minute basically telling the server "I'm still here". Then, if the server doesn't receive such a request for more than two minutes (you have to take into account latencies etc.), you consider the client offline.

另一种解决方案是使用 unloadbeforeunload 来执行 Sjax 请求(同步 JavaScript 和 XML),但完全不推荐这样做.这样做基本上会冻结用户的浏览器,直到请求完成,他们不会喜欢(即使请求需要很少的时间).

Another solution would be to use unload or beforeunload to do a Sjax request (Synchronous JavaScript And XML), but this is completely not recommended. Doing this will basically freeze the user's browser until the request is complete, which they will not like (even if the request takes little time).

这篇关于JavaScript、浏览器、窗口关闭 - 在窗口关闭时发送 AJAX 请求或运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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