Detect window closed

左心房为你撑大大i 提交于 2019-12-22 16:32:23

问题


I'm creating a chat client which uses a database to check the status of a session 0-waiting, 1-running, 2-closed.

I have a close button which will change the status to 2 but I was wondering, how do I detect if the browser is closed just by pressing x?

The main reason for this is I don't want the session showing up as running when one of the participants has closed their browser.


回答1:


use the unload and onbeforeunload events:

window.onunload = window.onbeforeunload = function (){...};

It's better to register to both of the events to be sure the callback will fire.




回答2:


You could listen for the onbeforeunload-event with JavaScript, which is fired when the browser window is closed.

As you tagged the question with jquery, you can use .unload():

$(window).unload(function() {
  // Do some ajax-request to kill the session
});

Without jQuery it would be:

window.onbeforeunload = function() {
   // Do some ajax-request to kill the session
};



回答3:


You can use beforeunload event, because unload event is deprecated in jQuery version 1.8 and the beforeunload event fires whenever the user leaves your page.

$(window).bind("beforeunload", function() { 
    return confirm("Do you really want to close?"); 
})


来源:https://stackoverflow.com/questions/9344670/detect-window-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!