How do I catch a WebSocket connection interruption?

前端 未结 2 415
天命终不由人
天命终不由人 2020-12-31 11:07

In Firefox (at least), if you hit ESC, then it will close all open WebSockets connections. I need to capture that disconnection and try to re-connect once it\'s available ag

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 11:41

    You can't catch it and it's not your fault. It's FireFox bug. Vote for it here:

    https://bugzilla.mozilla.org/show_bug.cgi?id=712329

    I personally tried all kind of solutions:

    event handlers onunload onbeforeunload onclose try..catch some js error handling 3rd party services etc.

    You can log to console your socket, it's closed before unload, but FF thinks different.. :(

    Solution (not answer directly to the answer, but it works):

    It's a bug, so you can't catch, but this info is not Solution. After all kind of crazy workarounds and tries to catch that bug, i finally found this working. If you use socket.io to work with WebScokets it can work with different transport technologies. xhr-polling works with Firefox.

    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x     or Firefox x.x (ignoring remaining digits);
        socket = io.connect('//' + node_server + '/', {
            transports: ['polling']
        });
    } else {
        socket = io.connect('//' + node_server + '/');
    }
    

    What helped me - might help you too:

    Web Socket support in Node.js/Socket.io for older browser

    Define transport types on the client side

    socket.io doens't work with transports: [ 'xhr-polling' ]

提交回复
热议问题