Is there a way to determine that the browser window was closed?

前端 未结 8 384
感动是毒
感动是毒 2021-01-14 12:35

How is it possible to identify that the browser\'s close button was clicked?

相关标签:
8条回答
  • 2021-01-14 13:15

    would this :

    $(window).unload( function () { alert("Bye now!"); } );
    

    help you ?

    It is in jQuery though.

    you should check the link given by Demoli though, it has further information about this particular method ( and its downside ).

    edit : added link.

    0 讨论(0)
  • 2021-01-14 13:22

    You should use onbeforeunload, not onunload. IE 7 (and perhaps other browsers) are not 100% reliable when it comes to firing the unload event, but it seems to always fire the beforeunload event.

    for example:

    window.onbeforeunload=function(){}
    

    or, if you are using prototype.js:

    Event.observe(window, 'beforeunload', function(){});
    
    0 讨论(0)
  • 2021-01-14 13:27

    From the JavaScript Event Reference, the closest match appears to be the OnUnload event. However, this also catches navigation away from the page (and thus you don't want the functions to run if the user actually clicks on a link.)

    There is no guarantee that the server will receive the message that the browser window is closed. For example, the older method that involved creating a small pop-up window would be blocked by most modern browsers. Using AJAX might work, but a browser window may close before it attempts to connect.

    0 讨论(0)
  • 2021-01-14 13:29

    I agree with northsouthwhat, but be aware that onbeforeunload may not be supported in all the browsers you might want to use it in.

    0 讨论(0)
  • 2021-01-14 13:33

    This is a hack but it seems to work for me. It might be IE specific as well. I code for an IE only environment.

    <body onunload="if(self.screenTop>9000){unloadFunction();}">
    

    Edited to add that my unloadFunction opens a popup window that kills the user's session. You can't do anything on the page that was closed itself. 'cause it's closed already! ;)

    0 讨论(0)
  • 2021-01-14 13:37

    you could setup an ajax call that periodically polls your server every few seconds to every few minutes (depending on your wanted time precision) and track the last hit time server side. not completely accurate (eg. network issues could cause a false positive), but may be an option depending on your requirements.

    0 讨论(0)
提交回复
热议问题