简体   繁体   中英

Check for WebSocket support in native android browser in a cordova project

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 dont 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?

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM