socket.io-client icon indicating copy to clipboard operation
socket.io-client copied to clipboard

Socket disconnect event triggered only after timeout with closeOnBeforeunload set up to true

Open Suvitruf opened this issue 3 years ago • 3 comments

Describe the bug

  1. Init socket with closeOnBeforeunload flag set up to true.
  2. System message popup (e. g, "This page is asking you to confirm that you want to leave — information you’ve entered may not be saved.").
  3. Server shows disconnected event.
  4. But client receive disconnect event only after ping timeout.

To Reproduce

Socket.IO server version: "@nestjs/platform-socket.io": "9.0.5".

Server

@WebSocketGateway(APP_CONFIG.serverWsPort, {
    pingTimeout: 10000,
    transports:  ['websocket'],
    maxHttpBufferSize: 1024 * 1024 * 100
})

Socket.IO client version: 4.5.1

Client

import OpenSocket from 'socket.io-client';

this.socket = OpenSocket(`${APP_CONFIG.api.ws.host}`, {
    query:               {
        token
    },
    secure:              true,
    transports:          ['websocket']
});

this.socket
    .on('connect', () => {
    })
    .on('message', (msg) => {
        console.log('message', msg);
    })
    .on('disconnect', (msg) => {
        console.log('disconnect', msg);
    });

Expected behavior

disconnect event should be triggered right after disconnection, and not after ping timeout.

Platform: Doesn't matter. Same problem on Win 10, Mac, in Chrome and FF.

Suvitruf avatar Sep 18 '22 09:09 Suvitruf

I could indeed reproduce the behavior you are describing, thanks.

Does setting closeOnBeforeunload: false work for your use case?

darrachequesne avatar Sep 19 '22 07:09 darrachequesne

I could indeed reproduce the behavior you are describing, thanks.

Does setting closeOnBeforeunload: false work for your use case?

It's complicated 😅

closeOnBeforeunload: false does help with my case (at least, it returns old behavior), but more importantly that:

  1. Introducing this flag you changed the default behavior of library.
  2. You added it in v4.1.0 and not v4.0.0.

Suvitruf avatar Sep 19 '22 08:09 Suvitruf

@Suvitruf you are right, the change was meant as a fix but had unexpected consequences, sorry for that.

See also: https://github.com/socketio/socket.io/issues/3639

darrachequesne avatar Sep 20 '22 05:09 darrachequesne

For future readers:

Due to this surprising behavior, closeOnBeforeunload now defaults to false (since version 4.7.1).

Reference: https://socket.io/docs/v4/client-options/#closeonbeforeunload

darrachequesne avatar Apr 09 '24 17:04 darrachequesne