Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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.

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.

Any suggestions?

like image 904
Steven Avatar asked Nov 18 '13 23:11

Steven


1 Answers

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
}
like image 179
Isaiah Turner Avatar answered Oct 13 '22 16:10

Isaiah Turner