Ajax是否可以在beforeunload中可靠地执行? [英] Will ajax in beforeunload reliably execute?

查看:58
本文介绍了Ajax是否可以在beforeunload中可靠地执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML5应用程序,当用户更改/刷新页面时,该应用程序需要发送断开ajax请求.我目前正在使用此代码:

I have a HTML5 application that needs to send a disconnect ajax request when the user changes/refreshes the page. I am currently using this code:

window.addEventListener("beforeunload", function(event) {
    $.ajax({
        url: api_disconnect,
        data: { identifier: token },
        method: "GET"
    });
});

我不需要处理响应,甚至不需要确保浏览器收到响应.我的问题是,我可以依靠服务器接收请求吗?

I don't need to process the response, or even ensure that the browser receives a response. My question is, can I rely on the server receiving the request?

如果没有,我该怎么做??目前,我让该应用发送我还活着!"每15秒请求一次(感觉已经太多了).我希望服务器知道用户断开连接的那一秒.

And if not, how can I accomplish this? Currently I have the app send an "I'm alive!" request every 15 seconds (which already feels like too much). I want the server to know the second the user disconnects.

为了澄清,我知道,如果浏览器/计算机崩溃,则我无能为力.那就是心跳的目的.我的意思是在正常用例中,当用户关闭/更改/刷新页面时.

To clarify, I know that if the browser/computer crashes there's nothing I can do about that. That's what the heartbeat is for. I just mean in a normal use case, when the user closes/changes/refreshes the page.

推荐答案

您不能100%依赖于通过ajax调用.您可以测试许多浏览器和操作系统,并确定通常在页面被拆除之前哪些浏览器和操作系统会收到发送的ajax调用,但是任何规范都不能保证这样做.

You cannot 100% rely on the ajax call getting through. You can test many browsers and operating systems and determine which ones will usually get the ajax call sent before the page is torn down, but it is not guaranteed to do so by any specification.

最常用的解决方法是使用心跳.这也将弥补您因网络连接丢失,掉电或计算机睡眠模式或浏览器崩溃而造成的损失,而 beforeunload 处理程序不会.

The heartbeat like you are using is the most common work-around. That will also cover you for a loss in network connection or a power-down or computer sleep mode or browser crash which the beforeunload handler will not.

我见过讨论的另一种解决方法是使用socket.io连接到服务器.由于socket.io连接同时具有很小的非常有效的心跳,并且服务器将在关闭页面时看到套接字被关闭,因此您将两全其美,因为您会看到通过心跳异常关闭并且您会看到通过webSocket连接立即关闭而导致的正常关闭.

Another work-around I've seen discussed is to use a socket.io connection to the server. Since the socket.io connection has both a small, very efficient heartbeat and the server will see the socket get closed when the page is closed, you kind of get the best of both worlds since you will see an abnormal shut-down via the heartbeat and you will see a normal shut-down immediately via the webSocket connection getting closed.

这篇关于Ajax是否可以在beforeunload中可靠地执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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