什么是使用JavaScript来检测的WebSocket支持的最佳方法是什么? [英] What is the best way to detect websocket support using Javascript?

查看:173
本文介绍了什么是使用JavaScript来检测的WebSocket支持的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript如果Web浏览器支持WebSockets的检测,但只使用基于特征的检测,我越来越误报,所以我增加了一个用户代理测试抛出了Android设备,而不是,这是我又不是高兴的事情。我有一个三星Galaxy Tab 2,这是我的检测code:

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:

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");

这code似乎与IE浏览器,火狐,Safari浏览器(包括iPhone / iPad的)和Chrome的工作。然而,基于特征的检查,返回true,当我用我的三星Galaxy Tab 2,这是不正确,因为该浏览器实际上并不支持的WebSockets的默认浏览器。此外,我不知道有多少其他Android设备如何有这个同样的问题,所以在目前,这是最好的解决方案,我所知道的检测。

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.

有没有更好的方法来检测WebSocket的支持,比我在做什么其他的?我也认识到,解决方法Android的存在,如使用不同的浏览器,这意味着我的用户代理检测code原样不会是一件好事。我的目标是不是还得靠摆在首位的用户代理。

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.

有什么建议?

推荐答案

我觉得Modernizr的图书馆是你在找什么: HTTP ://modernizr.com/

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
}

这篇关于什么是使用JavaScript来检测的WebSocket支持的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆