Matanya
Matanya

Reputation: 6346

Unsubscribe to a PubNub channel in response to (before)unload event

I am building a multi-players game in angular using the PubNub service, including the presence add-on.

Since I need to detect if someone left the game unexpectedly - in order to send a message to the other players and end the game - I am trying to unsubscribe a user when he refreshes the page or goes to some other url. However, in Chrome - as opposed to FireFox - no presence event is being triggered, which probably means that the user wasn't unsubscribed prior to his leaving of the page.

CODE:

 $(window).bind("unload",function(e) {

    PubNub.ngUnsubscribe({channel:$scope.game.channel});
    e.preventDefault();

    }); 

I am aware that these events (beforeunload and unload) are problematic and have poor browser support, which is probably the reason for the failure. If this is the case, is there any other cross-browsers detection method I can use?

Upvotes: 3

Views: 1137

Answers (1)

jwzirilli
jwzirilli

Reputation: 223

There is no reliable way to catch the browser closing. The "beforeUnload" event is your best shot, but most mobile browsers don't trigger it. The best way to handle a user closing the browser in PubNub is to specify a heartbeat when subscribing (http://www.pubnub.com/docs/javascript/api/reference.html#subscribe). The heartbeat tells how many seconds PubNub should wait after an ungraceful disconnect (such as closing the browser), before considering a user as timed out. This is defaulted to 320 and can be set to as low as 6 seconds (> 5). It still won't be immediate, but you will receive a presence "timeout" action 6 seconds after the browser is closed. Having a low heartbeat could impact your battery life so be wary of that.

Also, I know I linked the doc to the JS API, but the angular ngSubscribe allows most of the same arguments.

Hope that helps.

Upvotes: 4

Related Questions