Cross-Browser Testing for WebSockets | MyThinkPond

The traditional way to test for websockets is this:

[sourcecode] function WebSocketTest() { if (“WebSocket” in window) { alert(“Browser supports websocket”); } else { alert(“Browser does not support websocket”); } } … Run WebSocket test [/sourcecode]

Although the above example will be technically correct for modern browsers it is important to consider some of the “experimental” implementation of this feature in earlier FireFox (Mozilla) browsers.

In FireFox (Mozilla), experimental features (until they graduate) gets added with a prefix of “Moz”. This has been done for quite some time. So either a feature graduates from the Mozilla academy (which means that they no longer have the prefix of “Moz”) or they may get removed in future releases. This has been the case for WebSockets.

So how do we test for both WebSockets and MozWebSocket? Here’s how:


var wssupport = “MozWebSocket” in window ? ‘MozWebSocket’ : (“WebSocket” in window ? ‘WebSocket’ : null);

function WebSocketTest() { if (support == null) { alert(“Browser supports websocket”); } else { alert(“Browser does not support websocket”); } }

//To create a websocket using this strategy use the following: var ws = new window[wssupport](“wss://your-domain/path”); //Use “wss://” for secure-sockets or use “ws://” for plain-sockets w/o encryption. … Run WebSocket test [/sourcecode]

The variable “wssupport” contains an elaborate nested-if-else statement. It first checks for “MozWebSocket”, if found, then returns  “MozWebSocket” as a string. Else it tests for “WebSocket”, if found returns “WebSocket” as a string else returns “null”.

Here is a useful URL for determining Browser Support for Web Sockets:

If you have found this article useful, consider subscribing to my posts and/or share them.

Venkatt Guhesan avatar
About Venkatt Guhesan
Enterprise Software Architect currently working at DataDirect Networks developing a highly scalable monitoring solution called DDN Insight. My passions include all things Open Source including Linux (CentOS, Red Hat, Gentoo, Open Stack, Docker & Ubuntu), embedded ARM processors and microcontrollers (Arduino, UDOO, Cubieboard, BeagleBoard, OnionIO, TI's Zigbee). Coming from an Electrical and Computer Engineering background, working in developing and designing enterprise - distributed, highly scalable software requires a unique set of software skills with a good understanding of the hardware. This makes his work challenging and interesting. In his free time, he spends his time with his family and two children. He also enjoys researching on topics including - world ancient history and yoga. Visit the 'About' section for more details.
comments powered by Disqus