Chrome 中的 window.onbeforeunload ajax 请求 [英] window.onbeforeunload ajax request in Chrome

查看:37
本文介绍了Chrome 中的 window.onbeforeunload ajax 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 Ajax 处理机器远程控制的网页.当用户离开页面时,我想自动断开与机器的连接.所以这是代码:

I have a web page that handles remote control of a machine through Ajax. When user navigate away from the page, I'd like to automatically disconnect from the machine. So here is the code:

window.onbeforeunload = function () {
  bas_disconnect_only();
}

断开连接函数只是向 PHP 服务器端脚本发送 HTTP GET 请求,该脚本完成断开连接的实际工作:

The disconnection function simply send a HTTP GET request to a PHP server side script, which does the actual work of disconnecting:

function bas_disconnect_only () {
   var xhr = bas_send_request("req=10", function () {
   });
}

这在 FireFox 中运行良好.但是对于 Chrome,根本不发送 ajax 请求.有一个不可接受的解决方法:向回调函数添加警报:

This works fine in FireFox. But with Chrome, the ajax request is not sent at all. There is a unacceptable workaround: adding alert to the callback function:

function bas_disconnect_only () {
   var xhr = bas_send_request("req=10", function () {
     alert("You're been automatically disconnected.");
   });
}

添加警报调用后,请求将成功发送.但正如您所看到的,这根本不是一种解决方法.

After adding the alert call, the request would be sent successfully. But as you can see, it's not really a work around at all.

有人可以告诉我这是否可以通过 Chrome 实现?我正在做的事情在我看来完全合法.

Could somebody tell me if this is achievable with Chrome? What I'm doing looks completely legit to me.

谢谢,

推荐答案

我遇到了同样的问题,Chrome 没有在 window.unload 事件中向服务器发送 AJAX 请求.

I was having the same problem, where Chrome was not sending the AJAX request to the server in the window.unload event.

我只有在请求是同步的情况下才能让它工作.我能够使用 Jquery 做到这一点,并将 async 属性设置为 false:

I was only able to get it to work if the request was synchronous. I was able to do this with Jquery and setting the async property to false:

$(window).unload(function () {
   $.ajax({
     type: 'GET',
     async: false,
     url: 'SomeUrl.com?id=123'
   });
});

以上代码适用于 IE9、Chrome 19.0.1084.52 m 和 Firefox 12.

The above code is working for me in IE9, Chrome 19.0.1084.52 m, and Firefox 12.

这篇关于Chrome 中的 window.onbeforeunload ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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