如何在用户关闭浏览器/选项卡之前激活function?

如何在用户关闭浏览器/选项卡之前激活function?

下面是我的ajax请求

 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); }  

使用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) 

使用此function:

 $(window).bind('beforeunload', function() { //do your stuffs }); 

将它绑定到onbeforeunload事件

您可以将函数附加到window.onbeforeunload ,但chrome不允许您执行任何其他代码。 您只能返回在用户离开前显示的特定字符串。