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

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

问题描述

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

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

此代码似乎适用于 IE、Firefox、Safari(包括 iPhone/iPad)和 Chrome.但是,当我使用 Samsung Galaxy Tab 2 的默认浏览器时,基于功能的检查返回 true,这是不正确的,因为该浏览器实际上不支持 websocket.此外,我不知道有多少其他 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 存在解决方法,例如使用不同的浏览器,这意味着我的用户代理检测代码原样不是一件好事.我的目标是首先不必依赖用户代理.

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 使用.只需将此添加到您的代码中

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
}

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

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