最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - On browser close event - Stack Overflow

programmeradmin6浏览0评论

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>
发布评论

评论列表(0)

  1. 暂无评论