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

后端 未结 5 1275
慢半拍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: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();
    });
    

提交回复
热议问题