使用 Javascript 检测 websocket 支持的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20060320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:35:35  来源:igfitidea点击:

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

javascriptandroidwebsocket

提问by Steven

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 test to throw out Android devices instead, which I'm not happy about. I have a Samsung Galaxy Tab 2, and here's my detection code:

我正在尝试使用 Javascript 来检测 Web 浏览器是否支持 websockets,但仅使用基于功能的检测,我得到了误报,所以我添加了一个用户代理测试来代替 Android 设备,但我不是高兴。我有一个三星 Galaxy Tab 2,这是我的检测代码:

var isSupported = (("WebSocket" in window && window.WebSocket != undefined) ||
                   ("MozWebSocket" in window));

/* This line exists because my Galaxy Tab 2 would otherwise appear to have support. */
if (isSupported && navigator.userAgent.indexOf("Android") > 0)
  isSupported = false;

if (isSupported)
  document.write("Your browser supports websockets");
else
  document.write("Your browser does not support websockets");

This code seems to work with IE, Firefox, Safari (including iPhone/iPad), and Chrome. However, the feature-based check is returning true when I use the default browser of my Samsung Galaxy Tab 2, which is incorrect because that browser does not actually support websockets. Furthermore, I don't know how many other Android devices have this same issue, so at the moment, this is the best solution I'm aware of for detection.

此代码似乎适用于 IE、Firefox、Safari(包括 iPhone/iPad)和 Chrome。但是,当我使用 Samsung Galaxy Tab 2 的默认浏览器时,基于功能的检查返回 true,这是不正确的,因为该浏览器实际上不支持 websocket。此外,我不知道有多少其他 Android 设备有同样的问题,所以目前,这是我所知道的最好的检测解决方案。

Is there a better way to detect websocket support other than what I'm doing? I do realize that workarounds exist for Android, such as using a different browser, which means my user agent detection code as-is would not be a good thing. My goal is to not have to rely on the user agent in the first place.

除了我正在做的事情之外,有没有更好的方法来检测 websocket 支持?我确实意识到 Android 存在解决方法,例如使用不同的浏览器,这意味着我的用户代理检测代码原样不是一件好事。我的目标是首先不必依赖用户代理。

Any suggestions?

有什么建议?

回答by Isaiah Turner

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

这是最短的解决方案,由 Modernizr 使用。只需将此添加到您的代码中

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

then you can use it by running

然后你可以通过运行来使用它

if (supportsWebSockets) {
     // run web socket code
}

回答by Rob M.

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

我认为 Modernizr 库正是您要找的: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
}

回答by jfaron

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.

阅读@gzost 的回复后.. 我开始修修补补.. 因为没有其他东西可以正确检测我的 android 手机上的 WS ......甚至 websocket.org 说我有它,但后来无法连接。

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

无论如何,试试这个解决方法.. 似乎可以使用 chrome、FF、safari 和默认的 android 浏览器正确检测它的开/关。

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();
});

回答by kroko

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

在 2016 年为现代 WebSockets 实现(没有前缀,例如MozWebSocket)削减芥末将是

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

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

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

回答by cskwg

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.

上面的测试是排序的,所以速度快的先到。