Reputation: 1594
I have made up a cordova project which will be intensively using websockets. I have set up a few java classes which will implement websockets to the android platform while still be able to use the websockets in javascript in the same way as a native implementation will. That means, i then have a websocket object with its methods onopen
, onmessage
and so on...
Since the mobile safari (iPhone) already supports websockets, i don't have to implement the javascript part again (its only 1 html/css/js source for both platforms). That means i have to write a function which tells me if android is supported.
What i have:
var supportsWebSockets = function() {
if ('WebSocket' in window) {
if (WebSocket.hasOwnProperty('onopen'))
return true;
else
return false;
} else {
return false;
}
}
But that doesnt do it. I then made a script which will output all methods and properties of the WebSocket Object:
var obj = new WebSocket('ws://echo.websocket.org');
var methods = [];
for (var m in obj) {
methods.push(m);
}
document.write(methods.join("<br>"));
That outputs the same properties and methods in android as in mobile safari.
I guess that means, they have reserved the namespaces with empty functions.
How will i then be able to check if WebSockets are supported or not? I dont want to use a User Agent string to identify, since i dont want to modify it again when new version with eventual support are coming.
Weird nobody encountered this problem before..
Any thoughts?
Upvotes: 1
Views: 1818
Reputation: 9706
The other answer would give a false negative in Safari. I think the best approach is a combination of three things:
if ('WebSocket' in window
&& (typeof WebSocket === 'function' || typeof WebSocket === 'object')) {
// supports WebSocket
} else {
// does not support WebSocket
}
Upvotes: 1
Reputation: 3528
Ok so I can see that there are comments with slightly varying correct answers, I personally like to check positively, so would do the following to check if a browser supports WebSockets using JavaScript...
if (typeof WebSocket === "function"){
// implement WebSockets
} else {
// fallback
}
Upvotes: 1