javascript - Monitor if user closes browser offline
PHPz
PHPz 2017-06-05 11:09:36
0
3
774

I am working on a web system that needs to verify whether it is online. For the online situation, I added an online field to the user table. 1 means online and 0 means offline. There is an exit button in the website. When the button is clicked to exit normally, the online field of the user table will be added. It is no problem to set the field to 0 and clear the session to exit the website, but it is not possible to change the user's online status to offline after the user directly closes the window or browser. Currently trying to use JS to monitor whether the user closes the window or browser and then adds an exit method to the closing event. Some JS codes found on the Internet for monitoring the closing of the browser are as follows

<script type="text/javascript">  
    window.onbeforeunload = function(e) {
    e = e || window.event;
    var msg = "您确定要离开此页面吗?";
      
    // IE
    e.cancelBubble = true;
    e.returnValue = msg;
      
    // Firefox
    if(e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
     
    // Chrome / Safari
    return msg;
};
</script> 

Methods such as onbeforeunload or onload cannot determine the actions of closing the browser/refreshing the page/jumping the page. I wonder if anyone has experience in this area. Please give me some advice

PHPz
PHPz

学习是最好的投资!

reply all(3)
迷茫

The service period is notified every 1s that the client is online and confirmed on the server. If the client loses contact, it is confirmed to be offline.

setInterval(function(){
    $.ajax({
         type: "GET",
         url: "server url",
         data: {isOnline:1},
         dataType: "json",
         success: function(data){
                    //客户端在线
                  }
     });
}, 1000);
滿天的星座

Use websocket

洪涛
window.onbeforeunload = function () {
    window.event.returnValue = '';
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template