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

How to activate a function before user close browser/tab?

本文关键字:选项 功能 激活 浏览器 用户      更新时间:2023-09-26

如何在用户关闭浏览器/选项卡之前激活一个功能?

下面是我的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调用到达服务器之前有效地中断它)。

有一些技巧可以确保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)

使用此函数:

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

绑定onbeforeunload事件

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