如何激活用户关闭浏览器/标签之前的函数? [英] How to activate a function before user close browser/tab?

查看:81
本文介绍了如何激活用户关闭浏览器/标签之前的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用户关闭浏览器/标签前启动功能?

下面是我的Ajax请求

 < SCRIPT LANGUAGE =JavaScript的类型=文/ JavaScript的>
 功能srh_ajaxfunction_cny(id)的
    {VAR XMLHTTP;
    尝试{XMLHTTP =新XMLHtt prequest();}
    赶上(E){尝试{XMLHTTP =新的ActiveXObject(MSXML2.XMLHTTP);}
    赶上(E){尝试{XMLHTTP =新的ActiveXObject(microsoft.xmlhttp);}
    赶上(五){警报(您的浏览器不支持AJAX!);
    返回false;}}}
    xmlhttp.onreadystatechange =功能(){
    如果(xmlhttp.readyState == 4){
        警报('完成')
    }}

        xmlhttp.open(得,url_path,真正的);
        xmlhttp.send(空);
    }
< / SCRIPT>
 

解决方案

使用 beforeunload 事件。通常情况下,如果在该处理程序的异步操作,浏览器不会等待他们完成,并会继续进行页面卸载(有效地中断你的Ajax调用之前到达您的服务器)。

有一些(的hackish)的技巧,以确保您的AJAX获得通过浏览器之前,将卸载页。其中一个(由跟踪您的网页上的行为服务使用为例)正在做一个循环,像这样:

  window.addEventListener(beforeunload',函数(){
    //毫秒数之前卸载页举行
    VAR X = 200;
    VAR一个=(新日期())的getTime()+ X。

    // -----------
    //你的Ajax调用放在这里
    // -----------

    //浏览器将与卸载你的页面对于x毫秒为单位,让
    //你的Ajax调用完成
    而((新的日期())的getTime()< A){}
}, 假)
 

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

below is my ajax request

<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>

解决方案

Use beforeunload event. Normally, if there are asynchronous actions in that handler, browser won't wait for them to finish and will proceed with page unload (effectively interrupting your ajax call before it reaches your server).

There are some (hackish) tricks to make sure your ajax gets through before browser will unload page. One of those (used for example by services that track your behavior on webpages) is doing a loop, like so:

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)

这篇关于如何激活用户关闭浏览器/标签之前的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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