6

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

user645313
  • 83
  • 2
  • 5

2 Answers2

11

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();
});
Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
W. Andrew Loe III
  • 1,758
  • 1
  • 13
  • 9
  • 2
    You will need a patched Strophe.js: https://github.com/metajack/strophejs/issues/16 – W. Andrew Loe III Mar 16 '11 at 03:44
  • For the latest strophe you must use this.connection.options.sync = true; – CristiC Mar 31 '14 at 06:29
  • 2
    connection.options.sync = true actually made my hybrid app freeze while relogin. Seriously. I did a small chrome profiling . It showed that when you relogin after logout,the entire app freezed. However, when I removed sync = true, everything was fine. What exactly does this sync does?. I am assuming that it sets a sync pattern after which every operation is synhronous. The default being asynchronous, solved my problem. I am still not able to get my head around it – HIRA THAKUR Jan 13 '16 at 13:17
2

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

connection.flush();
connection._options.sync = true;    
connection.disconnect();   
John
  • 21
  • 1