My WebSocket doesnt work in Opera/Midori - javascript

everyone I'm creating an "Object" to manage all information about my socket connection but I've some problems about browser compatibilities
$(document).ready(function(){
socket.connect();
socket.connection.onopen = function(){
console.log('Connected '+ socket.connection.readyState);
//Show 1 for every browser
};
socket.connection.onmessage = function(event){
console.log('Some message '+event.data);
//Firefox / Chrome Fine
//Midori/Opera doesnt show this message (console)
};
});
var socket ={
dataConnection: {
url:"myURL",
param:"myParam"
},
connection: "",
connect: function(){
try{
this.connection = new WebSocket(this.dataConnection.url+"/"+this.dataConnection.param);
}catch(error){
console.log('Something wrong ' + error.message);
}
}
};
I don't understand Wy It works fine (FF and Chrome), Can you give an advice?

Related

Why Websocket connection is disconneting after sending message on iOS 15 devices?

I am building a website based on web socket communication. Its is working fine until iOS 14 but started breaking from iOS 15. Web socket java script client is able to open connection to server, but upon trying to send a message, the connection is getting closed. Following is my html and JS code.
function start_websocket() {
connection = new WebSocket("wss://localhost/wss/");
connection.onopen = function () {
console.log('Connection Opened');
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onclose = function(){
console.log("Closed");
};
connection.onmessage = function (e) {
console.log("Message Received :" + e.data);
};
}
function myFunction() {
var testText = document.getElementById("testText");
if (testText.value != "" && connection.readyState === connection.OPEN) {
connection.send("Test");
}
}
start_websocket();
myFunction() is an on-click event of a button.
A Java Websocket server is used, which will decode and send the messages based on the Data framing in https://datatracker.ietf.org/doc/html/rfc6455#section-5.
Saw different articles on the Web, but didn't found a solution to this issue. Any suggestions are much appreciated. Looking forward for your answers
Thanks in advance.

Connection has not been fully initialized

In my application the following console error occurs when I navigate to another page.
Uncaught Error: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.
In layout page the scripts are in the following order.
#Styles.Render("~/Content/themes/base/jqueryUi")
#Styles.Render("~/Content/customCss")
#Scripts.Render("~/Scripts/jQuery")
#Scripts.Render("~/Scripts/customScripts")
<script src="/signalr/hubs"></script>
var progressHub = $.connection.parallelProcessing;
var flagDownload = true;
$(function() {
progressHub.client.updateProgresssBar = function(progressPercentage, downloadedSize, totalFileSize) {
debugger
downloadProgress("", "", "");
$("#downloading-progress").dialog("open");
var progressObj = $("#progressBar").data("ejProgressBar");
progressObj.option("text", progressPercentage + " %");
progressObj.option("percentage", progressPercentage);
$(".received").html("(" + downloadedSize + " ");
$(".total-size").html("of " + totalFileSize + ")");
flagDownload = true;
if (progressPercentage == 100)
$("#downloading-progress").dialog("close");
};
progressHub.client.noNetConnection = function() {
if (flagDownload) {
flagDownload = false;
showalertdownload("#Message.Nointernetconnection");
}
};
progressHub.client.closeProgressDialog = function() {
$("#downloading-progress").dialog("close");
enableEvents();
};
$.connection.hub.start().done(function () {
});
});
function updateConnectionID() {
progressHub.server.updateConnectionID();
}
Please let me know is ther any solution to resolve this issue.Thanks in advance.
Basing my answer on your error message, it seems you are trying to access your connection or hub without waiting for it to be initialized.
Taken from the ASP.NET SignalR Github wiki:
// This callback will only run once
connection.start().done(function() {
console.log("connection started!");
});
A more complete and detailed example to be found on ASP.NET website

Websockets not working

I have the following code in javascript:
function ConnectWebSocket() {
if ("WebSocket" in window) {
myWebsocket = new WebSocket("wss://myserver/mychannel");
myWebsocket.onmessage = function(evt) {
alert("onmessage");
}
myWebsocket.onopen = function() {
alert("onopen");
myWebsocket.send("msg0");
myWebsocket.send("msg1");
myWebsocket.send("msg2");
}
myWebsocket.onclose = function() {
alert("onclose");
ConnectWebSocket();
}
} else {
// Do something if there is no websockets support
}
}
ConnectWebSocket();
The problem is that in Firefox, the connection is closed after sending the messages, and reopened due to the command on the onclose event. If I try to send only one message on onopen, the connection keeps opened, but if I try to send more than one message, the connection shut down. This issue appears only in Firefox, not in Chrome, not in IE, not in Safari.
Can someone help me? In other browsers like IE or Chrome, once the connection is created, it keep opened until I leave the page. I have the 40.0.3v of Firefox
Try this example:
var url = "ws://echo.websocket.org";
if (!window.WebSocket) alert("WebSocket not supported by this browser");
var myWebSocket = {
connect: function () {
var location = url
this._ws = new WebSocket(location);
this._ws.onopen = this._onopen;
this._ws.onmessage = this._onmessage;
this._ws.onclose = this._onclose;
this._ws.onerror = this._onerror;
},
_onopen: function () {
console.debug("WebSocket Connected");
},
_onmessage: function (message) {
console.debug("Message Recieved: " + message.data);
},
_onclose: function () {
console.debug("WebSocket Closed");
kiosk.connect();
},
_onerror: function (e) {
console.debug("Error occured: " + e);
},
_send: function (message) {
console.debug("Message Send: " + message);
if (this._ws) this._ws.send(message);
}
};
myWebSocket.connect();
setInterval(function() {
myWebSocket._send('msg1');
}, 5000);
Here is a JSFidlle
It may be that your support var is not behaving as you expect. The following code works in FireFox without closing the connection:
function ConnectWebSocket() {
if ("WebSocket" in window) {
myWebsocket = new WebSocket("ws://echo.websocket.org/");
myWebsocket.onmessage = function (evt) {
alert("onmessage");
}
myWebsocket.onopen = function () {
alert("onopen");
myWebsocket.send("a test message");
}
myWebsocket.onclose = function () {
alert("onclose");
ConnectWebSocket();
}
} else {
// Do something if there is no websockets support
}
}
ConnectWebSocket();
Example Fiddle
You can use the tool on Websocket.org to make sure websockets are
working correctly in your browser.
Or (although your issue is with FF) you can use the steps listed
here to debug websockets.
Try it.
var WS = window.WebSocket || window.MozWebSocket;
if (WS){
var websocket = new WS("wss://myserver/mychannel");
}

Cordova PushNotification onNotificationGCM is not called

I am doing pushnotification for both Android/IOS.
I have used a cordova push-plugin https://github.com/phonegap-build/PushPlugin, it seems to work great.
Info : I'm on a AngularJS project.
In my NotificationHelper factory i have this init method:
helper.init = function() {
// Instanciate push plugin notification
var pushNotification = window.plugins.pushNotification;
var errorHandler = function(error) {
logger.debug('errorHandler = ' + error);
};
if ($rootScope.isAndroid()) {
var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
pushNotification.register(function(result) {
logger.debug('successHandler = ' + result);
}, errorHandler, {
'senderID' : senderId,
'ecb' : 'onNotificationGCM'
});
}
};
I also defined those methods on mains.js :
var onNotificationGCM = function(event) {
// call back to web service in Angular.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var service = injector.get('NotificationHelper');
service.onNotificationGCM(event);
};
It's a trick to call angularJS factory from main javascript.
'onNotificationGCM' call the 'NotificationHelper.onNotificationGCM' method :
helper.onNotificationGCM = function(e) {
switch (e.event) {
case 'message':
// Notification happened while app was in the foreground
if (e.foreground) {
logger.debug('[notification] [message] Foreground : ' + JSON.stringify(e));
} else { // Notification touched in the notification tray
logger.debug('[notification] [message] Background : ' + JSON.stringify(e));
if (e.coldstart) {
// App was not running and user clicked on notification
} else {
// App was running and user clicked on notification
}
}
decriptPayloadNotification(e.payload);
break;
case 'registered':
logger.debug('[notification] [registered] : ' + JSON.stringify(e));
if (e.regid.length > 0) {
registerUser(e.regid, 'gcm');
}
break;
case 'error':
logger.debug('[notification] [error] : ' + JSON.stringify(e));
break;
default:
logger.debug('[notification] [default] : Unknown, an event was received and we do not know what it is : ' + JSON.stringify(e));
break;
}
};
During the first use, everything work good :
'Registered' event is received
Notifications are received
When i'm on foreground I receive 'message' event :
NotificationHelper: [notification] [message] Foreground : {"event":"message","from":"847593779913","message":"Agenêts 23/03 10h\r\n","collapse_key":"do_not_collapse","foreground":true,"payload":{"lt":"school","lv":"E1154","notId":"35429","title":"Agenêts le 23/03/2015","message":"Agenêts 23/03 10h\r\n"}}
When i'm on background, if i receive notif and touche it on notification tray, I receive 'message' event :
NotificationHelper: [notification] [message] Background : {"event":"message","from":"847593779913","message":"la piscine sera fermée 1 journée pour raison technique","coldstart":false,"collapse_key":"do_not_collapse","foreground":false,"payload":{"lt":"swimming pool","lv":"E114","notId":"29869","title":"23/04/2015 fermeture de la piscine","message":"la piscine sera fermée 1 journée pour raison technique"}}
BUT, if i kill my app, everything stop to work.
If i restart app, i will not receive anymore 'message'event and 'onNotificationGCM' will not be called.
I founded some articles speaking about this problem, but without success :
Stackoverflow : Phonegap PushNotification to open a specific app page
Does anyone has an idea about this problem ?
If you are using node-gcm as push notification server side I hope this might help for your question:
things to check:
use adb logcat from console and check your device logs to see if your device receives any notification (you should see some logs from gcmservices if you receive). I believe you should see some logs because otherwise you probably wouldn't get any notification when the app is on foreground either.
check if you add "title" and "message" keys on your message data (this draw me crazy before)
check if delayWhileIdle parameter is false
sample message variable and method i am using is below:
var pushAndroidSender = new gcm.Sender('Your GoogleApi Server Key Here');
var message = new gcm.Message({
collapseKey: 'demo',
delayWhileIdle: false,
timeToLive: 3,
data: {
"message":"What's up honey?",
"title":"Come on"
}
});
pushAndroidSender.send(message, registrationIds, function(err, result) {
if (err) {
console.error("this is an error: " + err);
} else {
console.log("this is a successful result:" + result);
}
});
I was asking myself why it worked correctly the first time and not the following times...and i had this idea :
maybe callback function is subscribed to plugin first time but not the next times.
And this is exactly the source of my problem. I call "pushNotification.register" only one time to init plugin and get ids...
But the next time I launch app, i don't instanciate again the plugin, so pushplugin don't know which method to call in callback request.
So answer is : Call "pushNotification.register" in each application launch !
In my code, i have to call method below on each "deviceready" event :
helper.init = function() {
// Instanciate push plugin notification
var pushNotification = window.plugins.pushNotification;
var errorHandler = function(error) {
logger.debug('errorHandler = ' + error);
};
if ($rootScope.isAndroid()) {
var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
pushNotification.register(function(result) {
logger.debug('successHandler = ' + result);
}, errorHandler, {
'senderID' : senderId,
'ecb' : 'onNotificationGCM'
});
}
};

How to enable OpenTok Plugin for Internet Explorer

I am trying to implement open tok for my video chat application.
I am using opentok.min.js v 2.2.9 with php SDK. It is working fine with google chrome and firefox.
According to their announcements, it should work in IE with 32 bit OS.
https://tokbox.com/opentok/libraries/client/js/release-notes.html
But it is not working for me at any version of IE.
Anybody knows how to implement it for IE?
// Detect whether this browser is IE
var isNotIE = function isIE() {
var userAgent = window.navigator.userAgent.toLowerCase(),
appName = window.navigator.appName;
return !(appName === 'Microsoft Internet Explorer' || // IE <= 10
(appName === 'Netscape' && userAgent.indexOf('trident') > -1)); // IE >= 11
};
function connect() {
if (isNotIE() && OT.checkSystemRequirements()) {
session = OT.initSession(apiKey, sessionId);
sendMessage("Session has initialized. Connecting to session ... ");
session.on({
streamCreated: function(event) {
sendMessage("New stream in the session: " + event.stream.streamId);
var parentDiv = document.getElementById(subscriberElement);
var replacementDiv = document.createElement("div"); // Create a div for the publisher to replace
replacementDiv.id = "opentok_subscriber";
parentDiv.appendChild(replacementDiv);
subscriber = session.subscribe(event.stream, replacementDiv, subscriberProperties, function(error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
}
});
},
streamDestroyed: function(event) {
sendMessage("Stream stopped streaming. Reason: " + event.reason)
},
signal: function(event) {
sendMessage("Signal sent from connection " + event.from.id);
// Process the event.data property, if there is any data.
}
});
session.connect(token, function(error) {
if (error) {
sendMessage("Error connecting: ", error.code, error.message);
} else {
sendMessage("Connected to the session successfully.");
displayBtn('connected');
}
});
}else{
sendMessage("What Should I do if it is IE?? :(");
}
}
function sendMessage(message) {
message = '<br>' + message;
$("#statusbox").append(message);
}
Now that IE versions 8-11 are supported by the plugin, you shouldn't need to switch on the isNotIE() && OT.checkSystemRequirements() condition, you can just use the same code path for all of those browsers.
It may still be a good idea to detect IE versions that are outside that range to let the user know that the feature of your application that uses OpenTok is not supported with some suggestions to upgrade/install.
Otherwise, one code suggestion: In the streamCreated event handler, rather than using 4 lines of code to create a new DOM element and then add it to a container, you can use the insertMode: "append" option. This works for both Publishers and Subscribers.
Before:
var parentDiv = document.getElementById(subscriberElement);
var replacementDiv = document.createElement("div"); // Create a div for the publisher to replace
replacementDiv.id = "opentok_subscriber";
parentDiv.appendChild(replacementDiv);
subscriber = session.subscribe(event.stream, replacementDiv, subscriberProperties, function(error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
}
});
After:
subscriber = session.subscribe(event.stream, document.getElementById(subscriberElement), { insertMode: "append" }, function (error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
// Set the ID of the DOM element if thats used elsewhere in the code
subscriber.element.id = "opentok_subscriber";
}
});

Categories