Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disconnect Strophe Connection on Page Unload

I've written a web-based MUC client using strophe.js and jQuery and I'm trying to send an unavailable presence to the room and disconnect the user in the jquery unload event for the window. If a user navigates away or closes the browser tab, they should be logged out of the MUC.

I've tested the code that I'm running in this event through a logout button I have on the page, so I'm pretty sure the stanza is correct. I think strophe is having trouble sending the stanza if the browser window is closing. Is there any workaround here? I've also tried the onbeforeunload event (I know it's not entirely cross-browser compatible), but that doesn't seem to work either.

Any advice is much appreciated!

Thanks, John

like image 370
user645313 Avatar asked Mar 04 '11 19:03

user645313


2 Answers

Ensure you switch to sync mode, and call flush() before sending your disconnect() call. Here is an example:

var Client = {
  connect: function(spec) {
    this.connection = new Strophe.Connection(spec.url);
  },

  disconnect: function() {
    this.connection.options.sync = true; // Switch to using synchronous requests since this is typically called onUnload.
    this.connection.flush();
    this.connection.disconnect();
  }
}

Then you can bind to onbeforeunload/onunload. (jQuery example)

var client = new Client;
client.connect();
$(window).unload(function() {
  client.disconnect();
});
like image 182
W. Andrew Loe III Avatar answered Nov 05 '22 03:11

W. Andrew Loe III


No patches needed, there's now a built-in solution:

connection.flush();
connection._options.sync = true;    
connection.disconnect();   
like image 31
John Avatar answered Nov 05 '22 05:11

John