Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On browser close event

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.

like image 841
Jorge Avatar asked Dec 20 '25 15:12

Jorge


2 Answers

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.

like image 137
Wolph Avatar answered Dec 23 '25 03:12

Wolph


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.

like image 45
Merr Leader Avatar answered Dec 23 '25 05:12

Merr Leader