What is the best way to detect websocket support using Javascript?

后端 未结 5 1245
慢半拍i
慢半拍i 2020-12-31 04:27

I\'m trying to use Javascript to detect if a web browser supports websockets, but using only feature-based detection, I\'m getting false positives, so I added a user agent t

相关标签:
5条回答
  • 2020-12-31 04:30

    None of the above answers by itself was sufficient in my tests. The following code seems to be working fine:

        function nll( o ) { return CS.undefined === typeof o || null === o; }
        // ...
        function check_ws_object() {
            try {
                var websocket = new WebSocket( "wss://echo.websocket.org" );
                return true;
            } catch ( e ) { ; }
            return false;
        }
        //
        function check_support() {
            if ( !( WebSocket in window ) ) {
                if ( nll( window.WebSocket) ) {
                    if ( !this.check_ws_object() ) {
                        alert( "This browser doesn't support HTML5 Web Sockets!" );
                        return false;
                    }
                }
            }
            return true;
        },
    

    The above tests are sorted, so that the faster ones come first.

    0 讨论(0)
  • 2020-12-31 04:34

    after reading @gzost's response.. I started tinkering.. since nothing else can properly detect WS's on my android phone... even websocket.org says i have it, but then fails to connect.

    Anyways, try this workaround.. seems to properly detect it on/off with chrome, FF, safari and the default android browser.

    var has_ws=0;
    function checkWebSocket(){
      try{
        websocket = new WebSocket("ws:websocket.org");
        websocket.close('');
      }catch(e){ //throws code 15 if has socket to me babies
        has_ws=1;
      }
    }
    
    $(document).ready(function(){
      checkWebSocket();
    });
    
    0 讨论(0)
  • 2020-12-31 04:40

    I think the Modernizr library is what you are looking for: http://modernizr.com/

    Once you include the library on your page, you can use a simple check like:

    if(Modernizr.websockets){
        // socket to me baby
    }
    
    0 讨论(0)
  • 2020-12-31 04:44

    This page comes on top in google search.

    In year 2016 cutting the mustard for modern WebSockets implementation (no prefixes such as MozWebSocket) would be

    if (
      'WebSocket' in window && window.WebSocket.CLOSING === 2
    ) {
     // supported
    }
    

    http://www.w3.org/TR/websockets/#the-websocket-interface

    0 讨论(0)
  • 2020-12-31 04:46

    This is the shortest solution and is used by Modernizr. Simply add this to your code

    supportsWebSockets = 'WebSocket' in window || 'MozWebSocket' in window;
    

    then you can use it by running

    if (supportsWebSockets) {
         // run web socket code
    }
    
    0 讨论(0)
提交回复
热议问题