views:

20

answers:

2

Hey,

Nowadays I am creating browser game, using ASPX, CSS and AJAX. I need to know when the user close the browser or exit from website, because of these cases for example:

  1. if a player opens a game room and than close the browser or exit from the website, this room need to be deleted immediately.

  2. 2 players are playing in a room, and than one of them leave so the game is finished and the one that stay is the winner. In this case I can use the countdown timer of the players' turns, and when the countdown timer reaches 0 - The other player wins, but I prefer that the message will appear as soon as the player left the room, its faster, and when the countdown reaches 0 there is 2 possibilities - the player left or the player didn't react in time.

Anyone can tell me how can I know when the user close the browser or exit from my website? because as far as I know the Session object won't be effective since the Session_End method runs several minutes after the browser is close or the user is AFK, and I can't let the Session_End close the room for players that are AFK since they are waiting for more players to join, and I need to fire my events immediately.

Thanks

P.S: I found this method, I dont know if its works but I don't think it will fit my needs because I need the event to fire even when the user move from my site to another website.

Ext.EventManager.on(window, 'beforeunload', function() {
    alert('cross-exit tab click AND cross-exit browser click');
});
A: 

Handling onbeforeunload will probably work.

jeffamaphone
A: 

The onbeforeunload event fires before the user leaves a page. This fires when the user closes the browser or tab, or goes to another page, even if that page is on your own website.

Inside the event handler, you'd make a call back to your server saying that the session was closed. Note that this will have to be an authenticated call with a crumb to avoid an XSRF (ie, player B tricks player A into ending his session).

The only caveat is that it does not work on Opera. For opera, you could use the onunload event, but since this fires when the browser is closed, it's very hard to send anything back to your server in this event handler.

bluesmoon