Question

I am able to use a NowJS chat when accessing a file with the android browser, but when the same code is executed within phonegap the messages don't get received or sent.

Has anybody been able to successfully use nowJS or sockets with phonegap/cordova?

Code working on web browsers, FF, Chrome, and android native browser, however not phonegap

$(document).ready(function(){
        now.receiveMessage = function(id, name, message, timestamp){
            $("#messages").append("<br>" + id + ' ' + name + ": " + message + ' ' + timestamp);
        };

        // Send message to people in the same group
        $("#send-button").click(function(){
            now.distributeMessage(room, $("#text-input").val());
            $("#text-input").val("");
        });

        now.name = 'Guest '+Math.floor(Math.random() * 1000 % 5 + 2);

        // on establishing 'now' connection, set server room and allow message sending
        now.ready(function(){
        room = location.hash.replace('#', '');

            if (!room) {
            alert("Please specify a room");
            throw "";
            }

            now.changeRoom(room);

            // Connection established and room set; allow user to start sending messages
            $("#send-button").removeAttr('disabled');
        });
    });
Was it helpful?

Solution

It may be that the fallback mechanism in Now.js isn't working in the WebView when running in PhoneGap. If they use Flash Fallback then you need to enable plugins. It looks like this is going to be enabled by default very soon: https://github.com/apache/incubator-cordova-android/pull/18

I recently created a Pusher for PhoneGap on Android starter project and instead of enabling plugins and relying on Flash I instead exposed a WebSocket object running in Java to the WebView JavaScript runtime. I really like this approach as it removes the Flash problem altogether. Maybe this is something that you could do in your android app?

You can see starter project which includes all the necessary code to expose the WebSocket object to the WebView JS runtime here (just replace the pusher.min.js include with the now.js one):

And information on the PhoneGap WebSocket Android support via the README: https://github.com/pusher/pusher-phonegap-android#native-websocket-support

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top