Detect if your browser supports WebSockets

Written by Tony Lea on Sep 25th, 2012 Views Report Post

WebSockets are great for creating a bi-directional connection between the server and the client. It's also great for making some awesome real-time and interactive web apps. The only downfall with WebSockets is that they are not supported by all browsers. So, when the browser does not support WebSockets what do you do from there. Well, you can always use the Socket.IO library for resorting to long-polling if a browser does not support websockets. Here is an excellent resource for seeing which current browsers support WebSockets: http://caniuse.com/websockets

Unfortunately, when falling back to long-polling you may experience some server bottlenecks, because long polling on a lot of concurrent connections can be highly resource intensive.

So, maybe you just need a way to test and see if a browser supports websockets. Well, here is a simple example of how you can detect if WebSockets are supported in Javascript:

if(window.WebSocket){
    // This browser supports websockets
} else {
    // This browser does not support websockets
}

Checkout a demo here

Below is the code used in the demo. Feel free to use it as you wish

<!DOCTYPE html>
<html>
<head>
	
</head>
<body style="text-align:center">
	<h2>Testing if your browser supports WebSockets</h2>
	<div id="supported"></div>
	<script type="text/javascript">
		var message = "WebSockets are not supported";
		if(window.WebSocket){
			message = "WebSockets are supported on your browser";
		}
	
		document.getElementById('supported').innerHTML = message;
	</script>
</body>
</html>

Comments (0)