如何提高“window.OnBeforeUnload”的成功率?发送 Ajax ping?

发布于 2024-11-17 14:14:11 字数 613 浏览 3 评论 0原文

我已经阅读了几十个关于 SO 的问题和答案,但没有一个回答我的特定问题...大多数都围绕弹出“哦,你需要保存”消息...这不是我的需要。

我正在构建一个供我办公室内部使用的应用程序(不是公共网站),并且特别是一个“页面”,我们希望记录用户的“退出”。

所以,我有一个简单的声明:

window.onbeforeunload = function () {
    $.post('LogExit.aspx');
}

现在,这个 post 在大多数情况下都会失败,因为浏览器不“想要”启动新请求,因为它知道页面即将消失......但是,如果我添加一个烦人的alert框,那么它会100%地发送ping!

示例:

window.onbeforeunload = function () {
    $.post('LogExit.aspx');
    alert("Ha ha ha, I can delay the browser!");
}

所以,我的问题是...我如何确保(或至少增加获得)“LogExit.aspx”ping 的机会?

I've read dozens of questions and answers on S.O., and none of them answer my particular question... most of them center around popping up a "Oooh, you need to save" message... that is not my need.

I am building an application for internal use at my office (not a public website), and one "page" in particular we would like to log the 'exiting' by the user.

So, I have this simple statement:

window.onbeforeunload = function () {
    $.post('LogExit.aspx');
}

Now, this post will fail most of the time due to the browser not "wanting" to start a new request since it knows that the page is going away... but, if I add an annoying alert box, then it will send the ping 100% of the time!!!

Example:

window.onbeforeunload = function () {
    $.post('LogExit.aspx');
    alert("Ha ha ha, I can delay the browser!");
}

So, my question is... how do I ensure (or at least increase the chances of having) the "LogExit.aspx" ping going through?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情定在深秋 2024-11-24 14:14:11

由于您必须发出某种请求并且并不真正关心响应,因此在这种情况下您可以使用图像:

window.onbeforeunload = function () {
   var img= new Image();
   img.src = "LogExit.aspx";
   // you have to check on your server to see if it worked :)
}

Since you have to make some kind of request and don't really care about about the response, you can use an image in this case:

window.onbeforeunload = function () {
   var img= new Image();
   img.src = "LogExit.aspx";
   // you have to check on your server to see if it worked :)
}
夜夜流光相皎洁 2024-11-24 14:14:11

不幸的是,没有 100%、甚至 10%“保证”的方法来实现这一目标...因此,我能够通过每 10 秒发送一次 ping 来解决我的特殊需求代码>函数。

由于我需要记录一个人查看特定页面的时间,因此上面的解决方法有助于至少将其精确度降低到 10 秒窗口。

我真的希望将来能有更好的解决方案。

Unfortunately there is no 100%, or even 10% "guaranteed" way of achieving this... so, I was able to solve my particular needs by having an every-10-seconds-send-a-ping function.

Since my need was to log how long a person was viewing a particular page, this work-around above helps to at least get it down to a 10 second window of accuracy.

I really hope a better solution comes down the pipe in the future.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文