问题
I need to detect if the browser is being closed using jQuery, and do an event if this is true. I have a chat feature on my website (much like Facebook) that keeps the user logged in as they navigate to other pages within the website structure but needs to log them out of chat (so they do not appear online to others) if they click the browsers close button. So .unload()
will not work because .unload() will apply the logout function to all window actions including navigating to another page within the website structure. .unload()
works for browser closes, but also works for browser forward and backward navigation, so I need a way to detect if the browser is being closed AND ONLY if the browser if being closed.
回答1:
Whatever you're using for chat (orbited, websockets?) should be able to detect a session timeout.
回答2:
The best way to do this would be to set up some regular polling of the server to tell it that the user is still on the page. You could send an AJAX request once a minute to confirm that the user is still there, and log them out on the server side if more than that time has gone by since the last notification.
This may not be the most reliable solution, but it is a very common one and will probably be effective for what you want to do.
回答3:
This is not possible. onunload
/ onbeforeunload
are the only events that the system offers. The reason why a page is unloaded is not disclosed to the page.
It is possible to frequently check for whether a window that your script opened still exists. These solutions work based on setInterval()
and the window's closed
property. But I don't think that is what you're looking for.
来源:https://stackoverflow.com/questions/4096955/how-to-detect-if-browser-is-closed-using-jquery