admin管理员组

文章数量:1402485

I Need help on browser close event. I saw 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.

I Need help on browser close event. I saw 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.

Share Improve this question edited Apr 10, 2014 at 22:25 Flexo - Save the data dump 88.9k22 gold badges201 silver badges281 bronze badges asked Aug 27, 2010 at 3:45 JorgeJorge 5,67618 gold badges50 silver badges68 bronze badges 1
  • So what did you try? And what did or didn't work in which browsers? – Mischa Commented Aug 27, 2010 at 3:47
Add a ment  | 

3 Answers 3

Reset to default 3

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>

本文标签: javascriptOn browser close eventStack Overflow