如何在用户关闭浏览器/选项卡之前激活功能?
下面是我的ajax请求
<script language="JavaScript" type="text/javascript">
function srh_ajaxfunction_cny(id)
{var xmlhttp;
try{xmlhttp=new XMLHttpRequest();}
catch (e){try{xmlhttp=new ActiveXObject("msxml2.xmlhttp");}
catch (e){try{xmlhttp=new ActiveXObject("microsoft.xmlhttp");}
catch (e){alert("Your browser does not support ajax!");
return false;}}}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
alert('done')
}}
xmlhttp.open("get",url_path,true);
xmlhttp.send(null);
}
</script>
最佳答案
使用beforeunload
事件。通常,如果该处理程序中有异步操作,浏览器不会等待它们完成,而是继续进行页面卸载(在 Ajax 调用到达服务器之前有效地中断它)。
有一些(hackish)技巧可以确保你的ajax在浏览器卸载页面之前通过。其中之一(例如由跟踪您在网页上的行为的服务使用)正在执行循环,如下所示:
window.addEventListener('beforeunload', function() {
// number of miliseconds to hold before unloading page
var x = 200;
var a = (new Date()).getTime() + x;
// -----------
// your ajax call goes here
// -----------
// browser will hold with unloading your page for X miliseconds, letting
// your ajax call to finish
while ((new Date()).getTime() < a) {}
}, false)
关于javascript - 如何在用户关闭浏览器/选项卡之前激活功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15614491/