Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Cross-Browser Testing for WebSockets

DZone's Guide to

Cross-Browser Testing for WebSockets

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

The traditional way to test for websockets is this:

function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     alert("Browser supports websocket");
  }
  else
  {
     alert("Browser does not support websocket");
  }
}
...
<a href="WebSocketTest()"">Run WebSocket test</a>

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) get 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.
...
<a href="WebSocketTest()"">Run WebSocket test</a>

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:

https://developer.mozilla.org/en-US/docs/WebSockets#Browser_compatibility

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Venkatt Guhesan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}