Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell the difference between a page refresh and closing a page

Tags:

javascript

php

I have a web app game and while in the game I want to have it so if a user closes the page or their browser, it will automatically log them out. I tried using the onbeforeunload event attached to the window:

window.onbeforeunload = function() {
    // perform logout functions here
}

The problem is, that will also fire if the user refreshes the page. Is there a way I could detect whether or not the user is completely closing the whole page, or just refreshing it?

like image 485
roflwaffle Avatar asked Dec 17 '22 08:12

roflwaffle


2 Answers

There is not a detectable difference. To automatically logout a user, you should set an expiration on your cookie storing the login or session information. So if you set it for 1 hour, the user would essentially be logged out after that time since the cookie would be destroyed. If you wanted to postpone this auto logout while they are still interacting with the site, you could reset the expiration of the cookie every time they perform some sort of action (clicking a link, activating an AJAX call, etc). That would mean that they'd be logged out after 1 hour of inactivity as opposed to just 1 hour from login, which sounds more like what you want.

If you set the cookie's expiration to 0, then it will expire it after the session ends. That usually occurs when the user quits their browser entirely. That's another option as well.

like image 50
Marc W Avatar answered Apr 09 '23 20:04

Marc W


As said, you cannot. Even worse, this event have been abandoned by lot of browsers, probably because it have been abused by malicious scripts doing pop-under and such.

A possible workaround is to have an Ajax script "phoning home": if it is silent for some time, the user just abandoned the site (closed page or browser).

like image 28
PhiLho Avatar answered Apr 09 '23 19:04

PhiLho