SocketCluster / socketcluster-client

JavaScript client for SocketCluster
MIT License
293 stars 91 forks source link

Disconnection occurs within 'beforeunload' event #49

Closed Kequc closed 6 years ago

Kequc commented 8 years ago

I'm prompting the user that their connection will be interrupted if they leave the page, however socketcluster will optimistically trigger disconnect before the user has made their selection at the confirmation prompt. The offending code is:

var unloadHandler = function () {
  self.disconnect();
};

if (global.attachEvent) {
  global.attachEvent('onunload', unloadHandler);
} else if (global.addEventListener) {
  global.addEventListener('beforeunload', unloadHandler, false);
}

All beforeunload events occur as near to "at the same time" as possible, so the user is not able to cancel unloading of the page before disconnection occurs.

I have toyed with using e.stopImmediatePropagation() in my beforeunload event handler, but this is only effective if my script loaded before socketcluster. Then it seems non-trivial to ensure trailing beforeunload events fire afterward.

Perhaps socketcluster could try more aggressively to attach to the unload event, rather than the more commonly utilised beforeunload event.

jondubois commented 6 years ago

You can now disable this behaviour in SC and do it yourself. See https://github.com/SocketCluster/socketcluster-client/blob/master/lib/scclientsocket.js#L41