On browser close event
I Need help on browser close event. I sa开发者_C百科w a tutorial but it is not working on all browsers. I need a JavaScript solution that works on all browsers. My purpose on that is to delete a PHP session on browser close.
You can use window.onunload
to find out if a user is leaving a page/closing a window/closing a tab.
But there is no way to really find out if a user has left your website. He might still have another tab or window opened.
So your only real solution is to check how much time has passed since the last activity from that user. And if that has to happen live, you could add an ajax-like callback to poll the server every minute or so to be sure that the user still has his window open.
If you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:
window.onbeforeunload = function (e) {
if ((window.event.clientY < 0)) {
//window.localStorage.clear();
//alert("Y coords: " + window.event.clientY)
}
};
In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.
<script language=”javascript”>
function deleteSession(){
// session deletion
}
window.onbeforeunload = deleteSession;
</script>
精彩评论