roflwaffle
roflwaffle

Reputation: 30656

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

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?

Upvotes: 4

Views: 2438

Answers (4)

Alix Axel
Alix Axel

Reputation: 154543

If I'm not mistaken Javascript should have a function named something like onWindowClose, maybe try searching for it?

Regarding PHP solutions, I'm not sure if there are any but I suggest you take a quick look into PHP Connection Handling, specifically the connection_aborted() and register_shutdown_function() functions.

Upvotes: 0

rspeed
rspeed

Reputation: 1662

Have the onunload event send a request to the server which will cause the session to expire in n seconds (where n is the maximum time for a page reload request to occur, so perhaps 10). Then have the script for the site check to see if that event is scheduled and if so, cancel it. This would give you the behavior you seem to want.

But yeah, I'd recommend simply having the session expire.

Upvotes: 2

PhiLho
PhiLho

Reputation: 41132

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).

Upvotes: 2

Marc W
Marc W

Reputation: 19241

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.

Upvotes: 8

Related Questions